Reputation: 1119
I have created a MapboxGeocoder
object in my code and I'm curious if I can access/use it to reverse geocode elsewhere in the code. This, in an effort to get a formatted address from coords.
I created an object like so:
const address = new MapboxGeocoder({
accessToken: mbat,
mapboxgl: mapboxgl,
container: 'geocoder',
countries: "us",
bbox: [-83.726807, 31.784217, -78.013916, 35.415915],
reverseGeocode: true,
}).on("result", function (result) {
console.log(result);
});
I also have the GeolocateControl
object in my code and I'm creating it like so:
map.addControl(
new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
// When active the map will receive updates to the device's location as it changes.
trackUserLocation: true,
// Draw an arrow next to the location dot to indicate which direction the device is heading.
showUserHeading: true
}).on('geolocate', (e) => {
console.log(e)
})
)
My question is, is there a way to access the address
object within the GeolocateControl
event handler to reverse geocode? I am imagining something to this effect:
.on('geolocate', (e) => { console.log(address(e)) })
Upvotes: 1
Views: 446
Reputation: 517
As long as your geocoder instance is in scope, you should be able to use it in the event handler from GeolocateControl
I am not 100% sure about the data
object in the geolocate
callback, so inspect it to see how to pull out the lng/lat coordinates.
const geocoder = new MapboxGeocoder(...)
map.addControl(
new mapboxgl.GeolocateControl({
...
}).on('geolocate', (data) => {
const geocoder.query(`${data.coords[0},${data.coords[1]}`)
})
)
Upvotes: 1