在vue项目中使用Vue2Leaflet地图组件

在vue项目中使用Vue2Leaflet地图组件

最近遇到一个项目,使用的是Vue2Leaflet地图插件,咱们简单地介绍一下怎么使用吧.详细内容可以看官方文档.

1.安装插件

由于项目中会使用到vue2-leaflet和leaflet,因此需要安装2个插件

npm install vue2-leaflet --save
npm install leaflet --save

2、添加LMap 组件

<l-map style="width: 100%; height: 600px;" :zoom="zoom" :center="center">
  <l-tile-layer :url="url" :attribution="attribution"></l-tile-layer>
  <l-marker :lat-lng="marker">
    <l-popup :content="text"></l-popup>
  </l-marker>
</l-map> 

3.引入需要的组件

import { LMap, LTileLayer, LMarker, LPopup } from 'vue2-leaflet';
export default {
  name: 'VueLeaflet',
  components: {
    LMap,
    LTileLayer,
    LMarker,
    LPopup
  },
  data () {
    return {
      zoom: 13,
      center: L.latLng(47.413220, -1.219482),
      url: 'http://{s}.tile.osm.org/{z}/{x}/{y}.png',
      attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
      marker: L.latLng(47.413220, -1.219482), //添加的标签
      text: 'this is a marker'
    }
  }
}

保存后就可以在浏览器里看到地图了,但是看起来乱七八糟的,跟想象中的不一样,是因为没有引入Leaflet的样式文件。

4.引入 leaflet.css

在main.js文件中添加:

import 'leaflet/dist/leaflet.css';

添加后,地图是正常显示了,但是你会发现,我明明加了一个marker,为什么没有看到呢?打开控制台就明白了,marker图标没有被正确加载。

5.修改icon路径

在main.js文件中添加:

delete L.Icon.Default.prototype._getIconUrl;
L.Icon.Default.mergeOptions({
  iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png'),
  iconUrl: require('leaflet/dist/images/marker-icon.png'),
  shadowUrl: require('leaflet/dist/images/marker-shadow.png'),
});

效果图:
在这里插入图片描述
希望对你有帮助.

猜你喜欢

转载自blog.csdn.net/weixin_46995731/article/details/110438373