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.
});
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.