How do I use:

L.GeometryUtil.closest(myMap, coords, b)

to find the closest point in a geojson point layer in leaflet. I have tried several things. And the error I receive is: Uncaught TypeError: Cannot read property '0' of undefined

    let coords=[]; 

    let closetPt;

    lyrPts = L.geoJSON.ajax('Geojson/pts.geojson',{
        pointToLayer: function (feature, latlng) {
        return L.circleMarker(latlng, markerPts);
        onEachFeature: function (feature) {
      return layer.feature.properties.Layer

    closestPt = L.GeometryUtil.closestLayer(myMap, coords, [-40.5512, 80.9454]);

This part now works when I take out closestPt and put it in a callback.

Is it possible to now automatically open the popup of this closest marker?

I want to use it so that as you are within a distance X of a point, its popup will be displayed.


2 Answers 2


Race condition. coords is an empty array when L.GeometryUtil.closest() runs.

Be sure to wait until the remote GeoJSON file is loaded first.


Since L.GeometryUtil.closest works on either of Array.<L.LatLng> | Array.<Array.<L.LatLng>> | L.PolyLine | L.Polygon you will have to pass an array of the coordinates of the GeoJSON point layer to it.

The following code gets an array of points from the point layer (getLayers()) and stores their coordinates in coordinates_array, which can be used in L.GeometryUtil.closest:

const coordinates_array = bicycle_layer.getLayers().map(l => l.feature.geometry.coordinates)
let closest_latlng = L.GeometryUtil.closest(map, coordinates_array, [-40.5512, 80.9454])

closest_latlng then contains: Object { lat: -85.05112877979998, lng: 39.75028330000001, distance: 825385.8575732928 }

Here is a jsfiddle: https://jsfiddle.net/newluck77/p17x28Lz/

  • getLayers() returns an empty array for my geojson layer Jan 22, 2019 at 17:21
  • Appears to be something wrong with my array. Is there a way to check its validity? Jan 22, 2019 at 17:42
  • 1
    I think this is because of a race condition (ajax is asynchronous after all) and getLayers is called before the data is loaded. You can try something like lyrPts.on('add', e => e.target.getLayers()) //fires when layer is added to the map Jan 22, 2019 at 18:24
  • Any ideas on how I would have the closest point automatically open as a popup when I am within a distance of X meters of it? Thanks Jan 24, 2019 at 8:20
  • I think that's for a new question: gis.stackexchange.com/questions/ask Jan 24, 2019 at 12:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.