6

I'm coding an app with Phonegap, which requests user's current position. As an overlay I have loaded a geojson layer. I want the app to automatically extract a value of said layer at the exact location, where the user currently is (without the user manually clicking on the layer).

I've tried Leaflet PIP extension, but couldn't get it to work with leaflet 1.0.3. I've also tried simulating a touch/mouseclick event at screen coordinates, but that didn't work either.

I've found the extension Leaflet.PointInPolygon, which can check, if a point is lying within a polygon. Therefore a transformation from geojson to an array with coords is required.

I wrote the following code to parse my geojson and write it into arrays to add polygon layers to my map (in order to check later, if map.getCenter() coords are within any of these):

var coord = [];
for (var i = 0; i < data.features.length; i++) {
  feat = data.features[i];

  for (var j = 0; j < feat.geometry.coordinates.length; j++) {
    coord = feat.geometry.coordinates[j];

    var polygon = L.polygon(coord, { color: "red" }).addTo(map);
  }
}

I'm facing the prolem now that lat and lon are in the wrong order:

[[10.77932197941255,52.03584196145097],[10.77932197941255,52.03575906909681],[10.779636389761993,52.03575906909681],[10.779636389761993,52.03584196145097],[10.77932197941255,52.03584196145097]]

How can I fix this?

Is there maybe a leaflet extension or javascript framework, which can directly check, if given coordinates are within a geojson object?

1 Answer 1

7

Nothing is in the wrong order. Leaflet uses lat-lng (or northing-easting) whereas GeoJSON uses lng-lat (or easting-northing).

Read https://macwright.org/lonlat/ for some background on the issue.

2
  • ok I should've specified: I simply want to flip my coords or tell leaflet to read them in reverse. Right now my layer is lying next to africa.
    – Revo
    Jun 20, 2017 at 13:50
  • 1
    You can either reverse the coordinates yourself, or use the utility function L.GeoJson.coordsToLatLngs() Jun 20, 2017 at 14:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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