Google地图显示来自json的路线

时间:2017-11-07 22:04:04

标签: 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在frontent
  4. 我尝试根据googleapi的后端json创建routeResponse json:
  5. 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]
    });
    

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

    enter image description here

    如何才能拥有正确的展示路线? 与流程代码类似:

    directionsService.route(request, function(response, status) {
        if (status === 'OK') {
            console.log(response);
            directionsDisplay.setDirections(response);
        } else {
            console.log('Directions request failed due to ' + status);
        }
    })
    

1 个答案:

答案 0 :(得分:2)

鉴于您向Directions webservice发出了后端请求,并且您已将完整的响应传递给您的前端,您需要处理结果以使其成为有效的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);
}