I am trying to make a web app where the user can click a point and I can get the closest address to the point. This example from the documentation looks pretty close to what I want to do, except it the queryRenderedFeatures call doesn't seem to return the physical address of any features. What is the best way to get the physical address from a clicked point?
Here is my code:
map.on("click", (e) => {
const features = map.queryRenderedFeatures(e.point);
const displayProperties = [
"type",
"properties",
"id",
"layer",
"source",
"sourceLayer",
"state",
];
const displayFeatures = features.map((feat) => {
const displayFeat = {};
displayProperties.forEach((prop) => {
displayFeat[prop] = feat[prop];
});
return displayFeat;
});
console.log(displayFeatures);
});
You can't get the street address from the queryRenderedFeatures function. However, you can get the coordinates of the point clicked:
map.on("click", (e) => {
mapClickFn(e.lngLat);
});
From these coordinates, you need to get a street address. This is called "reverse geocoding" and can be done using the Mapbox API:
function mapClickFn(coordinates) {
const url =
"https://api.mapbox.com/geocoding/v5/mapbox.places/" +
coordinates.lng +
"," +
coordinates.lat +
".json?access_token=" +
YOUR_ACCESS_TOKEN +
"&types=address";
$.get(url, function (data) {
if (data.features.length > 0) {
const address = data.features[0].place_name;
console.log(address);
} else {
console.log("No address found");
}
});
}
The term for finding the nearest address to a point is "reverse geocoding". You could use Mapbox's API for this, but there are many others, too.
There is no need to use queryRenderedFeatures here.