如何计算两个位置之间的距离?
Posted
技术标签:
【中文标题】如何计算两个位置之间的距离?【英文标题】:How to calculate distance between two locations? 【发布时间】:2018-09-21 03:38:23 【问题描述】:我想计算两个位置之间的距离,一个是固定的,第二个是用户的位置。 这是我要计算距离的活动。
public class CalDist extends AsyncTask<String, Void, String>
protected void onPreExecute()
protected String doInBackground(String... arg0)
StringBuilder stringBuilder = new StringBuilder();
Double dist = 0.0;
try
//destinationAddress = destinationAddress.replaceAll(" ","%20");
//String url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins="+fromLatitude+","+fromLongitude+"&destination=" + toLatitude + "," + toLongitude + "&mode=driving&sensor=false&key=AIzaSyBpFhiStQvyV5dbVXmarXhzhvGgGFOfubM";
//String url = "https://maps.googleapis.com/maps/api/directions/json?origin=" + fromLatitude + "," + fromLongitude + "&destination=" + toLatitude + "," + toLongitude + "&mode=driving&sensor=false&key=AIzaSyBpFhiStQvyV5dbVXmarXhzhvGgGFOfubM";
String url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins="+ fromLatitude + "," + fromLongitude + "&destinations=" + toLatitude + "," + toLongitude + "&mode=driving&sensor=false&key=HereIsMyAPIKey";
HttpPost httppost = new HttpPost(url);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
stringBuilder = new StringBuilder();
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1)
stringBuilder.append((char) b);
catch (ClientProtocolException e)
catch (IOException e)
JSONObject jsonObject = new JSONObject();
try
jsonObject = new JSONObject(stringBuilder.toString());
JSONArray array = jsonObject.getJSONArray("routes");
JSONObject routes = array.getJSONObject(0);
JSONArray legs = routes.getJSONArray("legs");
JSONObject steps = legs.getJSONObject(0);
JSONObject distance = steps.getJSONObject("distance");
Log.i("Distance", distance.toString());
dist = Double.parseDouble(distance.getString("text").replaceAll("[^\\.0123456789]","") );
//Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
catch (JSONException e)
// TODO Auto-generated catch block
e.printStackTrace();
return Double.toString(dist);
@Override
protected void onPostExecute(String result)
Toast.makeText(Payment.this, "ResultCalcDist:" +result, Toast.LENGTH_SHORT).show();
这是我调用函数的方式。
new CalDist().execute();
两点距离计算。
gps = new GPSTracker(Payment.this);
fromLatitude = gps.getLatitude();
fromLongitude = gps.getLongitude();
toLatitude = 23.1914909;
toLongitude = 72.630121;
这是我获取纬度和经度的 GPS 追踪器。
public class GPSTracker extends Service implements LocationListener
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
final private int REQUEST_LOCAION = 12;
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context)
this.mContext = context;
getLocation();
public Location getLocation()
try
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
// no network provider is enabled
else
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled)
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
android.support.v13.app.ActivityCompat.requestPermissions((Activity)getApplicationContext(),
new String[]Manifest.permission.ACCESS_FINE_LOCATION,
REQUEST_LOCAION);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null)
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null)
latitude = location.getLatitude();
longitude = location.getLongitude();
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled)
if (location == null)
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null)
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null)
latitude = location.getLatitude();
longitude = location.getLongitude();
else
showSettingsAlert();
catch (Exception e)
e.printStackTrace();
return location;
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS()
if(locationManager != null)
locationManager.removeUpdates(GPSTracker.this);
/**
* Function to get latitude
* */
public double getLatitude()
if(location != null)
latitude = location.getLatitude();
// return latitude
return latitude;
/**
* Function to get longitude
* */
public double getLongitude()
if(location != null)
longitude = location.getLongitude();
// return longitude
return longitude;
/**
* Function to check GPS/wifi enabled
* @return boolean
* */
public boolean canGetLocation()
return this.canGetLocation;
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert()
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener()
public void onClick(DialogInterface dialog,int which)
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
);
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
public void onClick(DialogInterface dialog, int which)
dialog.cancel();
);
// Showing Alert Message
alertDialog.show();
@Override
public void onLocationChanged(Location location)
@Override
public void onProviderDisabled(String provider)
@Override
public void onProviderEnabled(String provider)
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
@Override
public IBinder onBind(Intent arg0)
return null;
public void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[],
@NonNull int[] grantResults)
switch (requestCode)
case REQUEST_LOCAION:
if ((grantResults.length > 0) && (grantResults[0] +
grantResults[1]) == PackageManager.PERMISSION_GRANTED)
//Call whatever you want
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
return;
请帮帮我。
【问题讨论】:
Calculating distance between two geographic locations的可能重复 【参考方案1】:如果你想要地图上两点之间的距离,那么你可以使用下面的函数
Location locationA = new Location("point A");
locationA.setLatitude(latA);
locationA.setLongitude(lngA);
Location locationB = new Location("point B");
locationB.setLatitude(latB);
locationB.setLongitude(lngB);
float distance = locationA.distanceTo(locationB);
或者,如果您想要公路距离,那么您可以使用下面的 Google api:
http://maps.googleapis.com/maps/api/distancematrix/json?origins=54.406505,18.67708&destinations=54.446251,18.570993&mode=driving&language=en-EN&sensor=false
【讨论】:
我想沿着道路计算距离。 这里是路测距离的APIhttp://maps.googleapis.com/maps/api/distancematrix/json?origins=54.406505,18.67708&destinations=54.446251,18.570993&mode=driving&language=en-EN&sensor=false
..所以你可以调用这个API来寻找路测距离。【参考方案2】:
这里的距离以公里(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);
另一种选择是:
Location loc1 = new Location("");
loc1.setLatitude(lat1);
loc1.setLongitude(lon1);
Location loc2 = new Location("");
loc2.setLatitude(lat2);
loc2.setLongitude(lon2);
float distanceInMeters = loc1.distanceTo(loc2);
【讨论】:
我想沿着道路计算距离。以上是关于如何计算两个位置之间的距离?的主要内容,如果未能解决你的问题,请参考以下文章