Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map locations to their nearest location based on latitude and longitude

I have two set of locations say A(20K locations) and B(2k locations). I want to have a map for all locations in set A to their closest location in set B based on their latitude and longitude.

Is there any solution in java or R. Java solution preferred.

like image 330
aru007 Avatar asked Sep 19 '25 17:09

aru007


1 Answers

As from the answer from @rosscova

Take the points, but as a matrix

pointsA <- as.matrix(data.frame( lat = c( 10, 12, 20 ), lon = c( 12, 17, 10 ) ))
pointsB <- as.matrix(data.frame( lat = c( 11, 15 ), lon = c( 15, 15 ) ))

Then, when dealing with coordinates, you may prefer to use the Great Circle (WGS84 ellipsoid) distance instead of the euclidean. I usually use the spDists function from the sp package

library( sp )
out_Dists <- spDists(x = pointsA, y = pointsB, longlat = TRUE, segments = FALSE, diagonal = FALSE)

and at the end using the apply function with the which.min over the rows to get the nearest pointB to pointA

pointsA[ apply(out_Dists, 1, which.min), ]
like image 84
D-Lorenz Avatar answered Sep 21 '25 06:09

D-Lorenz