How can I measure distance between two location by road in my Android application? I wrote code that measure the distance in a straight line, but I need code for shortest distance by road. What should I change in my code for it?
public double updateDistance(Location location) {
float results[] = new float[3];
Location.distanceBetween(location.getLatitude(),
location.getLongitude(), mLatitude, mLongitude, results);
distance = results[0];
return distance;
}
Use the google maps api instead
https://developers.google.com/maps/documentation/distance-matrix/intro?hl=en
you can see this too
Google Map API v2 - Get Driving Distance from Current Location to Known Locations
Related
I am trying to calculate the distance between multiple GPS destinations.
My Approach
I am using Google's Matrix API for this, but it allows at max. 25 points. And I need to track the complete distance travelled by a user.
Any suggestion will be very helpful.
Using Android SDK:
Try using the Location object's distanceTo function like so:
float getTripDistance(List<LatLng> vertices) {
float totalDistance = 0;
for (int i = 0; i < vertices.size() - 1; i++) {
Location tLoc1 = new Location("");
Location tLoc2 = new Location("");
tLoc1.setLatitude(vertices.get(i).latitude);
tLoc1.setLongitude(vertices.get(i).longitude);
tLoc2.setLatitude(vertices.get(i + 1).latitude);
tLoc2.setLongitude(vertices.get(i + 1).longitude);
totalDistance += tLoc1.distanceTo(tLoc2);
}
return totalDistance;
}
You can loop over all of your points sequentially and sum each respective distance in meters to get the total trip distance.
I know this is too late but this is for users who are still searching for a solution.
float[] distanceResults = new float[1];
Location.distanceBetween(oldPosition.latitude, oldPosition.longitude,
newPosition.latitude, newPosition.longitude, distanceResults);
As per documentation, the above function computes the approximate distance in meters between two locations, and optionally the initial and final bearings of the shortest path between them. Hence, the variable distanceResults will have the distance in meters.
i trying to get if location is in my radius.
i.e I have my current location "LatLng" object and i have one more "LatLng" object and i want to check if the two object are in rang of 1km?
How can i implement that?
In Location.distanceBetween() function provide you distance in meters and float value ..
distanceBetween(double startLatitude, double startLongitude, double
endLatitude, double endLongitude, float[] results) Computes the
approximate distance in meters between two locations, and optionally
the initial and final bearings of the shortest path between them.
use this it working i've already checked it .....
float[] dist = new float[1];
Location.distanceBetween(firstLoaction.latitude,firstLoaction.longitude,anotherLocation.latitude,anotherLocation.longitude,dist);
if(dist[0]/1000 > 1){
//here your code or alert box for outside 1Km radius area
}
NOTE:- For getting the location distance always use Location.distanceBetween() which is provide by ANDROID .
double distanceInKiloMeters = (currentLocation.distanceTo(someLocation)) / 1000; // as distance is in meter
if(distanceInKiloMeters <= 1) {
// It is in range of 1 km
}
else {
// not in range of 1 km
}
you can try converting LatLng to Location object for both first and then using distanceTo method to find the distance between those two and check if it is 1km or not
distanceto methode to get distance from locCenter and point and just substitute this distance from the radius if <0 so the point out of range , else the point in border or inside the range.. good luck
Does it take into account altitude changes?
I mean, if I start in left vertex of this triangle and end in the right upper vertex, does it return distance a or b?
double distanceInMetersFloat = initialPosition.distanceTo(finalPosition);
In my app, both initialPosition and finalPosition are Location with altitudes (I set them with Google Elevation API).
According to Google:
Distance is defined using the WGS84 ellipsoid.
But you can do it with or without altitudes.
The altitude is not taken into account when computing Location.distanceTo.
You can test it like this:
Location location1 = new Location("");
location1.setLatitude(40);
location1.setLongitude(-4);
location1.setAltitude(0);
Location location2 = new Location("");
location2.setLatitude(30);
location2.setLongitude(-3);
location2.setAltitude(0);
Location location3 = new Location("");
location3.setLatitude(30);
location3.setLongitude(-3);
location3.setAltitude(100);
Log.e("Without altitude", ""+location1.distanceTo(location2));
Log.e("With altitude", ""+location1.distanceTo(location3));
Log.e("Different altitude", ""+location2.distanceTo(location3));
This is the output:
E/Without altitude﹕ 1113141.5
E/With altitude﹕ 1113141.5
E/Different altitude﹕ 0.0
I am fairly new to Android programming, but I am getting pretty good at it (I think: ))
What I am doing is building a situated stories app. It is an app that places audio files at certain GPS markers and enables the user to listen to them at specific locations.
The next step is moving audio files. What I want to do is set a marker at a specific position in a city. (done). Next I want to check the location of a second marker that moves in a circle around it.
What I have so far is this:
public void checkCircularPosition(){
/*
* could be a solution?
*
radius = 250; //offset in meters
gpsLatCenter = 5.1164; //?how can i make this accurate in meters?
gpsLonCenter = 52.0963; //??how can i make this accurate in meters?
degree = 0; //should be variable over time (full circle in 1Hr, 3600sec --> 360/3600 = 0,1 deg/s)
radian;
radian = (degree/180)*Math.PI;
gpsCircleLat = gpsLatCenter+Math.cos(radian)*radius;
gpsCircleLon = gpsLonCenter-Math.sin(radian)*radius;
*/
}
Now, I have checked this code in adobe flash, which made a movie clip move around in a circle. So I know the calculations are somewhat right. But, I have no way of calculating the latitude and longitude of the resulting coordinates.
EDIT!!
i found the solution with the help posted below. still a lot of work to figure out how to use the results. anyway, i posted the resulting function below.
to make this work, you need _radius wich is 6371 (earth's radius), a bearing, a distance, and a start location.
thanks a lot guys!
public static void destinationPoint(double brng, double dist) {
dist = dist/_radius; // convert dist to angular distance in radians
brng = Math.toRadians(brng); //
double lat1 = Math.toRadians(_lat);
double lon1 = Math.toRadians(_lon);
double lat2 = Math.asin( Math.sin(lat1)*Math.cos(dist) + Math.cos(lat1)*Math.sin(dist)*Math.cos(brng) );
double lon2 = lon1 + Math.atan2(Math.sin(brng)*Math.sin(dist)*Math.cos(lat1), Math.cos(dist)-Math.sin(lat1)*Math.sin(lat2));
lon2 = (lon2+3*Math.PI) % (2*Math.PI) - Math.PI; // normalise to -180..+180º
Log.i(APPTAG, ""+Math.toDegrees(lat2));
Log.i(APPTAG, ""+Math.toDegrees(lon2));
Location movLoc = new Location("");
movLoc.setLatitude(Math.toDegrees(lat2));
movLoc.setLongitude(Math.toDegrees(lon2));
Log.i(APPTAG, ""+movLoc);
}
You should check the section Destination point given distance and bearing from start point at this website: http://www.movable-type.co.uk/scripts/latlong.html
That website has the proper formula for using your start point (gpsLatCenter/gpsLonCenter) and bearing (degree in you code) to compute the final lat/lon (gpsCircleLat/gpsCircleLon).
I am trying to pass latitude and longitude to another activity and check the distance between this passed co-ordinates and the current co-ordinate.
In the first activity:
GeoPoint p1 = mapView.getProjection().fromPixels((int) event.getX(),(int event.getY());
setter(p1.getLatitudeE6()/ 1E6, p1.getLongitudeE6() /1E6);
public void setter(Double lati,Double longi)
{
latitude=lati;
longitude=longi;
}
on the button click event i am passing this with the help of a bundle. This works fine.
In the second activity:
public Location selected_location=null;
Double lati,longi;
Bundle b=this.getIntent().getExtras();
lati=b.getDouble("latitude");
longi=b.getDouble("longitude");
Till this much it works fine. I even printed the values. The real issue is the the lines given below:
selected_location.setLatitude(lati);
selected_location.setLongitude(longi);
I am trying to set the passed latitude and longitude values to a location variable. But this is causing the activity to terminate.
If possible please suggest a solution. If the question is childish please ignore.
If you aim to calculate only the distance you do not need to construct Location objects use this method. It is static and works with long and lat values. I can also help debuging the error if you put the stack trace of the exception.
EDIT The requested example:
float myGetDistance(double startLatitude, double startLongitude, double endLatitude, double endLongitude) {
float [] results = new float[1]; // You need only the distance, thus only one element
Location.distanceBetween(startLatitude, startLongitude, endLatitude, endLongitude, results);
return results[0];
}
You can complete the distance between two points given by it coordinates like this:
final float[] results= new float[1];
// The computed distance in meters is stored in results[0].
// If results has length 2 or greater, the initial bearing is stored in results[1].
// If results has length 3 or greater, the final bearing is stored in results[2].
Location.distanceBetween(refLat, refLong, latitude, longitude, results);
final float distance = results[0]; // meter!
You may reuse the results array for later computations. If you need bearing information use declare the result array of size 3, if you do not need it use size 1 and save the time for the computation of the not needed information this way.