如何在点击时在Mapbox GL JS地图上居中标记



我有一个带有动态自定义标记的映射。为了使我的UI正常工作,当您单击自定义标记时,我需要将标记/贴图居中。

可能不是"正确的方式"或最优雅的方式,但以下是我最终所做的。。。

//I have this run inside a loop that creates the markers.
//create marker element
var el = document.createElement("div");
el.className = "marker link";
//create the marker object and popup object
let tmpMarker = new mapboxgl.Marker(el);
let tmpPopUp = new mapboxgl.Popup() 
.setHTML('your popup html goes here');
// I "stuffed" the marker object as a property on the elment ( so I can retrieve it later on click)
el.markerInstance = tmpMarker;
//set the coordinates, add the popup and add it to the map.
tmpMarker
.setLngLat([data.coordinates.longitude, data.coordinates.latitude])
.setPopup(tmpPopUp)
.addTo(map);
// add a click listener to the "marker" element
el.addEventListener("click", e => {
// here's where I can use the "markerInstance" I added earlier to then expose the getLngLat
let coords = e.target.markerInstance.getLngLat();
//tell the map to center on the marker coordinates
map.flyTo({
center: coords,
speed: 0.2
});
});

Mapbox GL JS文档有两个例子:

  • https://docs.mapbox.com/mapbox-gl-js/example/flyto/
  • https://docs.mapbox.com/mapbox-gl-js/example/jump-to/

在我的项目中使用了react映射gl。

用解决了我的问题

const mapRef = useRef(null)
useEffect(() => {
if (mapRef.current) {
property.map(({ laty_decimal, longx_decimal }) =>
mapRef.current?.setCenter({
lat: laty_decimal,
lng: longx_decimal,
})
);
}
}, [property]);

这样,只要坐标发生变化,它就会更新,希望这对有帮助

阅读更多

最新更新