Reputation: 3028
I am new to Java. I have created a geofence with circle shape. I know the center(Latitude,longitude) point and radius(in meter). I want to check whether a geo point(i.e. latitude, longitude) is within this fence, and if it is true I want to find distance between that geopoint to the center point. How can I do this in java. In mysql there is one query for doing this
SELECT tripid,create_time, ( 6371 * acos( cos( radians(8.475316) ) * cos(
radians(lattitude ) ) * cos(
radians( longitude ) - radians(76.962528) ) + sin( radians(8.475316) ) * sin(
radians( lattitude ) ) ) ) AS
distance
FROM pack_history where speed<5 and tripid=685 HAVING distance < 0.10 ORDER BY
create_time desc LIMIT 0 ,100;
How can i do this similar functionality in Java??
Upvotes: 2
Views: 2803
Reputation: 1317
This function is to calculate the Distance between two lat/lon coordinates
private double distance(double lat1, double lon1, double lat2, double lon2, char unit) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
if (unit.equals("K")) {
dist = dist * 1.609344;
} else if (unit.equals("N")) {
dist = dist * 0.8684;
}
return (dist);
}
This function converts decimal degrees to radians
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
This function converts radians to decimal degrees
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
If you want in Miles pass M as unit
system.println(distance(32.9697, -96.80322, 29.46786, -98.53506, "M") + " Miles\n");
If you want in Kilometers pass K as unit
system.println(distance(32.9697, -96.80322, 29.46786, -98.53506, "K") + " Kilometers\n");
If you want in Nautical Miles pass N as unit
system.println(distance(32.9697, -96.80322, 29.46786, -98.53506, "N") + " Nautical Miles\n");
Upvotes: 0
Reputation: 28727
You simply need a method that calculates the distance between two lat/ lon coordinates.
(search here on SO or internet, this is easy to find).
if the distance is < r then the point is inside the circle.
Upvotes: 5