要使用Google地图Java客户端库获取距离,您可以按照以下步骤进行操作:
以下是一个示例代码片段,展示了如何使用Google地图Java客户端库获取距离:
import com.google.maps.DistanceMatrixApi;
import com.google.maps.DistanceMatrixApiRequest;
import com.google.maps.GeoApiContext;
import com.google.maps.model.Distance;
import com.google.maps.model.DistanceMatrix;
import com.google.maps.model.DistanceMatrixElementStatus;
import com.google.maps.model.LatLng;
public class GoogleMapsDistanceExample {
public static void main(String[] args) {
// 初始化地图服务对象
String apiKey = "YOUR_API_KEY";
GeoApiContext context = new GeoApiContext.Builder().apiKey(apiKey).build();
// 发起距离请求
LatLng origin = new LatLng(37.7749, -122.4194); // 起始点坐标
LatLng destination = new LatLng(34.0522, -118.2437); // 目标点坐标
DistanceMatrixApiRequest request = DistanceMatrixApi.newRequest(context)
.origins(origin)
.destinations(destination);
try {
// 处理距离响应
DistanceMatrix matrix = request.await();
if (matrix.rows[0].elements[0].status == DistanceMatrixElementStatus.OK) {
Distance distance = matrix.rows[0].elements[0].distance;
System.out.println("距离:" + distance.humanReadable);
} else {
System.out.println("无法获取距离信息");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
需要注意的是,在实际使用中,您需要将"YOUR_API_KEY"替换为您在Google开发者控制台创建的有效API密钥。此外,还可以根据需要设置其他可选参数,如语言、单位等。
推荐腾讯云相关产品:腾讯位置服务(https://cloud.tencent.com/product/tianditu)是腾讯云提供的基于地图的开发平台,可用于构建位置相关应用。它提供了丰富的地图展示、定位、路径规划等功能,适用于各种场景,包括导航、出行、物流等。
领取专属 10元无门槛券
手把手带您无忧上云