问题
I need to evaluate the proximity of a Point
to a LineString
using MongoDB.
Because the $near
operator can only compare a Point
to another Point
, I need to generate a polygon out of the LineString
, so I can use the $within
operator. The distance between the LineString and the edges of the polygon should represent the radius I want to search in, such as represented in red below:

What might be a useful algorithm in order to accomplish this?
回答1:
I think much easier would be to write your own function
To find (perpendicular) distance between point and line and then creating thickness of poly-line by polygon means.

Where:
P0,P1
are line endpointsP
is pointd
is distance between them
Line is defined as: p(t)=P0+(P1-P0)*t
where t=<0.0,1.0>
So the function should do this:
create perpendicular line
q(t)=P+DQ*u
whereu=(-inf,+inf)
DQ
is perpendicular vector to (P1-P0)
In 2D you can obtain it easily like this
(x,y) -> (y,-x)
. In higher dimensions use cross product with some non coplanar vectors.compute line vs. line intersection
there are tons of stuff about this so google or solve the equation yourself here you can extract mine implementation.
now after successful intersection
just compute
d
as distance betweenP
and intersection point. Do not forget that parametert
must be in range. If not (or if no intersection) thenreturn min(|P-P0|,|P-P1|)
[hints]
t
and u
parameters can be obtained directly from intersection test so if the perpendicular vector to (P1-P0)
is normalized to size = 1
then the abs(u)
parameter of intersection point is the distance
[notes]
I am not familiar with mongodb so if you have no means to use own tests inside then this answer is of coarse obsolete.
回答2:
Unfortunately, MongoDB provides very basic geospatial query, so you should create the buffer by your own. You can read how to do it here: Computing a polygon that surrounds a multi-point line
If you have longitude/latitude coordinates like WGS84 you must adjust this code; Read here how to calculate distance between point on a sphere https://en.wikipedia.org/wiki/Haversine_formula
来源:https://stackoverflow.com/questions/25188477/use-within-with-a-buffered-mondodb-linestring