Uzyskaj odległość między dwoma lokalizacjami w Androidzie?
Muszę uzyskać odległość między dwoma lokalizacjami, ale muszę uzyskać odległość jak Niebieska linia na zdjęciu.
I try next:
public double getDistance(LatLng LatLng1, LatLng LatLng2) {
double distance = 0;
Location locationA = new Location("A");
locationA.setLatitude(LatLng1.latitude);
locationA.setLongitude(LatLng1.longitude);
Location locationB = new Location("B");
locationB.setLatitude(LatLng2.latitude);
locationB.setLongitude(LatLng2.longitude);
distance = locationA.distanceTo(locationB);
return distance;
}
/ Align = "left" / 10 answers
Użyj Google Maps Directions API . Musisz poprosić o wskazówki przez HTTP. Możesz to zrobić bezpośrednio z Androida lub za pośrednictwem własnego serwera.
Na przykład, kierunki z Montreal do Toronto :
GET http://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&sensor=false
Skończysz z jakimś JSONEM. W routes[].legs[].distance
otrzymasz taki obiekt:
"legs" : [
{
"distance" : {
"text" : "542 km",
"value" : 542389
},
Można również uzyskać informacje o polyline bezpośrednio z obiektu response.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-19 11:09:43
Ponieważ Chris Broadfoot jest poprawny, aby parsować zwrócił JSON routes[].legs[].distance
"legs" : [
{
"distance" : {
"text" : "542 km",
"value" : 542389
}
Użycie:
final JSONObject json = new JSONObject(result);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONArray newTempARr = routes.getJSONArray("legs");
JSONObject newDisTimeOb = newTempARr.getJSONObject(0);
JSONObject distOb = newDisTimeOb.getJSONObject("distance");
JSONObject timeOb = newDisTimeOb.getJSONObject("duration");
Log.i("Diatance :", distOb.getString("text"));
Log.i("Time :", timeOb.getString("text"));
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-14 13:56:12
public String getDistance(final double lat1, final double lon1, final double lat2, final double lon2){
String parsedDistance;
String response;
Thread thread=new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL("http://maps.googleapis.com/maps/api/directions/json?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric&mode=driving");
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
InputStream in = new BufferedInputStream(conn.getInputStream());
response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
JSONObject jsonObject = new JSONObject(response);
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");
parsedDistance=distance.getString("text");
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return parsedDistance;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-06 19:35:23
Możesz użyć następującej metody klasy Location w Androidzie (jeśli masz lat, longs obu lokalizacji) metoda zwraca przybliżoną odległość w metrach.
public static void distanceBetween (double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results)
Explanation:
Oblicza przybliżoną odległość w metrach między dwoma lokalizacjami oraz opcjonalnie początkowe i końcowe położenie najkrótszej ścieżki między nimi. Odległość i łożysko są określone za pomocą elipsoidy WGS84.
Obliczona odległość jest przechowywana w results[0]
. Jeśli wyniki mają długość 2 lub większa, łożysko początkowe jest przechowywane w results[1]
. Jeśli wyniki mają długość 3 lub większą, ostateczne łożysko jest przechowywane w results[2]
.
parametry:
Szerokość startowa - szerokość startowa
Początek długości początkowej
Endszerokość końcówki
EndLongitude długość końcowa
Wyniki tablica pływaków do przechowywania wyników
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-20 09:12:55
Użyj Tego:
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;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-14 13:55:13
Spróbuj tego:
private double calculateDistance(double fromLong, double fromLat,
double toLong, double toLat) {
double d2r = Math.PI / 180;
double dLong = (toLong - fromLong) * d2r;
double dLat = (toLat - fromLat) * d2r;
double a = Math.pow(Math.sin(dLat / 2.0), 2) + Math.cos(fromLat * d2r)
* Math.cos(toLat * d2r) * Math.pow(Math.sin(dLong / 2.0), 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double d = 6367000 * c;
return Math.round(d);
}
Mam nadzieję, że to pomoże.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-19 09:17:29
Możesz użyć dowolnego API odległości. Google API jest jednym z najbardziej popularnych, ale istnieją również pewne alternatywy, takie jak Distance Matrix API: Documentation
Jest bardzo łatwy w użyciu, ponieważ nie musisz przepisywać kodu, jeśli wcześniej korzystałeś z Google Maps API.
Oto przykład żądania:
Get: https://api.distancematrix.ai/distancematrix?origins=51.4822656,-0.1933769&destinations=51.4994794,-0.1269979&key=<your_access_token>
I oto przykład odpowiedzi:
{
"destination_addresses":["Westminster Abbey, Westminster,
London SW1P 3PA, UK"],
"origin_addresses":["Chapel, Fulham, London SW6 1BA, UK"],
"rows":[
{
"elements":[
{
"distance":{
"text": "4.7 miles",
"value": 7563.898
},
"duration":{
"text": "28 min",
"value": 1680
},
"duration_in_traffic":{
"text": "28 min",
"value": 1680
},
"status": "OK"
}
]
}
],
"status": "OK"
}
Zastrzeżenie: pracuję w firmie, która tworzy ten API.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-05-07 14:19:24
Wypróbuj ten kod
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;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-01 00:22:04
private String getDistance(double lat2, double lon2){
Location loc1 = new Location("A");
loc1.setLatitude("A1");
loc1.setLongitude("B1");
Location loc2 = new Location("B");
loc2.setLatitude(lat2);
loc2.setLongitude(lon2);
float distanceInMeters = loc1.distanceTo(loc2);
float mile = distanceInMeters / 1609.34f;
String sm = String.format("%.2f", mile);
return sm;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-12 12:52:09
Aby znaleźć odległość między 2 lokalizacjami:
Po pierwszym otwarciu aplikacji przejdź do "Twoja oś czasu" z menu rozwijanego w lewym górnym rogu.
Po otwarciu nowego okna wybierz z ustawień w prawym górnym menu i wybierz "Dodaj miejsce".
Dodaj swoje miejsca i nazwij je jak punkt 1, punkt 2 lub dowolna łatwa nazwa do zapamiętania.
Po dodaniu i oznaczeniu miejsc wróć do głównego okna w Google app.
Kliknij na niebieskim kółku ze strzałką w prawym dolnym rogu.
Otworzy się nowe okno, a na górze znajdują się dwa pola tekstowe, w których można dodać "z lokalizacji" i "odległość".
Kliknij dowolne pole tekstowe i wpisz zapisaną lokalizację w punkcie 3.
Kliknij inne pole tekstowe i dodaj swoją następną zapisaną lokalizację.
W ten sposób Google Maps obliczy odległość pomiędzy dwoma lokalizacjami i pokazać niebieską ścieżkę na mapie.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-05 04:42:21