JavaScript: using geolocation on maps

JavaScript: using geolocation on maps

In this article we're going to show the current user's position on a map using JavaScript and the geolocation API.

In this article we're going to show the current user's position on a map using JavaScript and the geolocation API.

The geospatial coordinates sent through an HTTP request are stored on the client side in the navigator.geolocation object. When you invoke the navigator.geolocation.getCurrentPosition() method, browsers ask for user permission to allow the sharing of the relevant information contained in the returned object, namely latitude, longitude and accuracy.

To get this object, we can write the following code.

const getCoords = () => {
    return new Promise((resolve, reject) => {
        if(!navigator.geolocation) {
            reject({error: 'Not supported'});
        }
        navigator.geolocation.getCurrentPosition(pos => {
            const latitude = pos.coords.latitude;
            const longitude = pos.coords.longitude;

            resolve({
                lat: latitude,
                lng: longitude
            });

        });
    });
};

Once we get the coordinates, we can use them to display the user's position on a map using a JavaScript API such as Google Maps or Mapbox.

It's simply a matter of creating a new map instance using the coordinates obtained earlier and adding a marker to it.

const createMap = async () => {
    try {
       const coords = await getCoords();
       const {lat, lng} = coords;

       mapboxgl.accessToken = 'access_token';

        const mapInstance = new mapboxgl.Map({
            container: 'map',
            center: [0, 0],
            style: 'mapbox://styles/mapbox/streets-v11',
            zoom: 1
        });
        const marker = new mapboxgl.Marker()
            .setLngLat([lng, lat])
            .addTo(mapInstance);
        mapInstance.addControl(new mapboxgl.NavigationControl());
    } catch(err) {
        console.log(err);
    }
};

You can see the above code in action on the following page.