Use Vue2Leaflet map component in vue project

Use Vue2Leaflet map component in vue project

I recently encountered a project that uses the Vue2Leaflet map plug-in. Let's briefly introduce how to use it. For details, please refer to the official documentation .

1. Install the plugin

Since vue2-leaflet and leaflet will be used in the project, two plug-ins need to be installed

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

2. Add LMap component

<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. Introduce the required components

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'
    }
  }
}

After saving, you can see the map in the browser, but it looks messy, which is different from what you imagined, because the Leaflet style file is not imported.

4. Import leaflet.css

In the main.js file add:

import 'leaflet/dist/leaflet.css';

After adding, the map is displayed normally, but you will find that I obviously added a marker, why didn't I see it? Open the console to understand that the marker icon has not been loaded correctly.

5. Modify icon path

In the main.js file add:

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'),
});

Effect picture:
insert image description here
I hope it can help you.

Guess you like

Origin blog.csdn.net/weixin_46995731/article/details/110438373