studio google example current android google-maps android-location

example - get my location google maps android studio



Obtener la distancia entre dos ubicaciones en Android? (10)

Necesito distanciarme entre dos ubicaciones, pero necesito obtener una distancia como la línea azul en la imagen.

Intento el siguiente:

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

pero obtengo distancia de línea roja.


Como Chris Broadfoot es correcto, para analizar las routes[].legs[].distance JSON devueltas routes[].legs[].distance

"legs" : [ { "distance" : { "text" : "542 km", "value" : 542389 }

Utilizar:

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"));


Para encontrar la distancia entre 2 ubicaciones:

  1. Cuando abre la aplicación por primera vez, vaya a "su línea de tiempo" desde el menú desplegable en la parte superior izquierda.

  2. Una vez que se abra la nueva ventana, elija una de las configuraciones en su menú superior derecho y elija "agregar lugar".

  3. Agregue sus lugares y nómbrelos como punto 1, punto 2 o cualquier nombre fácil de recordar.

  4. Una vez que se hayan agregado y marcado sus lugares, regrese a la ventana principal de su aplicación de Google.

  5. Haga clic en el círculo azul con la flecha en la parte inferior derecha.

  6. Se abrirá una nueva ventana, y puede ver en la parte superior hay dos campos de texto en los que puede agregar su "ubicación" y "ubicación de distancia".

  7. Haga clic en cualquier campo de texto y escriba su ubicación guardada en el punto 3.

  8. Haga clic en el otro campo de texto y agregue su próxima ubicación guardada.

  9. Al hacerlo, Google Maps calculará la distancia entre las dos ubicaciones y le mostrará la ruta azul en el mapa.


Prueba esto:

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

Espero que esto ayude.


Puede usar el siguiente método de clase de ubicación en android (si tiene lat, longs de ambas ubicaciones) el método devuelve la distancia aproximada en metros.

distancia void estática pública Entre (inicio dobleLatitud, doble inicioLongitud, extremo dobleLatitud, extremo dobleLongitud, flotante [] resultados)

Explicación:

Calcula la distancia aproximada en metros entre dos ubicaciones, y opcionalmente los rodamientos iniciales y finales del camino más corto entre ellos. La distancia y el rumbo se definen usando el elipsoide WGS84.

La distancia calculada se almacena en los resultados [0]. Si los resultados tienen una longitud 2 o superior, la marca inicial se almacena en los resultados [1]. Si los resultados tienen una longitud de 3 o superior, el rumbo final se almacena en los resultados [2]. Parámetros:

StartLatitude: la latitud inicial

startLongitude la longitud inicial

endLatitude la latitud final

endLongitude la longitud final

resultados una serie de flotadores para contener los resultados


Utiliza la API de indicaciones de Google Maps . Deberá solicitar las instrucciones a través de HTTP. Puede hacerlo directamente desde Android o a través de su propio servidor.

Por ejemplo, indicaciones desde Montreal a Toronto :

GET http://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&sensor=false

Terminarás con algo de JSON. En las routes[].legs[].distance , obtendrás un objeto como este:

"legs" : [ { "distance" : { "text" : "542 km", "value" : 542389 },

También puede obtener la información de la polilínea directamente del objeto de respuesta.


Utilizar esta:

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


prueba este código

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


puedes usar este código

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


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


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