Lau*_*tiu 3 javascript google-maps google-maps-api-3
我有下一个问题来显示来自基本 JSON 的路由。
curl to https://maps.googleapis.com/maps/api/directions/jsonRun Code Online (Sandbox Code Playgroud)data.overviewRouteDirectionSteps.bounds = new google.maps.LatLngBounds( data.overviewRouteDirectionSteps.bounds.southwest,data.overviewRouteDirectionSteps.bounds.northeast); data.overviewRouteDirectionSteps.overview_path=google.maps.geometry.encoding.decodePath(data.overviewRouteDirectionSteps.overview_polyline.points); data.overviewRouteDirectionSteps.overview_polyline = data.overviewRouteDirectionSteps.overview_polyline.points; directionsDisplay.setDirections({ request: { travelModel: 'DRIVING' }, routes: [data.overviewRouteDirectionSteps] });
问题是我看到了开始和结束标记 + 腿点,但没有看到这条线:
我应该怎么做才能有正确的显示路线?与流程代码类似:
directionsService.route(request, function(response, status) {
if (status === 'OK') {
console.log(response);
directionsDisplay.setDirections(response);
} else {
console.log('Directions request failed due to ' + status);
}
})
Run Code Online (Sandbox Code Playgroud)
鉴于您向 Directions Web 服务发出后端请求,并且您将完整的响应传递给前端,您需要处理结果以使它们成为有效的 DirectionResult 对象。这就是我要做的:
if (response.status === 'OK') {
var bounds = new google.maps.LatLngBounds(response.routes[0].bounds.southwest, response.routes[0].bounds.northeast);
response.routes[0].bounds = bounds;
response.routes[0].overview_path = google.maps.geometry.encoding.decodePath(response.routes[0].overview_polyline.points);
response.routes[0].legs = response.routes[0].legs.map(function (leg) {
leg.start_location = new google.maps.LatLng(leg.start_location.lat, leg.start_location.lng);
leg.end_location = new google.maps.LatLng(leg.end_location.lat, leg.end_location.lng);
leg.steps = leg.steps.map(function (step) {
step.path = google.maps.geometry.encoding.decodePath(step.polyline.points);
step.start_location = new google.maps.LatLng(step.start_location.lat, step.start_location.lng);
step.end_location = new google.maps.LatLng(step.end_location.lat, step.end_location.lng);
return step;
});
return leg;
});
directionsDisplay.setDirections(response);
}
Run Code Online (Sandbox Code Playgroud)
基本上,当您使用google.maps.DirectionsService类时,库会代表您负责在两个 actor 之间进行转换:
路由服务(后端Directions API)负责为“我如何从 A 到 B”问题提供路由解决方案?它对您将使用其结果的方式不做任何假设。
绘图服务(前端google.maps.DirectionsRenderer 类)负责向用户显示通用(但详细)路线的视觉表示。只要您提供正确的结构(它期待google.maps.DirectionsResult的实例),它就不会假设您从何处获得路由解决方案。
当您选择使用 curl 或任何其他服务器端库来请求路线时,您填补了空白,将前端 google.maps.DirectionsRequest对象转换为正确 URL 编码的Directions API Request。现在您需要将Directions API Response 转换回google.maps.DirectionsResult的实例。
即使 JSON 结果主要是一个对象,渲染器也不会也不应该假设应该使用普通对象来实例化路径、路线、位置或腿。