在Android上使用Google Maps Directions API,可以通过以下步骤实现:
implementation 'com.google.android.gms:play-services-maps:17.0.0'
<application>
标签内添加以下代码:<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY" />
确保将YOUR_API_KEY
替换为你在第一步中获取的API密钥。
<com.google.android.gms.maps.MapView
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
private MapView mapView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
// 在地图准备好后,可以进行相关操作
// 例如,使用Directions API获取路线信息
GoogleDirection.withServerKey("YOUR_API_KEY")
.from(new LatLng(START_LATITUDE, START_LONGITUDE))
.to(new LatLng(END_LATITUDE, END_LONGITUDE))
.execute(new DirectionCallback() {
@Override
public void onDirectionSuccess(Direction direction, String rawBody) {
// 处理路线信息
if (direction.isOK()) {
// 获取路线步骤、距离、持续时间等信息
Route route = direction.getRouteList().get(0);
Leg leg = route.getLegList().get(0);
String distance = leg.getDistance().getText();
String duration = leg.getDuration().getText();
List<Step> stepList = leg.getStepList();
// 在地图上绘制路线
ArrayList<LatLng> directionPositionList = leg.getDirectionPoint();
PolylineOptions polylineOptions = DirectionConverter.createPolyline(MainActivity.this, directionPositionList, 5, Color.RED);
googleMap.addPolyline(polylineOptions);
}
}
@Override
public void onDirectionFailure(Throwable t) {
// 处理失败情况
}
});
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
确保将YOUR_API_KEY
替换为你在第一步中获取的API密钥,并根据需要修改起始和目标地点的经纬度。
这样,你就可以在Android上使用Google Maps Directions API获取并显示路线信息了。请注意,这只是一个简单的示例,你可以根据自己的需求进行定制和扩展。
推荐的腾讯云相关产品:腾讯位置服务(https://cloud.tencent.com/product/tianditu)
领取专属 10元无门槛券
手把手带您无忧上云