locations
sorting of locations ref. nearest location.
sort locations with nearest distance
how it works?
- get user’s current location
- compare with other destinations
- sort according the nearest
there are two ways to compare distance
personally, i like haversine formula and have been using it.
algorithm 1
use havesine formula.
haversine formula
double getdistancefromlatloninkm(lat1,lon1,lat2,lon2) {
var r = 6371; // radius of the earth in km
var dlat = deg2rad(lat2-lat1); // deg2rad below
var dlon = deg2rad(lon2-lon1);
var a =
math.sin(dlat/2) * math.sin(dlat/2) +
math.cos(deg2rad(lat1)) * math.cos(deg2rad(lat2)) *
math.sin(dlon/2) * math.sin(dlon/2)
;
var c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a));
var d = r * c; // distance in km
return d;
}
double deg2rad(deg) {
return deg * (math.pi/180);
}
algorithm 2
use inbuilt distance comparision function provided by geolocater.
geolocator.distancebetween(source.latitude,source.longitude, destination.latitude,destination.longitude);
assumption”
- you are in google plex (37.422,-122.084)
destinations:
- destination(37.4274684,-122.1698161, “standford university”),
- destination(37.4083327,-122.0776016, “taco bell”),
- destination(37.4259071,-122.1095606, “ramos park”),
- destination(37.8711583,-122.336457, “bekerly”),
- destination(37.7586968,-122.3053474, “oakland”),
- destination(37.4420794,-122.1432758, “palo alto”),
- destination(37.5206515,-122.064364, “new wark”)
output:
haversine algorithm | geolocator algorithm |
---|---|
Comments are closed.