1.首先下载leaflet依赖
npm i leaflet --save
2.然后在页面引入
<script>
import L from "leaflet";
</script>
根据leaflet官网文档实现地图显示
leaflet文档:Documentation - Leaflet - 一个交互式地图 JavaScript 库
完整代码
<template>
<div id="map"></div>
</template>
<script>
import L from "leaflet";
import icon from "leaflet/dist/images/marker-icon-2x.png";
export default {
components: {},
data() {
return {
map: null,
center: [30.524, 119.267],
zoom: 5,
markerUrl: L.icon({
iconUrl: icon,
iconSize: [34, 45],
iconAnchor: [12, 25],
popupAnchor: [1, -34],
shadowSize: [41, 41],
}),
};
},
computed: {},
watch: {},
//生命周期 - 创建完成(可以访问当前this实例)
created() {},
//生命周期 - 挂载完成(可以访问DOM元素)
mounted() {
this.init();
},
methods: {
// 初始化地图
init() {
this.map = L.map("map", {
center: this.center,
zoom: this.zoom,
});
const tiles = L.tileLayer(
"http://{s}.tile.osm.org/{z}/{x}/{y}.png"
).addTo(this.map);
this.map.on("click", (e) => {
console.log("地图点击事件", e);
});
// 画marker
this.drawMarker();
},
drawMarker() {
//模拟数据
let arr = [{ point: [30.524, 119.267] }, { point: [33.834, 119.267] }];
this.gem = [];
for (let i = 0; i < arr.length; i++) {
const marker = L.marker(arr[i].point, { icon: this.markerUrl }).addTo(
this.map
);
this.gem.push(marker);
//监听marker点击事件
marker.on("click", () => {});
// marker绑定气泡框
marker.bindPopup(
`<div><a id='aa' style='color:red'>marker${i}</a></div>`
);
}
},
},
};
</script>
<style lang="scss" scoped>
#map {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
z-index: 0;
}
</style>