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.
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), ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With