Skip to content
Advertisement

Mapbox GL JS find closest address to clicked point

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement