Lanzamiento de Direcciones de Google Maps a través de una intención en Android


Mi aplicación tiene que mostrar las direcciones de Google Maps de A a B, pero no quiero poner los Mapas de Google en mi aplicación, en su lugar, quiero iniciarla usando una Intent. Es esto posible? Si es así, ¿cómo?

Author: Reg Edit, 2010-04-18

13 answers

Podrías usar algo como esto:

Intent intent = new Intent(android.content.Intent.ACTION_VIEW, 
    Uri.parse("http://maps.google.com/maps?saddr=20.344,34.34&daddr=20.5666,45.345"));
startActivity(intent);

Para iniciar la navegación desde la ubicación actual, elimine el parámetro y el valor saddr.

Puede usar una dirección real en lugar de latitud y longitud. Sin embargo, esto le dará al usuario un diálogo para elegir entre abrirlo a través del navegador o Google Maps.

Esto activará Google Maps en el modo de navegación directamente:

Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
    Uri.parse("google.navigation:q=an+address+city"));

UPDATE

En mayo de 2017, Google lanzó la nueva API para URLs universales y multiplataforma de Google Maps:

Https://developers.google.com/maps/documentation/urls/guide

También puede usar Intents con la nueva API.

 556
Author: Jan S.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 14:54:11

Esto está un poco fuera de tema porque pediste "direcciones", pero también puedes usar el esquema Geo URI descrito en la Documentación de Android:

Http://developer.android.com/guide/appendix/g-app-intents.html

El problema de usar "geo:latitud,longitud" es que Google Maps solo se centra en su punto, sin ningún pin o etiqueta.

Eso es bastante confuso, especialmente si necesitas apuntar a un lugar preciso o/y pedir direcciones.

Si usa el parámetro de consulta " geo: lat, lon?q=name " para etiquetar su geopunto, utiliza la consulta para buscar y descarta los parámetros lat/lon.

Encontré una manera de centrar el mapa con lat / lon y mostrar un pin con una etiqueta personalizada, muy agradable de mostrar y útil cuando se pide direcciones o cualquier otra acción:

Intent intent = new Intent(android.content.Intent.ACTION_VIEW, 
Uri.parse("geo:0,0?q=37.423156,-122.084917 (" + name + ")"));
startActivity(intent);

NOTA (por @ TheNail): No funciona en Maps v.7 (última versión en el momento de escribir este artículo). Ignorará las coordenadas y buscará un objeto con el nombre dado entre paréntesis. Véase también Intent para Google Maps 7.0.0 con ubicación

 113
Author: Murphy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:42

Aunque las respuestas actuales son geniales, ninguna de ellas hizo lo que estaba buscando, quería abrir la aplicación maps solo, agregar un nombre para cada una de las ubicaciones de origen y destino, usar el esquema geo URI no funcionaría para mí y el enlace web de maps no tenía etiquetas, así que se me ocurrió esta solución, que es esencialmente una amalgama de las otras soluciones y comentarios hechos aquí, espero que sea útil para otros que ven esta pregunta.

String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?saddr=%f,%f(%s)&daddr=%f,%f (%s)", sourceLatitude, sourceLongitude, "Home Sweet Home", destinationLatitude, destinationLongitude, "Where the party is at");
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);

Para usar su actual ubicación como punto de partida (desafortunadamente no he encontrado una manera de etiquetar la ubicación actual) a continuación, utilice la siguiente

String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?daddr=%f,%f (%s)", destinationLatitude, destinationLongitude, "Where the party is at");
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);

Para completar, si el usuario no tiene la aplicación maps instalada, entonces va a ser una buena idea capturar la ActivityNotFoundException, entonces podemos iniciar la actividad nuevamente sin la restricción de la aplicación maps, podemos estar bastante seguros de que nunca llegaremos al Brindis al final ya que un navegador de Internet es una aplicación válida para iniciar este esquema de url demasiado.

        String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?daddr=%f,%f (%s)", 12f, 2f, "Where the party is at");
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
        intent.setPackage("com.google.android.apps.maps");
        try
        {
            startActivity(intent);
        }
        catch(ActivityNotFoundException ex)
        {
            try
            {
                Intent unrestrictedIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                startActivity(unrestrictedIntent);
            }
            catch(ActivityNotFoundException innerEx)
            {
                Toast.makeText(this, "Please install a maps application", Toast.LENGTH_LONG).show();
            }
        }

P.d. Cualquier latitudes o longitudes utilizadas en mi ejemplo no son representativas de mi ubicación, cualquier semejanza con una ubicación verdadera es pura coincidencia, también conocido como No soy de África: P

EDITAR:

Para las direcciones, una intent de navegación ahora es compatible con Google.navegación

Uri navigationIntentUri = Uri.parse("google.navigation:q=" + 12f +"," + 2f);//creating intent with latlng
Intent mapIntent = new Intent(Intent.ACTION_VIEW, navigationIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);
 83
Author: David Thompson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-02 13:56:56
Uri.Builder directionsBuilder = new Uri.Builder()
        .scheme("https")
        .authority("www.google.com")
        .appendPath("maps")
        .appendPath("dir")
        .appendPath("")
        .appendQueryParameter("api", "1")
        .appendQueryParameter("destination", lat + "," + lon);

startActivity(new Intent(Intent.ACTION_VIEW, directionsBuilder.build()));
 19
Author: Igor Bubelov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-30 12:26:45

Usando la última URL multiplataforma de Google Maps: Incluso si la aplicación de Google Maps falta, se abrirá en el navegador

Ejemplo https://www.google.com/maps/dir/?api=1&origin=81.23444,67.0000&destination=80.252059,13.060604

Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
        .authority("www.google.com").appendPath("maps").appendPath("dir").appendPath("").appendQueryParameter("api", "1")
        .appendQueryParameter("destination", 80.00023 + "," + 13.0783);
String url = builder.build().toString();
Log.d("Directions", url);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
 12
Author: lakshman sai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-05 09:35:15

Bueno, puedes intentar abrir la aplicación integrada Android Maps usando el método Intent.setClassName.

Intent i = new Intent(Intent.ACTION_VIEW,Uri.parse("geo:37.827500,-122.481670"));
i.setClassName("com.google.android.apps.maps",
    "com.google.android.maps.MapsActivity");
startActivity(i);
 7
Author: Jonathan Caceres Romero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-07 07:52:28

Prueba esto

Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr="+src_lat+","+src_ltg+"&daddr="+des_lat+","+des_ltg));
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);
 2
Author: Vijay Web Solutions,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-16 12:12:23

Para múltiples puntos de ruta, los siguientes también se pueden usar.

Intent intent = new Intent(android.content.Intent.ACTION_VIEW, 
    Uri.parse("https://www.google.com/maps/dir/48.8276261,2.3350114/48.8476794,2.340595/48.8550395,2.300022/48.8417122,2.3028844"));
startActivity(intent);

El primer conjunto de coordenadas es su ubicación inicial. Todos los siguientes son puntos de camino, ruta trazada pasa a través.

Simplemente sigue agregando puntos de paso concatando "/latitud,longitud" al final. Aparentemente hay un límite de 23 puntos de camino de acuerdo con google docs . No estoy seguro de si eso se aplica a Android también.

 2
Author: Adeel Tariq,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:05:21

Esto es lo que funcionó para mí:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://maps.google.co.in/maps?q=" + yourAddress));
if (intent.resolveActivity(getPackageManager()) != null) {
   startActivity(intent);
}
 2
Author: JediCate,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-27 15:37:53

Si está interesado en mostrar la Latitud y Longitud desde la dirección actual, puede usar esto:

Las instrucciones siempre se dan desde la ubicación actual del usuario.

La siguiente consulta le ayudará a realizar eso . Puede pasar la latitud y longitud de destino aquí:

google.navigation:q=latitude,longitude

Use lo anterior como:

Uri gmmIntentUri = Uri.parse("google.navigation:q=latitude,longitude");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);

O si desea mostrar a través de ubicación , utilice:

google.navigation:q=a+street+address

Más información aquí: Google Maps Intenta para Android

 2
Author: WannaBeGeek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-07 18:32:28

Si conoce el punto A, el punto B (y cualquier característica o pista intermedia) puede usar un archivo KML junto con su intent.

String kmlWebAddress = "http://www.afischer-online.de/sos/AFTrack/tracks/e1/01.24.Soltau2Wietzendorf.kml";
String uri = String.format(Locale.ENGLISH, "geo:0,0?q=%s",kmlWebAddress);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);

Para más información, ver esto ASÍ respuesta

NOTA: este ejemplo utiliza un archivo de ejemplo que (a partir del 13 de marzo) todavía está en línea. si se ha desconectado, busque un archivo kml en línea y cambie su url

 1
Author: tony gil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:27

Google DirectionsView con la ubicación de origen como ubicación actual y la ubicación de destino como una cadena

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?f=d&daddr="+destinationCityName));
intent.setComponent(new ComponentName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity"));
if (intent.resolveActivity(getPackageManager()) != null) {
    startActivity(intent);
}

En el anterior destinationCityName es una cadena varaiable modificado como sea necesario.

 1
Author: Ramesh kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-07 13:32:01

Primero lo necesitas ahora que puedes usar la intent implícita, la documentación de Android nos proporciona una intents comunes para implementar la intent del mapa, debe crear una nueva intent con dos parámetros

  • Acción
  • Uri

Para la acción podemos usar Intent.ACTION_VIEW y para Uri debemos Construir, a continuación adjunto un código de ejemplo para crear, construir, iniciar la actividad.

 String addressString = "1600 Amphitheatre Parkway, CA";

    /*
    Build the uri 
     */
    Uri.Builder builder = new Uri.Builder();
    builder.scheme("geo")
            .path("0,0")
            .query(addressString);
    Uri addressUri = builder.build();
    /*
    Intent to open the map
     */
    Intent intent = new Intent(Intent.ACTION_VIEW, addressUri);

    /*
    verify if the devise can launch the map intent
     */
    if (intent.resolveActivity(getPackageManager()) != null) {
       /*
       launch the intent
        */
        startActivity(intent);
    }
 0
Author: Bachiri Taoufiq Abderrahman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-21 13:54:38