Aaron Mcguire
Aaron Mcguire

Reputation: 143

How to center marker on Mapbox GL JS map on click?

I have a map with a dynamic amount of custom markers. For my UI to work properly, I need to center the marker/map when you click on the custom marker.

Upvotes: 0

Views: 5522

Answers (3)

emekaokoli
emekaokoli

Reputation: 165

used react-map-gl for my project.

Solved mine with this

  const mapRef = useRef(null)

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

this way whenever the coordinates change it'll update, hope it helps

read more

Upvotes: 0

Aaron Mcguire
Aaron Mcguire

Reputation: 143

Might not be the "right way" or most elegant but here's what I ended up doing...

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

Upvotes: 2

Related Questions