440

My app needs to show Google Maps directions from A to B, but I don't want to put the Google Maps into my application - instead, I want to launch it using an Intent. Is this possible? If yes, how?

Reg Edit
  • 6,719
  • 1
  • 35
  • 46
Lars D
  • 8,483
  • 7
  • 34
  • 37

18 Answers18

671

You could use something like this:

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

To start the navigation from the current location, remove the saddr parameter and value.

You can use an actual street address instead of latitude and longitude. However this will give the user a dialog to choose between opening it via browser or Google Maps.

This will fire up Google Maps in navigation mode directly:

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

UPDATE

In May 2017 Google launched the new API for universal, cross-platform Google Maps URLs:

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

You can use Intents with the new API as well.

xomena
  • 31,125
  • 6
  • 88
  • 117
Jan S.
  • 10,328
  • 3
  • 31
  • 36
  • 2
    Not that I am aware of. However, there won't be any dialog if the user has already chosen the default app to open this type of intents to be the map app. – Jan S. Jun 11 '11 at 23:40
  • 112
    If you want to get rid of the dialog you can give the intent a hint as to which package you want to use. Before the startActivity() add this: `intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");` – Jeremy Logan Jun 27 '11 at 17:45
  • and how to forze to show it on the navigator and not on the googlemaps application? – NullPointerException Nov 18 '11 at 11:48
  • @fiXedd Honestly, *that* should be *the* answer, or at least part of it. – Navarr Mar 09 '12 at 20:49
  • 71
    Forcing the user into a specific activity when they may have other apps they prefer seems contrary to the bolt it together Android spirit to me. I would be tempted to let the intent filters take care of things here. – superluminary Jun 10 '12 at 09:20
  • @JanS. , thank you for this great answer. is it possible to show names for the start and end locations? – omer schleifer Jun 13 '13 at 07:26
  • 15
    Navigation intents seem to be officially supported now: https://developers.google.com/maps/documentation/android/intents#launch_turn-by-turn_navigation – Sanketh Katta Feb 15 '15 at 01:59
  • is there any way to get distance from this navigation if i will start map in startActivityforresult(); – Ando Masahashi Jul 28 '15 at 10:09
  • When pressing back button from maps app,there shows a black screen and underlying activity is recreated.Any idea how to fix this? – Jas Oct 14 '15 at 05:05
  • I found error with that code "Unable to find explicit activity class {com.google.android.apps.maps/com.google.android.maps.MapsActivity}; have you declared this activity in your AndroidManifest.xml?" How to fix this? – Mohamad Damba Putrabangga May 17 '16 at 07:50
  • I launched navigation intent view from my application activity successfully. When I press the back button from Navigation View that goes to map activity and then come back to my application. I want to single back to my activity from Navigation view when i press back. – Satheesh Jul 03 '16 at 08:11
  • is there a way to add multiple points by using "google.navigation:q=lat1,lng1;lat2,lng2" I tried this on the destination location but it concatenates all the lat,lng pairs and shows a Error icon, I cant find google api support for multiple destinations – Im Rick James Sep 19 '16 at 12:32
  • Can we show our app icon in maps like uber ola shows their icon in google navigation? – Prashanth Debbadwar Sep 28 '16 at 10:46
  • Does uber or ola uses same technique for directions? – Prashanth Debbadwar Sep 28 '16 at 10:46
  • Is there any limited number to launch the Google Maps App via this mentioned intent ? Like 2400 requests/day or something ? – Sagar Shah Nov 08 '17 at 13:38
  • How can we use features like "Avoid Highways, Tolls" using the universal URL? – CopsOnRoad Feb 12 '18 at 07:31
  • Google Maps URL works on iOS but not on Android for me, on Android, it just opens the google maps in browser. – sojim2 Aug 04 '19 at 02:43
  • Is there any way to Open polyline or List of Lat/Long in Google Map via Intent, – mini developer Apr 21 '21 at 06:44
133

This is a little off-topic because you asked for "directions", but you can also use the Geo URI scheme described in the Android Documentation:

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

The problem using "geo:latitude,longitude" is that Google Maps only centers at your point, without any pin or label.

That's quite confusing, especially if you need to point to a precise place or/and ask for directions.

If you use the query parameter "geo:lat,lon?q=name" in order to label your geopoint, it uses the query for search and dismiss the lat/lon parameters.

I found a way to center the map with lat/lon and display a pin with a custom label, very nice to display and useful when asking for directions or any other action:

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

NOTE (by @TheNail): Not working in Maps v.7 (latest version at the time of writing). Will ignore the coordinates and search for an object with the given name between the parentheses. See also Intent for Google Maps 7.0.0 with location

Community
  • 1
  • 1
Murphy
  • 4,858
  • 2
  • 24
  • 31
  • 3
    Nice, the default geo:0,0 just moves the map there. This solution ["geo:0,0?q=37.423156,-122.084917 (" + name + ")"] allows you to put in your own marker name. Thanks. – gnac Aug 31 '11 at 05:36
  • Above also works with Uri.parse("geo:0,0?q=custom+address (" + name + ")");. Exactly what I want wanted. Thanks. – anargund Oct 31 '11 at 04:07
  • 4
    Works great - fyi doesn't appear to work in conjunction with the "z" query parameter (zoom level) – scolestock Jan 06 '12 at 21:33
  • Works great thank you. When user clicks the pin on the map, it opens page which consists of Maps, Direction and Call. I wish there is a way to make call button available as well. – tasomaniac Aug 26 '12 at 20:52
  • 1
    Is it possible to set the default transit mode in the intent. By default the car option is selected. Can I set Walking as the default mode? – Bear Jan 07 '13 at 17:32
  • 6
    Why don't you use `geo:37.423156,-122.084917?q=37.423156,-122.084917 ...`? – rekire Jan 31 '13 at 08:38
  • @Murphy , this works great , thanks. any way to display more than one locartion this way? – omer schleifer Jun 13 '13 at 06:55
  • The scheme suggested in the answer (with the brackets and name) is not working any more in the latest version of google maps. It will search for an object with the given name and ignore the coordinates. Rekire' s suggestion is working (so without the name) – The Nail Jul 27 '13 at 19:31
  • 1
    Make sure you urlEncode the label parameter. I had issues with special characters like space. – Ethan Jan 31 '18 at 03:05
106

Although the current answers are great, none of them did quite what I was looking for, I wanted to open the maps app only, add a name for each of the source location and destination, using the geo URI scheme wouldn't work for me at all and the maps web link didn't have labels so I came up with this solution, which is essentially an amalgamation of the other solutions and comments made here, hopefully it's helpful to others viewing this question.

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

To use your current location as the starting point (unfortunately I haven't found a way to label the current location) then use the following

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

For completeness, if the user doesn't have the maps app installed then it's going to be a good idea to catch the ActivityNotFoundException, then we can start the activity again without the maps app restriction, we can be pretty sure that we will never get to the Toast at the end since an internet browser is a valid application to launch this url scheme too.

        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.S. Any latitudes or longitudes used in my example are not representative of my location, any likeness to a true location is pure coincidence, aka I'm not from Africa :P

EDIT:

For directions, a navigation intent is now supported with google.navigation

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);
Hassnain Jamil
  • 1,651
  • 17
  • 21
David Thompson
  • 2,902
  • 2
  • 18
  • 21
  • 2
    This is a great answer David! Also do you know how to really start the navigation while inside the navigation app? At its present state, the user has to click 'Start Navigation' one final time. I searched Google for any parameter to pass, but couldn't find any. – Nirmal Feb 14 '15 at 00:04
  • When pressing back button from maps app,there shows a black screen and underlying activity is recreated.Any idea how to fix this? – Jas Oct 14 '15 at 05:05
  • @Jas remove intent.setclassname method – Ameen Maheen Dec 10 '15 at 07:28
  • hi, the above code is taking long time to launch the default map app in android version 4.4.2 , 4.4.4, and 5.0.2. Its launching fine in 5.1 and Marshmallow version. Could you please help in solving this issue. – OnePunchMan Jan 05 '17 at 06:34
  • I would now suggest using intent.SetPackage instead of intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity"); I will update the answer to reflect this. – David Thompson Mar 09 '17 at 11:53
  • for "current_location" as source/starting point, you can use "my location" in this link > "https://www.google.com/maps/dir/?api=1&origin=my location&destination=Pike+Place+Market+Seattle+WA&travelmode=bicycling" Ref> https://developers.google.com/maps/documentation/urls/guide – Vivek Solanki Jul 24 '17 at 07:54
  • Hi @DavidThompson, thank you so much for your answer, but I face a little trouble about showing the label of the destination, I want keep the label name as what it is, like your example: "Where the party is at", but Google Map auto replace the label name with the exact address (123 ABC Street...). Do you have any idea to prevent this? – Phong Nguyen Apr 02 '18 at 03:26
29

Using the latest cross-platform Google Maps URLs: Even if google maps app is missing it will open in browser

Example 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);
lakshman sai
  • 481
  • 6
  • 14
23

Open Google Maps using Intent with different Modes:

We can open Google Maps app using intent:

val gmmIntentUri = Uri.parse("google.navigation:q="+destintationLatitude+","+destintationLongitude + "&mode=b")
val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri)
mapIntent.setPackage("com.google.android.apps.maps")
startActivity(mapIntent)

Here, "mode=b" is for bicycle.

We can set driving, walking, and bicycling mode by using:

  • d for driving
  • w for walking
  • b for bicycling

You can find more about intent with google maps here.

Note: If there is no route for the bicycle/car/walk then it will show you "Can't find the way there"

You can check my original answer here.

SANAT
  • 8,489
  • 55
  • 66
8

Well you can try to open the built-in application Android Maps by using the Intent.setClassName method.

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);
gvlasov
  • 18,638
  • 21
  • 74
  • 110
8

For multiple way points, following can be used as well.

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

First set of coordinates are your starting location. All of the next are way points, plotted route goes through.

Just keep adding way points by concating "/latitude,longitude" at the end. There is apparently a limit of 23 way points according to google docs. Not sure if that applies to Android too.

Adeel Tariq
  • 81
  • 1
  • 3
  • Actually don't use the exact coordinates I put here. They are in the middle of no where somewhere with no roads around so that won't work. – Adeel Tariq May 23 '17 at 12:00
7

A nice kotlin solution, using the latest cross-platform answer mentioned by lakshman sai...

No unnecessary Uri.toString and the Uri.parse though, this answer clean and minimal:

 val intentUri = Uri.Builder().apply {
      scheme("https")
      authority("www.google.com")
      appendPath("maps")
      appendPath("dir")
      appendPath("")
      appendQueryParameter("api", "1")
      appendQueryParameter("destination", "${yourLocation.latitude},${yourLocation.longitude}")
 }.build()
 startActivity(Intent(Intent.ACTION_VIEW).apply {
      data = intentUri
 })
Vin Norman
  • 2,749
  • 1
  • 22
  • 33
6

If you interested in showing the Latitude and Longitude from the current direction , you can use this :

Directions are always given from the users current location.

The following query will help you perform that . You can pass the destination latitude and longitude here:

google.navigation:q=latitude,longitude

Use above as:

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

Or if you want to show via location , use:

google.navigation:q=a+street+address

More Info here: Google Maps Intents for Android

WannaBeGeek
  • 979
  • 14
  • 32
6

to open maps app which is in HUAWEI devices which contains HMS:

const val GOOGLE_MAPS_APP = "com.google.android.apps.maps"
const val HUAWEI_MAPS_APP = "com.huawei.maps.app"

    fun openMap(lat:Double,lon:Double) {
    val packName = if (isHmsOnly(context)) {
        HUAWEI_MAPS_APP
    } else {
        GOOGLE_MAPS_APP
    }

        val uri = Uri.parse("geo:$lat,$lon?q=$lat,$lon")
        val intent = Intent(Intent.ACTION_VIEW, uri)
        intent.setPackage(packName);
        if (intent.resolveActivity(context.packageManager) != null) {
            context.startActivity(intent)
        } else {
            openMapOptions(lat, lon)
        }
}

private fun openMapOptions(lat: Double, lon: Double) {
    val intent = Intent(
        Intent.ACTION_VIEW,
        Uri.parse("geo:$lat,$lon?q=$lat,$lon")
    )
    context.startActivity(intent)
}

HMS checks:

private fun isHmsAvailable(context: Context?): Boolean {
var isAvailable = false
if (null != context) {
    val result =
        HuaweiApiAvailability.getInstance().isHuaweiMobileServicesAvailable(context)
    isAvailable = ConnectionResult.SUCCESS == result
}
return isAvailable}

private fun isGmsAvailable(context: Context?): Boolean {
    var isAvailable = false
    if (null != context) {
        val result: Int = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context)
        isAvailable = com.google.android.gms.common.ConnectionResult.SUCCESS == result
    }
    return isAvailable }

fun isHmsOnly(context: Context?) = isHmsAvailable(context) && !isGmsAvailable(context)
Mina Farid
  • 5,041
  • 4
  • 39
  • 46
5

This is what worked for me:

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);
}
JediCate
  • 396
  • 4
  • 8
4

try this

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);
daker
  • 3,430
  • 3
  • 41
  • 55
4

Google DirectionsView with source location as a current location and destination location as given as a string

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

In the above destinationCityName is a string varaiable modified it as required.

Cid
  • 14,968
  • 4
  • 30
  • 45
Ramesh kumar
  • 935
  • 14
  • 16
2
            Uri uri = Uri.parse("google.navigation:q=" + Latitude + "," + longitude + "&mode=d"); 
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.setPackage("com.google.android.apps.maps");
            startActivity(intent);
1

if you know point A, point B (and whatever features or tracks in between) you can use a KML file along with your 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);

for more info, see this SO answer

NOTE: this example uses a sample file that (as of mar13) is still online. if it has gone offline, find a kml file online and change your url

Community
  • 1
  • 1
tony gil
  • 9,424
  • 6
  • 76
  • 100
  • 1
    When pressing back button from maps app,there shows a black screen and underlying activity is recreated.Any idea how to fix this? – Jas Oct 14 '15 at 05:05
  • @Jas, google changed lots of its APIs and this behavior has maybe changed as well. i have been using open street maps exclusively for quite some time now, so i would be able to help you. :) – tony gil Oct 22 '15 at 13:12
1

You can Launch Google Maps Directions via an intent on Android through this way

btn_search_route.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String source = et_source.getText().toString();
            String destination = et_destination.getText().toString();

            if (TextUtils.isEmpty(source)) {
                et_source.setError("Enter Soruce point");
            } else if (TextUtils.isEmpty(destination)) {
                et_destination.setError("Enter Destination Point");
            } else {
                String sendstring="http://maps.google.com/maps?saddr=" +
                        source +
                        "&daddr=" +
                        destination;
                Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                        Uri.parse(sendstring));
                startActivity(intent);
            }
        }

    });
jay patoliya
  • 611
  • 7
  • 8
1

Try this one updated intent google map address location find out

 Uri gmmIntentUri1 = Uri.parse("geo:0,0?q=" + Uri.encode(address));
    Intent mapIntent1 = new Intent(Intent.ACTION_VIEW, gmmIntentUri1);
    mapIntent1.setPackage("com.google.android.apps.maps");
    startActivity(mapIntent1);
0

First you need to now that you can use the implicit intent, android documentation provide us with a very detailed common intents for implementing the map intent you need to create a new intent with two parameters

  • Action
  • Uri

For action we can use Intent.ACTION_VIEW and for Uri we should Build it ,below i attached a sample code to create,build,start the activity.

 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);
    }
  • 1
    Using Uri.Builder only works for absolute URIs, in the form of: `://?#`, not opaque URIs `:#`. The above code yields the following URI: `geo:/0%2C0?Eiffel%20Tower` which causes the Google Maps app to crash. Even [the official documentation](https://developers.google.com/maps/documentation/android-api/intents) uses raw/opaque URIs for this very reason. The correct code would then be: `Uri.parse("geo:0,0?q=" + Uri.encode("Eiffel Tower"))` – Alex Bitek Feb 11 '17 at 18:29
  • Also see this answer for an explanation for why your answer doesn't work: http://stackoverflow.com/a/12035226/313113 – Alex Bitek Feb 11 '17 at 18:38