[java] Launching Google Maps Directions via an intent on Android

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?

This question is related to java android google-maps android-intent

The answer is


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

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


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

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

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

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

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.


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


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.


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

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

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.


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

    });

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


to open maps app that 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) {
            appLifecycleObserver.isSecuredViewing = true
            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)

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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to google-maps

GoogleMaps API KEY for testing Google Maps shows "For development purposes only" java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion How to import JSON File into a TypeScript file? Googlemaps API Key for Localhost Getting "Cannot call a class as a function" in my React Project ERROR: Google Maps API error: MissingKeyMapError This page didn't load Google Maps correctly. See the JavaScript console for technical details Google Maps API warning: NoApiKeys ApiNotActivatedMapError for simple html page using google-places-api

Examples related to android-intent

Kotlin Android start new Activity Open Facebook Page in Facebook App (if installed) on Android Android - Adding at least one Activity with an ACTION-VIEW intent-filter after Updating SDK version 23 Not an enclosing class error Android Studio Parcelable encountered IOException writing serializable object getactivity() Sending intent to BroadcastReceiver from adb How to pass ArrayList<CustomeObject> from one activity to another? Android Intent Cannot resolve constructor Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT Android - java.lang.SecurityException: Permission Denial: starting Intent