NOTE: I DO NOT need to monitor the user location continuously, just perform the check once off on a button click
I have a Set of Latitude and Longitude, and need to check if the user is within given distance of that point, how can I do it? I checked out Geofencing, but it works like a service, while I need to perform the check once in the main thread
just check with it.
for a location having latitude and longitude set boundaries with the below code:
public LatLngBounds getLocationBounds(LatLng sourceLocation, double distance)
{
LatLng southwest = SphericalUtil.computeOffset(sourceLocation, distance, 225);
LatLng northeast = SphericalUtil.computeOffset(sourceLocation, distance, 45);
return new LatLngBounds(southwest, northeast);
}
This is the method used to calculate the distance between two points:
public double CalculationByDistance(LatLng StartP, LatLng EndP) {
int Radius = 6371;// radius of earth in Km
double lat1 = StartP.latitude;
double lat2 = EndP.latitude;
double lon1 = StartP.longitude;
double lon2 = EndP.longitude;
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2)
* Math.sin(dLon / 2);
double c = 2 * Math.asin(Math.sqrt(a));
double valueResult = Radius * c;
double km = valueResult / 1;
DecimalFormat newFormat = new DecimalFormat("####");
int kmInDec = Integer.valueOf(newFormat.format(km));
double meter = valueResult % 1000;
int meterInDec = Integer.valueOf(newFormat.format(meter));
Log.i("Radius Value", "" + valueResult + " KM " + kmInDec
+ " Meter " + meterInDec);
return Radius * c;
}
This is also a duplicate of this question: Find distance between two points on map using Google Map API V2
Please try to see if your question has been answered before asking in future.
Related
I'm working on Google Maps directions API.
I need to calculate the distance traveled between two points.
If the starting and ending point is same how can we calculate the distance traveled?
Can anyone help me or give some suggestions regarding this?
Try this code
public double Distance(LatLng StartP, LatLng EndP) {
int Radius = 6371;// radius of earth in Km
double lat1 = StartP.latitude;
double lat2 = EndP.latitude;
double lon1 = StartP.longitude;
double lon2 = EndP.longitude;
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2)
* Math.sin(dLon / 2);
double c = 2 * Math.asin(Math.sqrt(a));
double valueResult = Radius * c;
double km = valueResult / 1;
DecimalFormat newFormat = new DecimalFormat("####");
int kmInDec = Integer.valueOf(newFormat.format(km));
double meter = valueResult % 1000;
int meterInDec = Integer.valueOf(newFormat.format(meter));
Log.i("Radius Value", "" + valueResult + " KM " + kmInDec
+ " Meter " + meterInDec);
return Radius * c;
}
Till now, I have inserted all the sets of latitude and longitude in my database after every 5 sec from the path I have travelled.
Now after reaching the destination I have to calculate the distance from the sets of Latitude, longitude. It's not about calculating the travelling distance between two points but to get the total distance travelled from set of lat,long in my database .
I have thought a way of calculating the total distance by getting the distance between the two points
and add them up at last
Is there any better solution than this? please suggest and help
Already read this SO post but not getting how I will get the total distance by using the Google Maps Distance Matrix API
///////service to insert coordinates into the database.
private class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
String name = arg1.getAction();
if (name.equalsIgnoreCase("Location_Changed")) {
db.insertlatlong(new Latilongi(arg1.getStringExtra("latitude"),
arg1.getStringExtra("longitude"),currentDateandTime));
} else if (arg1.getAction().matches("android.location.PROVIDERS_CHANGED")) {
Toast.makeText(MapActivity.this, "in android.location.PROVIDERS_CHANGED",
Toast.LENGTH_SHORT).show();
}
}
}
you can use the following method that will give you acurate result
public double CalculationByDistance(LatLng StartP, LatLng EndP) {
int Radius = 6371;// radius of earth in Km
double lat1 = StartP.latitude;
double lat2 = EndP.latitude;
double lon1 = StartP.longitude;
double lon2 = EndP.longitude;
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2)
* Math.sin(dLon / 2);
double c = 2 * Math.asin(Math.sqrt(a));
double valueResult = Radius * c;
double km = valueResult / 1;
DecimalFormat newFormat = new DecimalFormat("####");
int kmInDec = Integer.valueOf(newFormat.format(km));
double meter = valueResult % 1000;
int meterInDec = Integer.valueOf(newFormat.format(meter));
Log.i("Radius Value", "" + valueResult + " KM " + kmInDec
+ " Meter " + meterInDec);
return Radius * c;
}
try this one
private double distance(double lat1, double lon1, double lat2, double lon2, String 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 == "K") {
dist = dist * 1.609344;
} else if (unit == "N") {
dist = dist * 0.8684;
}
return (dist);
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
/*:: This function converts decimal degrees to radians :*/
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
private static double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
You can insert only distance between two co-ordinates and lastly sum up all distances you had in database. Distance achieve like below.
float distanceInMeters = lastLocation.distanceTo(myLocation);
where "lastLocation" and "myLocation" are of Location object.
If you dont have Location object than you can try this.
Location lastLocation = new Location("");
lastLocation.setLatitude(latitude);
lastLocation.setLongitude(longitude);
Location myLocation = new Location("");
myLocation.setLatitude(otherlatitude);
myLocation.setLongitude(otherlongitude);
float distanceInMeters = lastLocation.distanceTo(myLocation);
I have a list of latitude and longitude stored in database. Now I'm trying to develop a function on finding nearby place from my current location. Means that, i have to search all the latitude and longitude from my database and see which of the places are within my area will be shown.
Location.distanceBetween(lat1,lon1, lat2,lon2, result);
To find the distance from one two-dimensional point to another you can use the Haversine formula, (without calling any API functions.)
// All measurements are in meters
var rad = function(x) {
return x * Math.PI / 180;
};
var getDistance = function(coord1, coord2) {
// This is the Earth's radius
var earthRad = 6378137;
var dLat = rad(coord2.lat() - coord1.lat());
var dLong = rad(coord2.lng() - coord1.lng());
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(rad(coord1.lat())) * Math.cos(rad(coord2.lat())) *
Math.sin(dLong / 2) * Math.sin(dLong / 2);
var b = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var distance = earthRad * b;
// Returns distance from coord1 to coord2 in meters
return distance;
};
Your question is a bit broad so this might not be the best solution. If you were constantly updating your current location you'd have to implement a Tree Sorting algorithm or some other way of optimizing performance rather than checking through your database for distances on every update.
You can use the Location object. The distanceBetween or distanceTo method will give you the 'as the crow flies' distance between two points. From there you can filter your results and display only the places you want to.
here is what i use
public void nearBy() {
if (map.getMyLocation() != null) {//check if my location was found
db = new MyDatabase(MainActivity.context);
Cursor medecin = db.lireMedecin();//read values from database
map.clear();//clearing the map
while (medecin.getPosition() < medecin.getCount()) { //cheking if this doctor is nearby...
String Lat1 = medecin.getString(5);//doctor's latitude
String Lon1 = medecin.getString(6);//doctor's longitude
LatLng me = new LatLng(map.getMyLocation().getLatitude(), map.getMyLocation().getLongitude());//my location
LatLng med = new LatLng(Double.parseDouble(Lat1), Double.parseDouble(Lon1));//doctor location
if (CalDist(me, med) < 6) {//if distance is < 6km add marker to the map
map.addMarker(new MarkerOptions().position(med).title(medecin.getString(1) + " " + medecin.getString(2))
.snippet(medecin.getString(4)).icon(BitmapDescriptorFactory
.fromResource(Icone(medecin.getString(7).charAt(0))))); //showing the doctor on the map
}
medecin.moveToNext();//next doctor
}
} else
Toast.makeText(context, "Gps signal not valid", Toast.LENGTH_SHORT).show();//can't find my position
}
calculate distance :
public static double CalDist(LatLng StartP, LatLng EndP) {
int Radius = 6371;//radius of earth in Km
double lat1 = StartP.latitude ;
double lat2 = EndP.latitude ;
double lon1 = StartP.longitude ;
double lon2 = EndP.longitude ;
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
double c = 2 * Math.asin(Math.sqrt(a));
return Radius * c;
}
First of all I apologise for my poor English.
I currently working on an android-app and I am using the google api v2. I have got 2 Markers on my google map and calculate the distance between them, with the .distancebetween method. Then I draw a Polyline between the markers.
Now i want to bind the distance to my Polyline. The distance should be under the polyline and if i move a marker the distance should still under the polyline.
This is not easy to do, but certainly possible.
Here are the steps:
calculate center of each line
for that center latitude, calculate point that is 50dp below it (using Projection)
put a marker on that position
set marker icon to Bitmap with text
update markers position when you get calls to OnCameraChangeListener.onCameraChange or in Handler's Runnable posted every few milliseconds
This method may help you to find the distance, it finds the distance between the starting points LatLng and ends point LatLng
public double CalculationByDistance(LatLng StartP, LatLng EndP) {
int Radius=6371;//radius of earth in Km
double lat1 = StartP.latitude;
double lat2 = EndP.latitude;
double lon1 = StartP.longitude;
double lon2 = EndP.longitude;
double dLat = Math.toRadians(lat2-lat1);
double dLon = Math.toRadians(lon2-lon1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2);
double c = 2 * Math.asin(Math.sqrt(a));
double valueResult= Radius*c;
double km=valueResult/1;
DecimalFormat newFormat = new DecimalFormat("####");
int kmInDec = Integer.valueOf(newFormat.format(km));
double meter=valueResult%1000;
int meterInDec= Integer.valueOf(newFormat.format(meter));
Log.i("Radius Value",""+valueResult+" KM "+kmInDec+" Meter "+meterInDec);
return Radius * c;
}
you can also try this :
Location locationA = new Location("location A");
locationA.setLatitude(locationA.getLatitudeE6() / 1E6);
locationA.setLongitude(locationA.getLongitudeE6() / 1E6);
Location locationB = new Location("location B");
locationB.setLatitude(locationB.getLatitudeE6() / 1E6);
locationB.setLongitude(locationB.getLongitudeE6() / 1E6);
double distance = locationA.distanceTo(locationB);
I have used tutorial from the link below to display Google map route in Android app. My question is how can I calculate distance to polyline points on map? Like when I use Google maps app and it tells when a street turn is getting close. I want to implement similar feature in my app. I am able to display the route polyline on the map and it updates itself while I drive along it but I want it to warn me 500 feet in advance of a coming turn. How can I do that?
Here is the link:
http://jigarlikes.wordpress.com/2013/04/26/driving-distance-and-travel-time-duration-between-two-locations-in-google-map-android-api-v2/
I use this method for Markers. Assuming you have Latitude and Longitude of the points that make up the Polyline this should do:
public class MapUtils {
public static float distBetween(LatLng pos1, LatLng pos2) {
return distBetween(pos1.latitude, pos1.longitude, pos2.latitude,
pos2.longitude);
}
/** distance in meters **/
public static float distBetween(double lat1, double lng1, double lat2, double lng2) {
double earthRadius = 3958.75;
double dLat = Math.toRadians(lat2 - lat1);
double dLng = Math.toRadians(lng2 - lng1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2)
* Math.sin(dLng / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double dist = earthRadius * c;
int meterConversion = 1609;
return (float) (dist * meterConversion);
}
}
To determine wether the road is turning, I would look into euclidean angle between vectors (x being current location and y being a polyline point)
Simply take your current location and a LatLng from some distance ahead for this.
Calculation is based on: http://en.wikipedia.org/wiki/Euclidean_space#Angle
Location currentLocation; // obtained somewhere in your code
LatLng polylinePoint; // a point further ahead
double cLat = currentLocation.getLatitude();
double cLon = currentLocation.getLongitude();
double pLat = polylinePoint.latitude;
double pLon = polylinePoint.longitude;
double angle = Math.acos(
(cLat*pLat+cLon+pLon) / norm(cLat,cLon)*norm(pLat,cLon));
private double norm(double x, double y) {
return Math.sqrt(Math.pow(x, 2)*Math.pow(y, 2));
}
This is untested so might contain error.