MapBox Reverse Geocoding Without Map in Javascript

1.2k views Asked by At

I'm attempting to retrieve places info using the MapBoox JS API.

I currently have forward geocoding working well without a map and now looking to do the reverse.

The docs and other information I've gathered seems to suggest that the two are essentially the same, but the big difference being how the results are returned.

navigator.geolocation.getCurrentPosition(function(position) {
    const latitude  = position.coords.latitude;
    const longitude = position.coords.longitude;

    mapboxgl.accessToken = 'pk.mycode';
        var reverseGeocoder = new MapboxGeocoder({
        id : 'myid',
        accessToken: mapboxgl.accessToken,
        location: [latitude, longitude],
        callback: 'callback',
        types: 'country,region,place,postcode,locality,neighborhood',
        reverseGeocode: true
    });

    function callback(pos, result) {
        console.log(pos, result);
    }

});

Forgive me if the callback is just totally wrong, but this is how I thought it should work. With no direct example in the API doc I wasn't sure what arguments or how many should or could be passed but it made sense to follow the reverseQuery().

I found the reverseGeocode argument/option from GitHub issue/commit on reverse Geocoding example.

There are no errors in console but as the docs suggest this functions return is not useful. I don't know how to use the callback as the doc suggest to retrieve information from the result.

1

There are 1 answers

3
Steve Bennett On

The normal way to use Mapbox's reverse geocoding service is to call the API directly:

https://docs.mapbox.com/api/search/#reverse-geocoding

You could do that using a library such as axios:

axios.get('https://api.mapbox.com/geocoding/v5/mapbox.places/-73.989,40.733.json?access_token=YOURTOKEN')
.then(({data}) => {
    console.log(data);
});