Search code examples
mapboxmapbox-gl-jsmapbox-gl

Getting user location on opening map in mapbox


Hey guys how do i get the user location in mapbox as soons as the component with mapbox map is rendered.

I have seen in their documentation they have provided an option like

this.map.addControl(
      new mapboxgl.GeolocateControl({
        positionOptions: {
          enableHighAccuracy: true,
        },
        trackUserLocation: true,
      }),

    );

which does that, after clcking on the location symbol it shows my current location, but is there any way i could do it intially ? without clicking on location button the map should show the user location


Solution

  • You should use the map.flyTo() method coupled with map.on('load') from mapbox.

    map.on('load', function () {
        map.flyTo({
           center: [
              -74.5 + (Math.random() - 0.5) * 10, // Example data
              40 + (Math.random() - 0.5) * 10 // Example data
           ],
           essential: true // this animation is considered essential with respect to prefers-reduced-motion
        });
    }
    

    As you notice you need the coordinates of the user in order to use the flyTo function.

    You have two alernatives to get them:

    1. User has authorized browser location -> use the browser location

    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        coordinates = [position.coords.latitude, position.coords.longitude];
      });
    }
    

    2. User hasn't authorized browser location -> use an IP geolocation API

    You could use an IP geolocation api like Abstract to get your visitors location:

    $.getJSON("https://ipgeolocation.abstractapi.com/v1/?api_key=**********", function(data) {
           console.log(data.longitude);
           console.log(data.latitude);
           coordinates = [data.longitude,data.latitude]
       })
    

    You could then load the map.on('load') function written above and pas the coordinates for the "center" key.