Here my code I used below code to calculate the distance between two location using their latitude and longitude. It is giving wrong distance. sometimes getting right and sometimes getting irrelevant distance.
这里我的代码我在下面的代码中使用它们的纬度和经度来计算两个位置之间的距离。这是错误的距离。有时候变得正确,有时会变得无关紧要。
We are getting lat1 and lng1 from database.
我们从数据库获取lat1和lng1。
//getting lat2 and lng2 from GPS as below
public class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc)
{
lat2=loc.getLatitude();
lng2=loc.getLongitude();
String Text = "My current location is: " +"Latitud = "+ loc.getLatitude() +"Longitud = " + loc.getLongitude();
//System.out.println("Lat & Lang form Loc"+Text);
//Toast.makeText( getApplicationContext(), Text,Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderDisabled(String provider)
{
}
@Override
public void onProviderEnabled(String provider)
{
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
//Calculating distance
double earthRadius = 3958.75;
double dLat = Math.toRadians(lat1-lat2);
double dLng = Math.toRadians(lng1-lng2);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat2)) * Math.cos(Math.toRadians(lat1)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double dist = earthRadius * c;
11 个解决方案
#1
35
Here getting distance in kilometers (km)
这里以公里(km)为距离
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);
}
#2
62
There is an android.location.Location.distanceBetween()
method which does this quite well.
有一个android.location.Location.distanceBetween()方法可以很好地完成这项工作。
Android Developer Docs: Location
Android开发人员文档:位置
#3
44
Try this code.
试试这个代码。
startPoint.distanceTo(endPoint) function returns the distance between those places in meters.
startPoint.distanceTo(endPoint)函数返回这些位置之间的距离(以米为单位)。
Location startPoint=new Location("locationA");
startPoint.setLatitude(17.372102);
startPoint.setLongitude(78.484196);
Location endPoint=new Location("locationA");
endPoint.setLatitude(17.375775);
endPoint.setLongitude(78.469218);
double distance=startPoint.distanceTo(endPoint);
here "distance" is our required result in Meters. I hope it will work for android.
这里“距离”是我们在米中所需的结果。我希望它适用于android。
#4
5
in build.gradle:
compile 'com.google.maps.android:android-maps-utils:0.4'
and then:
public static Double distanceBetween(LatLng point1, LatLng point2) {
if (point1 == null || point2 == null) {
return null;
}
return SphericalUtil.computeDistanceBetween(point1, point2);
}
#5
4
If you have two Location Objects Location loc1
and Location loc2
you do
如果您有两个位置对象位置loc1和位置loc2
float distance = loc1.distanceTo(loc2);
If you have longitude and latitude values you use the static distanceBetween()
function
如果您有经度和纬度值,则使用静态distanceBetween()函数
float[] results = new float[1];
Location.distanceBetween(startLatitude, startLongitude,
endLatitude, endLongitude, results);
float distance = results[0];
#6
2
private String getDistanceOnRoad(double latitude, double longitude,
double prelatitute, double prelongitude) {
String result_in_kms = "";
String url = "http://maps.google.com/maps/api/directions/xml?origin="
+ latitude + "," + longitude + "&destination=" + prelatitute
+ "," + prelongitude + "&sensor=false&units=metric";
String tag[] = { "text" };
HttpResponse response = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
response = httpClient.execute(httpPost, localContext);
InputStream is = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(is);
if (doc != null) {
NodeList nl;
ArrayList args = new ArrayList();
for (String s : tag) {
nl = doc.getElementsByTagName(s);
if (nl.getLength() > 0) {
Node node = nl.item(nl.getLength() - 1);
args.add(node.getTextContent());
} else {
args.add(" - ");
}
}
result_in_kms = String.format("%s", args.get(0));
}
} catch (Exception e) {
e.printStackTrace();
}
return result_in_kms;
}
#7
1
Why are you writing the code for calculating the distance by yourself?
你为什么要编写自己计算距离的代码?
Check the api's in Location class
检查位置类中的api
#8
1
private float distanceFrom_in_Km(float lat1, float lng1, float lat2, float lng2) {
if (lat1== null || lng1== null || lat2== null || lng2== null)
{
return null;
}
double earthRadius = 6371000; //meters
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));
float dist = (float) (earthRadius * c);
return dist;
}
#9
0
You should use Haversine Distance Formulas
您应该使用Haversine Distance Formulas
Haversine Formulas used to calculate the great distance between two points on the earth.
Haversine Formulas用于计算地球上两点之间的距离。
public void haversine(double lat1, double lon1, double lat2, double lon2) {
double Rad = 6372.8; //Earth's Radius In kilometers
// TODO Auto-generated method stub
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
lat1 = Math.toRadians(lat1);
lat2 = Math.toRadians(lat2);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
double c = 2 * Math.asin(Math.sqrt(a));
haverdistanceKM = Rad * c;
}
#10
0
public float getMesureLatLang(double lat,double lang) {
Location loc1 = new Location("");
loc1.setLatitude(getLatitute());// current latitude
loc1.setLongitude(getLangitute());//current Longitude
Location loc2 = new Location("");
loc2.setLatitude(lat);
loc2.setLongitude(lang);
return loc1.distanceTo(loc2);
// return distance(getLatitute(),getLangitute(),lat,lang);
}
#11
0
Get KM from lat long
从lat获得KM
public static float getKmFromLatLong(float lat1, float lng1, float lat2, float lng2){
Location loc1 = new Location("");
loc1.setLatitude(lat1);
loc1.setLongitude(lng1);
Location loc2 = new Location("");
loc2.setLatitude(lat2);
loc2.setLongitude(lng2);
float distanceInMeters = loc1.distanceTo(loc2);
return distanceInMeters/1000;
}
#1
35
Here getting distance in kilometers (km)
这里以公里(km)为距离
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);
}
#2
62
There is an android.location.Location.distanceBetween()
method which does this quite well.
有一个android.location.Location.distanceBetween()方法可以很好地完成这项工作。
Android Developer Docs: Location
Android开发人员文档:位置
#3
44
Try this code.
试试这个代码。
startPoint.distanceTo(endPoint) function returns the distance between those places in meters.
startPoint.distanceTo(endPoint)函数返回这些位置之间的距离(以米为单位)。
Location startPoint=new Location("locationA");
startPoint.setLatitude(17.372102);
startPoint.setLongitude(78.484196);
Location endPoint=new Location("locationA");
endPoint.setLatitude(17.375775);
endPoint.setLongitude(78.469218);
double distance=startPoint.distanceTo(endPoint);
here "distance" is our required result in Meters. I hope it will work for android.
这里“距离”是我们在米中所需的结果。我希望它适用于android。
#4
5
in build.gradle:
compile 'com.google.maps.android:android-maps-utils:0.4'
and then:
public static Double distanceBetween(LatLng point1, LatLng point2) {
if (point1 == null || point2 == null) {
return null;
}
return SphericalUtil.computeDistanceBetween(point1, point2);
}
#5
4
If you have two Location Objects Location loc1
and Location loc2
you do
如果您有两个位置对象位置loc1和位置loc2
float distance = loc1.distanceTo(loc2);
If you have longitude and latitude values you use the static distanceBetween()
function
如果您有经度和纬度值,则使用静态distanceBetween()函数
float[] results = new float[1];
Location.distanceBetween(startLatitude, startLongitude,
endLatitude, endLongitude, results);
float distance = results[0];
#6
2
private String getDistanceOnRoad(double latitude, double longitude,
double prelatitute, double prelongitude) {
String result_in_kms = "";
String url = "http://maps.google.com/maps/api/directions/xml?origin="
+ latitude + "," + longitude + "&destination=" + prelatitute
+ "," + prelongitude + "&sensor=false&units=metric";
String tag[] = { "text" };
HttpResponse response = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
response = httpClient.execute(httpPost, localContext);
InputStream is = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(is);
if (doc != null) {
NodeList nl;
ArrayList args = new ArrayList();
for (String s : tag) {
nl = doc.getElementsByTagName(s);
if (nl.getLength() > 0) {
Node node = nl.item(nl.getLength() - 1);
args.add(node.getTextContent());
} else {
args.add(" - ");
}
}
result_in_kms = String.format("%s", args.get(0));
}
} catch (Exception e) {
e.printStackTrace();
}
return result_in_kms;
}
#7
1
Why are you writing the code for calculating the distance by yourself?
你为什么要编写自己计算距离的代码?
Check the api's in Location class
检查位置类中的api
#8
1
private float distanceFrom_in_Km(float lat1, float lng1, float lat2, float lng2) {
if (lat1== null || lng1== null || lat2== null || lng2== null)
{
return null;
}
double earthRadius = 6371000; //meters
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));
float dist = (float) (earthRadius * c);
return dist;
}
#9
0
You should use Haversine Distance Formulas
您应该使用Haversine Distance Formulas
Haversine Formulas used to calculate the great distance between two points on the earth.
Haversine Formulas用于计算地球上两点之间的距离。
public void haversine(double lat1, double lon1, double lat2, double lon2) {
double Rad = 6372.8; //Earth's Radius In kilometers
// TODO Auto-generated method stub
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
lat1 = Math.toRadians(lat1);
lat2 = Math.toRadians(lat2);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
double c = 2 * Math.asin(Math.sqrt(a));
haverdistanceKM = Rad * c;
}
#10
0
public float getMesureLatLang(double lat,double lang) {
Location loc1 = new Location("");
loc1.setLatitude(getLatitute());// current latitude
loc1.setLongitude(getLangitute());//current Longitude
Location loc2 = new Location("");
loc2.setLatitude(lat);
loc2.setLongitude(lang);
return loc1.distanceTo(loc2);
// return distance(getLatitute(),getLangitute(),lat,lang);
}
#11
0
Get KM from lat long
从lat获得KM
public static float getKmFromLatLong(float lat1, float lng1, float lat2, float lng2){
Location loc1 = new Location("");
loc1.setLatitude(lat1);
loc1.setLongitude(lng1);
Location loc2 = new Location("");
loc2.setLatitude(lat2);
loc2.setLongitude(lng2);
float distanceInMeters = loc1.distanceTo(loc2);
return distanceInMeters/1000;
}