Leaflet--自定义Mark的图标

171 阅读1分钟

默认的Mark图标

下载好leaflet包之后,其文件结构如下:

image.png

一般我们需要使用的是leaflet.jsleaflet.cssimages文件夹三个资源,按下载后的相对位置引入我们的代码。

定义默认的mark

const tdt_layer = L.tileLayer('https://t6.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=你的天地图token');
const map = L.map('map', {
    center: [39.5424, 116.2351],
    zoom: 13,
    layers: [tdt_layer]
});
const marker = L.marker([39.5424, 116.2351]);
marker.addTo(map);

没有自定义mark的图标icon所以采用了默认的图标(image文件之下)

image.png image.png

自定义图标iconmarker

image.png

  1. 图标被定义在一个L.icon
const greenIcon = L.icon({
    iconUrl: './icons/leaf-green.png', //图标的位置
    iconSize: [38, 96], // 图标的大小
    iconAnchor: [22, 94], // 图标相对与定位经纬度那个点位的位置
})
  1. icon挂载到mark
const green_marker = L.marker([39.5524, 116.2351], { icon: greenIcon }).addTo(map);

image.png

  1. 绑定一个默认的弹出框
const greenIcon = L.icon({
    iconUrl: './icons/leaf-green.png',
    iconSize: [38, 96], 
    iconAnchor: [22, 94], 
    popupAnchor: [-7, -76] // 弹出框的相对于iconAnchor的位置
})
const green_marker = L.marker([39.5324, 116.2351], { icon: greenIcon }).bindPopup('这是一个绿色的叶片').addTo(map);

image.png