[OSM-dev] Getting a distance to a way
Frederik Ramm
frederik at remote.org
Mon Jul 21 08:47:09 BST 2008
Hi,
> Has someone a working algorithm to get the shortest distance from a
> node to a
> way?
Assume that "begin" and "end" are the nodes defining your way, and
"point" is the point from which you want to measure distance, and
assume all coordinates are given as instances of class
"EastNorth" (i.e. in projected coordiantes with an "easting" and a
"northing" value), then the point on the way for which the distance
is shortest can be computed like this:
double u = ((point.east()-begin.east())*(end.east()-begin.east())
+ (point.north()-begin.north())*(end.north()-begin.north()))/
end.distanceSq(begin);
EastNorth nearest = new EastNorth(begin.east()+u*(end.east()-
begin.east()), begin.north()+u*(end.north()-begin.north()));
Then you only have to compute the distance between "nearest" and
"point":
double dist = Math.sqrt(nearest.distanceSq(point));
(distanceSq is just a method that returns (north1-north2)**2 + (east1-
east2)**2)
If you want all this to work on unprojected coordinates, i.e. lat/lon
values, then doing it *right* (i.e. doing it in a way that works even
if your way goes from Iceland to South Africa and your point is in
New Zealand) requires a *lot* more math.
Bye
Frederik
--
Frederik Ramm ## eMail frederik at remote.org ## N49°00'09" E008°23'33"
More information about the dev
mailing list