2

I have a collection of geoJSON LineString objects and need to determine which is closest to a point. I don't have much experience with Mongo DB, but have used the $geoNear to find closest points. Is there a way to adapt this to work with a collection of LineStrings?

Example collection:

{
    "_id": ObjectId("5ee3e2deee404124a8ba4382"),
    "geoJSON": {
         "type": "Feature",
         "geometry": {
            "type": "LineString",
            "coordinates": [
                [
                    -85.5,
                    31.0
                ],
                [
                    -85.6,
                    31.0
                ]
            ]
        }
    }
}
{
    "_id": ObjectId("5ee3e2deee404124a8ba4383"),
    "geoJSON": {
         "type": "Feature",
         "geometry": {
            "type": "LineString",
            "coordinates": [
                [
                    -85.55,
                    31.5
                ],
                [
                    -85.6,
                    31.5
                ]
            ]
        }
    }
}
{
    "_id": ObjectId("5ee3e2deee404124a8ba4384"),
    "geoJSON": {
         "type": "Feature",
         "geometry": {
            "type": "LineString",
            "coordinates": [
                [
                    -85.5,
                    32.0
                ],
                [
                    -85.6,
                    32.0
                ]
            ]
        }
    }
}

I'd like to search this collection to determine which line is closest to the point [-85.55, 31.77]. This should return the third line (blue line in the image below). Is there a way to do this efficiently in MongoDB?

Plot

MRip
  • 21
  • 3
  • The MongoDB documentation is not 100% clear for this item, but it looks like `$geoNear` supports only difference between 2 **points**. Otherwise you would have the option to calculate the distance for end-points, the middle or any point at the line. – Wernfried Domscheit Dec 22 '20 at 17:50
  • I guess you have to use a 3rd party library for this, e.g. [turfjs](https://turfjs.org/). The needed operation would be `nearestPoint` or `nearestPointOnLine` – Wernfried Domscheit Dec 22 '20 at 17:58

0 Answers0