首页 > 解决方案 > 谷歌最后一次更新后,Direction API 谷歌地图出现问题

问题描述

我需要在我的 android 应用程序中建立一个方向,所以 1-我从 google api 控制台获取新密钥 2-我进行了计费并获得了免费试用 3-我按照谷歌开发人员中的说明进行操作,但我有一个问题 我注意到无效的 Api 密钥我的工作中有一个缺失的部分是谷歌指南中的 第二步第 2 步:将 API 密钥添加到您的应用程序加载方向 API 时,将下面代码中的 YOUR_API_KEY 替换为您从上一步 https 中获得的 API 密钥: //maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&key=YOUR_API_KEY 但我不知道把这段代码放在哪里?最后这是我的所有代码:

    DateTime now = new DateTime();
        try {
            DirectionsResult result = DirectionsApi.newRequest(getGeoContext())
                    .mode(TravelMode.DRIVING).origin(String.valueOf(userLocation))
                    .destination(String.valueOf(sydney)).departureTime(now)
                    .await();
            addMarkersToMap(result,mMap);
            addPolyline(result,mMap);


        } catch (ApiException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
  private GeoApiContext getGeoContext() {
    GeoApiContext geoApiContext = new GeoApiContext();
    return geoApiContext.setQueryRateLimit(3)
            .setApiKey("@string/google_maps_key")
            .setConnectTimeout(1, TimeUnit.SECONDS)
            .setReadTimeout(1, TimeUnit.SECONDS)
            .setWriteTimeout(1, TimeUnit.SECONDS);
}
private void addMarkersToMap(DirectionsResult results, GoogleMap mMap) {
    mMap.addMarker(new MarkerOptions().position(new LatLng(results.routes[0].legs[0].startLocation.lat,results.routes[0].legs[0].startLocation.lng)).title(results.routes[0].legs[0].startAddress));
    mMap.addMarker(new MarkerOptions().position(new LatLng(results.routes[0].legs[0].endLocation.lat,results.routes[0].legs[0].endLocation.lng)).title(results.routes[0].legs[0].startAddress)
            .snippet(getEndLocationTitle(results)));
}
private void addPolyline(DirectionsResult results, GoogleMap mMap) {
    List<LatLng> decodedPath = PolyUtil.decode(results.routes[0].overviewPolyline.getEncodedPath());
    mMap.addPolyline(new PolylineOptions().addAll(decodedPath));
}
private String getEndLocationTitle(DirectionsResult results){
    return  "Time :"+ results.routes[0].legs[0].duration.humanReadable + " Distance :" + results.routes[0].legs[0].distance.humanReadable;    }

标签: javaandroidgoogle-mapsgoogle-directions-api

解决方案


您正在将 Google Directions 的 Javascript API 与您正在使用的 Map SDK for Android 混淆。

在此处查看文档:https ://developers.google.com/maps/documentation/android-sdk/signup

在 AndroidManifest.xml 中,将以下元素添加为元素的子元素,方法是将其插入到结束标记之前:

<meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="YOUR_API_KEY"/>

推荐阅读