gpt4 book ai didi

android - 如何计算两个位置之间的距离?

转载 作者:行者123 更新时间:2023-11-29 14:59:47 30 4
gpt4 key购买 nike

我想计算两个位置之间的距离,一个是固定的,第二个是用户的位置。
这是我要计算距离的 Activity 。

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;
}
}
}
}

请帮我解决一下这个。

最佳答案

如果您想要 map 上两点之间的距离,那么您可以使用以下功能

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

关于android - 如何计算两个位置之间的距离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49771901/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com