Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Mapbox Geocoding API in JavaScript to reverse geocode a point?

I have read a lot of SO questions and answers and looked at the Mapbox documentation but I can't see a simple example of how to reverse geocode from a latitude/longitude point. The example only shows the URL to use to make a query but presumably there's a way to do it using the MapboxGeocoder object?

So, here, what would I use to display the reverse geocode for lat/long when the user clicks on the map?

var map = new mapboxgl.Map({
  container: document.getElementsByClassName("js-map")[0],
  center: [0, 51],
  style: "mapbox://styles/mapbox/streets-v11",
  zoom: 11
});

map.on("click", function(ev) {
  // 1. Reverse geocode `ev.lngLat.lat` and `ev.lngLat.lng`
  // 2. Do something with the result.
});
like image 765
Phil Gyford Avatar asked Mar 03 '26 23:03

Phil Gyford


1 Answers

You could use the Mapbox SDK for JS which is a wrapper around the rest API.

<script src="https://unpkg.com/@mapbox/mapbox-sdk/umd/mapbox-sdk.min.js"></script>
var mapboxClient = mapboxSdk({ accessToken: mapboxgl.accessToken });
mapboxClient.geocoding
  .reverseGeocode({
    query: "lng,lat"
  })
  .send()
  .then(function(response) {
    if (
      response &&
      response.body &&
      response.body.features &&
      response.body.features.length
    ) {
      var feature = response.body.features[0];
    }
  });

The MapboxGeocoder plugin for Mapbox GL JS is to provide an out of the box search box interface, not for calling the API directly.

like image 86
AndrewHarvey Avatar answered Mar 06 '26 13:03

AndrewHarvey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!