Как отцентрировать маркер на карте Mapbox GL JS при нажатии? - PullRequest
0 голосов
/ 24 марта 2020

У меня есть карта с динамическим c количеством пользовательских маркеров. Чтобы мой пользовательский интерфейс работал правильно, мне нужно отцентрировать маркер / карту при нажатии на пользовательский маркер.

1 Ответ

1 голос
/ 26 марта 2020

Не может быть "правильным путем" или самым элегантным, но вот что я в итоге сделал ...

//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
    });
});
...