Get Current Center Position Mapbox GL JS
Asked Answered
S

2

7

Looking for a way to get the current coordinates of the center of a map using Mapbox GL JS the same way they do on Mapbox Studio (see below)

Mapbox Studio Screenshot

Thanks

Sialoid answered 20/2, 2018 at 21:22 Comment(0)
E
11

The Map#getCenter method returns the coordinates of the center of the map.

Eustacia answered 21/2, 2018 at 19:2 Comment(0)
Y
3

To get the current center position:


map.current.getCenter();
    // return => {lat: 42.5232 , lng: -70.5552}

This is with React => but if you want to get the current position always that the map change, so added this method inside useEffect:


    useEffect(() => {
      if (!map.current) return; // wait for map to initialize
      map.current.on('move', () => {
      setLng(map.current.getCenter().lng.toFixed(4));
      setLat(map.current.getCenter().lat.toFixed(4));
      setZoom(map.current.getZoom().toFixed(2));
      });
    });

Dos getCenter REACT

Yseulta answered 28/2, 2023 at 20:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.