问题: 层级小的时候点击确实是在线上,但是当放大后,marker就不在线上了。
原因:
层级小的时候点击的经纬度,位置是眼睛看到的, 放大后就不是理想要的位置,这时候跟标注的偏移是没有关系的,因为我们鼠标点的位置就是所展示的。如果我们地图放的很大再去点,这时候的maker 就是非常准确的了。
解决思路:
采用turf的 nearestPointOnLine 方法, 计算获取点距离线图层的交点。
代码片段:
drawa(){
// 线:坐标点
var latlngs = [
[31.537628173828125,121.190185546875],
[30.878448486328125,121.19430541992188],
[30.839996337890625,121.92901611328125]
];
let map = this.map; //获取map地图
let lineLayer = L.featureGroup([]) // 创建线图层
map.addLayer(lineLayer)
// 绘制且添加
var polyline = L.polyline(latlngs, {color: 'red'}).addTo(lineLayer);
// 跳到线的范围
//map.fitBounds(polyline.getBounds());
lineLayer.on("click",function(e){
console.log(e);
var Icon = L.icon({
// iconUrl:require(`../../../assets/images/bigscreen/red.png`),
iconUrl:require(`./abc.png`),
iconSize: [50, 50], // size of the icon
// 左移 上移
iconAnchor: [25, 49], // 偏移量
});
let latlng = e.latlng;
let linejson = e.layer.toGeoJSON(); //获取线图层点集
let pt = turf.point([latlng.lng, latlng.lat], {"marker-color": "F00"});
// 计算交点
let snapped = turf.nearestPointOnLine(linejson, pt, {units: 'kilometers'});
console.log("snapped",snapped)
let center = snapped.geometry.coordinates;
console.log("center",center);
L.marker([center[1],center[0]], { icon: Icon }).addTo(map);
})
},
实现结果:
无论地图放多大,点始终在线上,因为绘制的经纬度就和线的交点。
随笔小记(来源公司大佬)