I'm working on an Android app and I want to add store locator details and map view.I searched a lot.,but I'm n't getting anything purposeful.I'm tensed and strongly need your help.
The problem is,I want to find the distance between 2 co-ordinates,I got one Haversine formula.,but don't know how to run the program successfully.,As I'm a beginner in Android,please help to do the coding in stepwise.,ie the xml code also..,please.,please.,
As stated above, the Location Class is the way to go. Here is the code I have used :
Location locationA = new Location("point A");
locationA.setLatitude(pointA.getLatitudeE6() / 1E6);
locationA.setLongitude(pointB.getLongitudeE6() / 1E6);
Location locationB = new Location("point B");
locationB.setLatitude(pointB.getLatitudeE6() / 1E6);
locationB.setLongitude(pointB.getLongitudeE6() / 1E6);
double distance = locationA.distanceTo(locationB);
In this example, both pointA and pointB are instances of the GeoPoint class.
From MotoDev snippets (Distance between GPS Coordinates):
Location originLocation = new Location("gps");
Location destinationLocation = new Location("gps");
originLocation.setLatitude(originLatitude);
originLocation.setLongitude(originLongitude);
destinationLocation.setLatitude(originLatitude);
destinationLocation.setLongitude(originLongitude);
float distance = originLocation.distanceTo(destinationLocation);
http://developer.android.com/reference/android/location/Location.html
Look into distanceTo or distanceBetween. You can create a Location object from a latitude and longitude:
Location location = new Location("");
location.setLatitude(lat);
location.setLongitude(lon);
Use this code. you will get distance between two geo points.
private String distance(double lati, double longi, double curlati1,
double curlongi1) {
double theta = longi - curlongi1;
double dist = Math.sin(deg2rad(lati)) * Math.sin(deg2rad(curlati1))
+ Math.cos(deg2rad(lati)) * Math.cos(deg2rad(curlati1))
* Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
dist = dist * 1.609344;
result = Double.toString(dist);
System.out.println("dist_result :" + result);
return (result);
}
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
/* :: 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);
}
Related
ArrayList<LatLng> arrayList= new ArrayList<LatLng>();
LatLng near = new LatLng(33.549232, 73.125256);
LatLng pass = new LatLng(33.549844, 73.125849);
LatLng qareeb = new LatLng(33.549603, 73.124201);
public void onMapReady(GoogleMap googleMap) {
mMap= googleMap;
for (int i =0; i<arrayList.size();i++){
mMap.addMarker(new MarkerOptions().position(arrayList.get(i)).title("Marker").snippet("and snippet")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
LatLng latLng = new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude());
MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("Main Yahan hn");
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(arrayList.get(i),15));
mMap.animateCamera(CameraUpdateFactory.zoomIn());
mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
/*mMap.animateCamera(CameraUpdateFactory.zoomTo(15.0f));*/
mMap.moveCamera(CameraUpdateFactory.newLatLng(arrayList.get(i)));
googleMap.addMarker(markerOptions);
}
}
Above is my code and I want to create 3 points which compare to my current location that which one is near to the current location.
The question which you are asking and the code which you have posted are not complete. The code simply enables GoogleMaps on the Activity. Instead of coding the entire solution to you, I would explain you the logic and expect you try it out at your end and repost the updated answer here if required.
Steps:
Fetch the current location of the device using FusedLocationProviderClient and store the value in a variable (say currentLocation). (Get the last known location)
Use Location class to find the distance between point1 and currentLocation. (say d1). (distanceBetween)
Use the same process to find the distances between point2 and point3 from the currentLocation.
Now you will have 3 distance variables, d1, d2 and d3. I guess you'll be able to find the shortest of these easily.
You can calculate distance between two location and then compare the distance.
private double distance(double lat1, double lon1, double lat2, double lon2) {
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;
return (dist);
}
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
You can use this as below code
LatLng near = new LatLng(33.549232, 73.125256);
LatLng pass = new LatLng(33.549844, 73.125849);
LatLng qareeb = new LatLng(33.549603, 73.124201);
double distance = distance(near.latitude, near.longitude, pass.latitude, pass.longitude);
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 had plotted two points in Google Map. I want to compute the distance between the two points in terms of road way. Any solution or working code?
Just use Android's inbuilt Location class, for getting distance between two locations.
Also you can 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);
You can use following method for calculating distance between two lat-long points.
public static float distFrom (float lat1, float lng1, float lat2, float 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 new Float(dist * meterConversion).floatValue();
}
You can do it through the APIs: there is a ComputeDistanceBetween function in the "geometry" library, "spherical" namespace. Reference: https://developers.google.com/maps/documentation/javascript/geometry
It is used this way:
var distance = google.maps.geometry.spherical.computeDistanceBetween(latLong, latLong);
I am developing an application in which I need to calculate the distance travelled. I am facing a problem while calculating the distance.
Here is my code:
locationmanager.requestLocationUpdates(bestProvider,0,0,new Listener());
public class Listener implements LocationListener{
#Override
public void onLocationChanged(Location location) {
if(location!=null) {
if(loc1==null) {
loc1=new Location(location);
}
speed=location.getSpeed()*3.6;
loc2=new Location(location);
dist+=loc1.distanceTo(loc2);
loc1=loc2;
breaktv.setText(""+dist/1000);
My intention is calculate the total distance travelled by car or something. But distanceTo() method is not working well for me.
Technically it should work.
I have some suggestions :
dist must be float (if it isn't already)
dist += loc2.distanceTo(location), there is no need to create loc1
This is the code I've used
if(lastLoc != null)
{
ttf = (location.getTime() - lastLoc.getTime()) / 1000;
int R = 6371;
double lat1 = Math.PI / 180.0 *lastLoc.getLatitude();
double lon1 = Math.PI / 180.0 *lastLoc.getLongitude();
double lat2 = Math.PI / 180.0 *location.getLatitude();
double lon2 = Math.PI / 180.0 *location.getLongitude();
// double dLon = Math.PI / 180.0 * (location.getLongitude() - lastLoc.getLongitude());
double dLat = (lat2-lat1);
double dLon = (lon2-lon1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1) * Math.cos(lat2) *
Math.sin(dLon/2) * Math.sin(dLon/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double d = R * c;
totalDistance += d;
}
lastLoc = location;
Here is another Question on SO where I have posted 2 Answers one for the User Defined function to get the distance and other to User android.Location class method to calculate it.
Hope this will help you.
When You start your jurney take the CurrentLocation and store it may be using SharedPreferences,
Then I think you need to Continuosly keep updating the Distance Travelled,
You just use OnLocationChanged same way and Call the method above two mentioned from there to know the Current Distance Travelled.
EDIT:
here is a good example that may help you,Link To OpenSource Project
double distance;
Location locationA = new Location("point A");
locationA.setLatitude(latA);
locationA.setLongitude(lngA);
Location locationB = new Location("point B");
locationB.setLatitude(latB);
LocationB.setLongitude(lngB);
distance = locationA.distanceTo(locationB);
the above code is not working and i am getting 0.0 Km as distance?
Also in the constructor of the location class, what does the string provider mean.
In the above code i am using PointA and PointB as the providers.
why is the above code not working?
thank you in advance.
LOGCAT
05-09 17:48:56.144: INFO/current loc(1573): lat 0.0 lng 0.0
05-09 17:48:56.155: INFO/checklocation loc(1573): lat 54.4288665 lng 10.169366
Just a quick snippet since I didn't see a complete and simple solution with GeoPoints above:
public float getDistanceInMiles(GeoPoint p1, GeoPoint p2) {
double lat1 = ((double)p1.getLatitudeE6()) / 1e6;
double lng1 = ((double)p1.getLongitudeE6()) / 1e6;
double lat2 = ((double)p2.getLatitudeE6()) / 1e6;
double lng2 = ((double)p2.getLongitudeE6()) / 1e6;
float [] dist = new float[1];
Location.distanceBetween(lat1, lng1, lat2, lng2, dist);
return dist[0] * 0.000621371192f;
}
If you want meters, just return dist[0] directly.
Try Location.distanceBetween(..)
Update:
If you are getting lat/lon from GeoPoint then they are in microdegrees. You must multiply by 1e6.
As stated above, the Location Class is the way to go. Here is the code I have used :
Location locationA = new Location("point A");
locationA.setLatitude(pointA.getLatitudeE6() / 1E6);
locationA.setLongitude(pointA.getLongitudeE6() / 1E6);
Location locationB = new Location("point B");
locationB.setLatitude(pointB.getLatitudeE6() / 1E6);
locationB.setLongitude(pointB.getLongitudeE6() / 1E6);
double distance = locationA.distanceTo(locationB);
In this example, both pointA and pointB are instances of the GeoPoint class.
This is not an answer, but note the signature for the Location constructor is Location(String provider).
i.e. the String you pass to the constructor should be one of LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER or LocationManager.PASSIVE_PROVIDER, not "point A" and "point B".
An alternative way to accomplish the above,
public class Distance {
public static double distance(double lat1, double lon1, double lat2, double lon2) {
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);
}
public static final double PI = 3.14159265;
public static final double deg2radians = PI/180.0;
public static double getDistance(double latitude1, double longitude1, double latitude2,double longitude2) {
double lat1 = latitude1 * deg2radians;
double lat2 = latitude2 * deg2radians;
double lon1 = longitude1 * deg2radians;
double lon2 = longitude2 * deg2radians;
// Williams gives two formulae;
// this is the more accurate for close distances.
// In practice, the two differed only in the 8th or 9th place, for
// separations as small as 1 degree.
double radd = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin((lat1 - lat2) / 2),
2.0)
+ Math.cos(lat1)
* Math.cos(lat2)
* Math.pow(Math.sin((lon1 - lon2) / 2), 2.0)));
return radd;
}
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
/* :: This function converts decimal degrees to radians : */
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
private static double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
/* :: This function converts radians to decimal degrees : */
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
private static double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
}
double CalculateDistance( double nLat1, double nLon1, double nLat2, double nLon2 )
{
double nRadius = 6371; // Earth's radius in Kilometers
// Get the difference between our two points
// then convert the difference into radians
double nDLat = ToRad(nLat2 - nLat1);
double nDLon = ToRad(nLon2 - nLon1);
// Here is the new line
nLat1 = ToRad(nLat1);
nLat2 = ToRad(nLat2);
double nA = pow ( sin(nDLat/2), 2 ) + cos(nLat1) * cos(nLat2) * pow ( sin(nDLon/2), 2 );
double nC = 2 * atan2( sqrt(nA), sqrt( 1 - nA ));
double nD = nRadius * nC;
return nD; // Return our calculated distance
}
http://www.jaimerios.com/?p=39