Java 通过 Android 上的 Intent 启动 Google 地图路线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2662531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:29:52  来源:igfitidea点击:

Launching Google Maps Directions via an intent on Android

javaandroidgoogle-mapsandroid-intent

提问by Lars D

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?

我的应用程序需要显示从 A 到 B 的 Google 地图路线,但我不想将 Google 地图放入我的应用程序 - 相反,我想使用 Intent 启动它。这可能吗?如果是,如何?

采纳答案by Jan S.

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 saddrparameter 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 结合使用。

回答by Murphy

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

注意(@TheNail):不适用于 Maps v.7(撰写本文时的最新版本)。将忽略坐标并搜索括号之间具有给定名称的对象。另请参阅带有位置的 Google 地图 7.0.0 的意图

回答by tony gil

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. if it has gone offline, find a kml file online and change your url

注意:此示例使用(截至 3 月 13 日)仍然在线的示例文件。如果它已离线,请在线查找kml文件并更改您的网址

回答by David Thompson

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

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

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

回答by Vijay Web Solutions

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

回答by Jonathan Caceres Romero

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

那么您可以尝试使用该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);

回答by Bachiri Taoufiq Abderrahman

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

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

  • Action
  • Uri
  • 行动
  • 乌里

For action we can use Intent.ACTION_VIEWand 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);
    }

回答by Adeel Tariq

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.

只需通过在末尾连接“/纬度,经度”来继续添加航点。根据google docs ,显然有 23 个航路点的限制。不确定这是否也适用于 Android。

回答by JediCate

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

回答by lakshman sai

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