简体   繁体   English

通过 Android 的意图启动 Google Maps Directions

[英]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.我的应用程序需要显示从 A 到 B 的 Google 地图方向,但我不想将 Google 地图放入我的应用程序 - 相反,我想使用 Intent 启动它。 Is this possible?这可能吗? If yes, how?如果是,如何?

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.要从当前位置开始导航,请删除saddr参数和值。

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.但是,这将为用户提供一个对话框,供用户选择通过浏览器或 Google 地图打开它。

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: 2017 年 5 月,谷歌为通用的、跨平台的谷歌地图 URL 推出了新的 API:

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

You can use Intents with the new API as well.您也可以将 Intent 与新 API 结合使用。

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:这有点偏离主题,因为您要求提供“方向”,但您也可以使用 Android 文档中描述的地理 URI 方案:

http://developer.android.com/guide/appendix/g-app-intents.html 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.使用“geo:latitude,longitude”的问题是谷歌地图只以你的点为中心,没有任何图钉或标签。

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.如果您使用查询参数“geo:lat,lon?q=name”来标记您的地理点,它会使用查询进行搜索并忽略纬度/经度参数。

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).注意(@TheNail):不适用于 Maps v.7(撰写本文时的最新版本)。 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另请参阅带有位置的 Google 地图 7.0.0 的意图

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.虽然目前的答案很好,但没有一个完全符合我的要求,我只想打开地图应用程序,为每个源位置和目的地添加一个名称,使用地理 URI 方案对我不起作用根本没有,地图网络链接没有标签,所以我想出了这个解决方案,它本质上是其他解决方案和评论的合并,希望它对其他查看这个问题的人有所帮助。

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.为了完整起见,如果用户没有安装地图应用程序,那么捕获 ActivityNotFoundException 将是一个好主意,然后我们可以在没有地图应用程序限制的情况下再次启动该活动,我们可以很确定我们永远不会得到到最后的 Toast,因为互联网浏览器也是启动此 url 方案的有效应用程序。

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

PS 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 PS 在我的例子中使用的任何纬度或经度都不能代表我的位置,任何与真实位置的相似之处纯属巧合,也就是我不是来自非洲:P

EDIT:编辑:

For directions, a navigation intent is now supported with google.navigation对于路线,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);

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

Open Google Maps using Intent with different Modes:使用不同模式的 Intent 打开 Google 地图:

We can open Google Maps app using intent:我们可以使用 Intent 打开 Google Maps 应用:

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.这里,“mode=b”是自行车。

We can set driving, walking, and bicycling mode by using:我们可以使用以下方法设置驾驶、步行和骑车模式:

  • d for driving d 开车
  • w for walking w 步行
  • b for bicycling b 骑自行车

You can find more about intent with google maps here .您可以在此处找到有关 Google 地图意图的更多信息。

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 .你可以在这里查看我的原始答案。

Well you can try to open the built-in application Android Maps by using the Intent.setClassName method.那么您可以尝试使用Intent.setClassName方法打开内置应用程序 Android Maps。

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

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 .根据google docs ,显然有 23 个航路点的限制。 Not sure if that applies to Android too.不确定这是否也适用于 Android。

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:或者,如果您想通过 location 显示,请使用:

google.navigation:q=a+street+address

More Info here: Google Maps Intents for Android此处的更多信息: Android 版 Google Maps Intents

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

A nice kotlin solution, using the latest cross-platform answer mentioned by lakshman sai...一个不错的 kotlin 解决方案,使用 lakshman sai 提到的最新跨平台答案...

No unnecessary Uri.toString and the Uri.parse though, this answer clean and minimal:虽然没有不必要的 Uri.toString 和 Uri.parse ,但这个答案干净且最小:

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

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

Google DirectionsView with source location as a current location and destination location as given as a string Google DirectionsView ,源位置为当前位置,目标位置为字符串

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.在上面的destinationCityName是一个字符串变量,根据需要修改它。

to open maps app which is in HUAWEI devices which contains HMS:打开包含 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: HMS检查:

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)

if you know point A, point B (and whatever features or tracks in between) you can use a KML file along with your intent.如果您知道 A 点、B 点(以及它们之间的任何特征或轨迹),您可以将 KML 文件与您的意图一起使用。

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有关更多信息,请参阅此 SO 答案

NOTE: this example uses a sample file that (as of mar13) is still online.注意:此示例使用(截至 3 月 13 日)仍然在线的示例文件。 if it has gone offline, find a kml file online and change your url如果它已离线,请在线查找kml文件并更改您的网址

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首先你需要现在你可以使用隐式意图,android文档为我们提供了一个非常详细的常见意图来实现你需要创建一个带有两个参数的新意图的地图意图

  • 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.对于动作,我们可以使用Intent.ACTION_VIEW ,对于 Uri,我们应该构建它,下面我附上了一个示例代码来创建、构建、启动活动。

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

You can Launch Google Maps Directions via an intent on Android through this way您可以通过这种方式在 Android 上通过 Intent 启动 Google Maps Directions

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

    });

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM