如何在Android Studio中为未知目标实施Google Directions API?

问题描述 投票:0回答:1

我是android studio的初学者,目前正在为我的最终项目创建自行车应用程序。在这些应用中,我需要实现Maps and Direction API。我搜索教程,但它们都设置了目标。在我的应用中,目的地是未知的。

如果我在骑车时显示当前位置(自动)并在地图上画一条线,也可以提供教程吗?我是否可以为此项目使用免费的API密钥?

谢谢...

android google-maps android-studio google-maps-android-api-2 direction
1个回答
0
投票

首先,此方向API并非免费。第二,您需要提供方向API路线的起点和终点。您可以使用当前位置作为起点,如果没有目的地,那么您想在哪里画线?是指从您当前的位置到哪里?

或如果要从起始位置绘制到当前位置的跟踪线,则不需要Direction API,只需要实时位置跟踪,就可以使用当前位置在地图上绘制折线。以下是为您提供帮助的代码。

要将此库放入我们的应用程序,我们需要将以下内容添加到我们的build.gradle文件中。

implement 'com.google.maps:google-maps-services:0.1.20'

//首先初始化地理环境

private GeoApiContext getGeoContext() {
    GeoApiContext geoApiContext = new GeoApiContext();
    return geoApiContext.setQueryRateLimit(3)
            .setApiKey(getString(R.string.directionsApiKey))
            .setConnectTimeout(1, TimeUnit.SECONDS)
            .setReadTimeout(1, TimeUnit.SECONDS)
            .setWriteTimeout(1, TimeUnit.SECONDS);
}

//此代码将从Google Directions api从起点到终点获取结果

    DateTime now = new DateTime();
    DirectionsResult result = DirectionsApi.newRequest(getGeoContext()).mode(TravelMode.DRIVING).origin(origin)
.destination(destination)
.departureTime(now).await();

//您可以使用此方法在地图上添加标记

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));
}
© www.soinside.com 2019 - 2024. All rights reserved.