书接上回,继续对leaflet进行操作
一、在地图上打上标记
首先写一个方法,并在init()中使用
methods: {
// 初始化地图
init() {
this.map = L.map("map", { attributionControl: false }).setView(
//可以调节数值的大小来决定地图显示的位置
[35.04656, 104.86254],
5
);
L.tileLayer(
"https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}",
{
maxZoom: 19,
attribution:
'© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
}
).addTo(this.map);
this.addMarker();
},
addMarker() {
//这是需要标记城市的几个坐标
var data = [
{
name: "北京",
coordinates: [39.92, 116.46],
},
{
name: "成都",
coordinates: [30.67, 104.06],
},
{
name: "沈阳",
coordinates: [41.8, 123.38],
},
{
name: "广州",
coordinates: [23.135336, 113.271431],
},
{
name: "南京",
coordinates: [32.04, 118.78],
},
{
name: "武汉",
coordinates: [30.56, 114.34],
},
];
let that = this;
data.forEach(function (item) {
var greenIcon = L.icon({
iconUrl: "http://localhost:8088/image/wjx.png",
iconSize: [25, 25], // size of the icon
});
var marker = L.marker(item.coordinates, { icon: greenIcon }).addTo(
that.map
);
marker.on("click", function () {
that.showMarkerInfo(item.name);
});
});
},
// 五角星消息的点击事件
showMarkerInfo(areaName) {
console.log(areaName);
},
},
效果展示:
二、添加自定义标记
//添加标记
this.marker = L.marker([29.06097, 111.93969]).addTo(this.map);
除了标记之外,还有圆和多边形
//圆
this.circle = L.circle([35.16175, 100.40661], {
color: "red", //颜色
fillColor: "#f03",
fillOpacity: 0.5,//透明度
radius: 500000, // 半径
}).addTo(this.map);
//多边形
this.polygon = L.polygon([
[25.22409, 113.2196],
[28.80135, 120.87902],
[28.74358, 113.543701],
]).addTo(this.map);
三、还可以给标记添加自定义弹窗
//给添加的标记添加弹窗显示
//bindPopup()绑定需要显示的信息 (点击元素后显示标记内容)
// openPopup()自动打开(不需要手动点击就可以出现的)
this.marker.bindPopup("<b>Hello!</b><br>这是标记").openPopup();
this.circle.bindPopup("这是圆的弹窗");
this.polygon.bindPopup("这是多边形的弹窗");
效果展示:
完整代码:
init() {
this.map = L.map("map", { attributionControl: false }).setView(
//可以调节数值的大小来决定地图显示的位置
[35.04656, 104.86254],
5
);
L.tileLayer(
"https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}",
{
maxZoom: 19,
attribution:
'© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
}
).addTo(this.map);
//添加标记
this.marker = L.marker([29.06097, 111.93969]).addTo(this.map);
this.circle = L.circle([35.16175, 100.40661], {
color: "red",
fillColor: "#f03",
fillOpacity: 0.3,
radius: 500000, // 半径
}).addTo(this.map);
this.polygon = L.polygon([
[25.22409, 113.2196],
[28.80135, 120.87902],
[28.74358, 113.543701],
]).addTo(this.map);
//给添加的标记添加弹窗显示
//bindPopup()绑定需要显示的信息 (点击元素后显示的内容)
// openPopup()自动打开(不需要手动点击,直接显示)
this.marker.bindPopup("<b>Hello!</b><br>这是标记").openPopup();
this.circle.bindPopup("这是圆的弹窗");
this.polygon.bindPopup("这是多边形的弹窗");
},
三、事件交互
随机点击地图上的一处,会弹出点击位置的经纬度
onMapClick(e) {
L.popup()
.setLatLng(e.latlng)
.setContent("你点击的经纬度是 " + e.latlng.toString())
.openOn(this.map);
},
//在init中使用该方法
this.map.on('click', this.onMapClick);
效果展示: