谷歌地图显示来自 json 的路线

Lau*_*tiu 3 javascript google-maps google-maps-api-3

我有下一个问题来显示来自基本 JSON 的路由。

  1. 我在后端打了一个电话: curl to https://maps.googleapis.com/maps/api/directions/json
  2. 我将响应 json 发送回前端
  3. 在前端,我尝试仅出于视觉目的渲染路由,为什么我不使用 google v3 API 来获取 routeResponse 对象是因为我不想复制与后端使用相同的配置并在前端转换为 requestObejct
  4. 我尝试基于来自 googleapi 的后端 json 创建 routeResponse json:
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]
});
Run Code Online (Sandbox Code Playgroud)

问题是我看到了开始和结束标记 + 腿点,但没有看到这条线:

在此处输入图片说明

我应该怎么做才能有正确的显示路线?与流程代码类似:

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)

ame*_*iel 8

鉴于您向 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 之间进行转换:

  1. 路由服务(后端Directions API)负责为“我如何从 A 到 B”问题提供路由解决方案?它对您将使用其结果的方式不做任何假设。

  2. 绘图服务(前端google.maps.DirectionsRenderer 类)负责向用户显示通用(但详细)路线的视觉表示。只要您提供正确的结构(它期待google.maps.DirectionsResult的实例),它就不会假设您从何处获得路由解决方案。

当您选择使用 curl 或任何其他服务器端库来请求路线时,您填补了空白,将前端 google.maps.DirectionsRequest对象转换为正确 URL 编码的Directions API Request。现在您需要将Directions API Response 转换google.maps.DirectionsResult的实例。

即使 JSON 结果主要是一个对象,渲染器也不会也不应该假设应该使用普通对象来实例化路径、路线、位置或腿。