如何获取DirectionsService以在地图上显示路线(Google Maps API)?

时间:2016-03-30 11:18:03

标签: javascript html google-maps

所以我对谷歌地图很陌生,我试图让我的代码显示一条通过4个优化路标的路线。我的代码基于DirectionsService示例(https://developers.google.com/maps/documentation/javascript/examples/directions-waypoints),但我似乎无法理解我所缺少的使代码工作的内容。我已经多次浏览过示例代码,在我看来,我没有遗漏任何东西。目前我的代码只显示我在代码的第一部分设置的标记。非常感谢任何帮助,谢谢。

        //map details, i.e. creates a map of Lucca
var mapOptions = {
    center: new google.maps.LatLng(43.8430,10.5050),
    zoom: 15,
    mapTypeId: google.maps.MapTypeId.SATELLITE
};



//create map
var map = new google.maps.Map(document.getElementById('map'), mapOptions);

//marker details
var markerOptions1 = {
    position: new google.maps.LatLng( 43.8402250, 10.5008083)
};
var markerOptions2 = {
    position: new google.maps.LatLng( 43.83811, 10.50328)
};
var markerOptions3 = {
    position: new google.maps.LatLng( 43.8439194, 10.5032083)
};
var markerOptions4 = {
    position: new google.maps.LatLng( 43.8405167, 10.5038722)
};

//creates markers
var marker1 = new google.maps.Marker(markerOptions1);
var marker2 = new google.maps.Marker(markerOptions2);
var marker3 = new google.maps.Marker(markerOptions3);
var marker4 = new google.maps.Marker(markerOptions4);

//sets markers
marker1.setMap(map);
marker2.setMap(map);
marker3.setMap(map);
marker4.setMap(map);

//marker info windows
var infoWindowOptions1 = {
    content: '1'
};

var infoWindowOptions2 = {
    content: '2'
};

var infoWindowOptions3 = {
    content: '3'
};

var infoWindowOptions4 = {
    content: '4'
};

//Events for clicking on the markers
var infoWindow1 = new google.maps.InfoWindow(infoWindowOptions1);
google.maps.event.addListener(marker1,'click',function(e){
  infoWindow1.open(map, marker1);
});

var infoWindow2 = new google.maps.InfoWindow(infoWindowOptions2);
google.maps.event.addListener(marker2,'click',function(e){
  infoWindow2.open(map, marker2);
});

var infoWindow3 = new google.maps.InfoWindow(infoWindowOptions3);
google.maps.event.addListener(marker3,'click',function(e){
  infoWindow3.open(map, marker3);
});

var infoWindow4 = new google.maps.InfoWindow(infoWindowOptions4);
google.maps.event.addListener(marker4,'click',function(e){
  infoWindow4.open(map, marker4);
});



/*  document.getElementById('submit').addEventListener('click', function() {
    calculateAndDisplayRoute(directionsService, directionsDisplay);
  });
} */


var directionsService = new google.maps.DirectionsService();

directionsDisplay.setMap(map);

function initialize() {
      // Create a renderer for directions and bind it to the map.
    var rendererOptions = {
        map: map
      }
    var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions)

     // Instantiate an info window to hold step text.
      //stepDisplay = new google.maps.InfoWindow();
}




function calcRoute() {

    var waypts = [];

    stop = new google.maps.LatLng( 43.8402250, 10.5008083)
    waypts.push({
        location: stop,
        stopover: true
    });
    stop = new google.maps.LatLng( 43.83811, 10.50328)
    waypts.push({
        location: stop,
        stopover: true
    });
    stop = new google.maps.LatLng( 43.8439194, 10.5032083)
    waypts.push({
        location: stop,
        stopover: true
    });
    stop = new google.maps.LatLng( 43.8405167, 10.5038722)
    waypts.push({
        location: stop,
        stopover: true
    });

    start = new google.maps.LatLng(43.8405167, 10.6038722);
    end = new google.maps.LatLng(43.8405167, 10.6038722);

    var request = {
        origin: start,
        destination: end,
        waypoints: waypts,
        optimizeWaypoints: true,
        travelMode: google.maps.DirectionsTravelMode.WALKING
    };

    directionsService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            var route = response.routes[0];
        }
    });
}

initialize();

1 个答案:

答案 0 :(得分:0)

如果我理解了正确的问题,你可以这样解决。 首先,您需要polyLine:

poly = new google.maps.Polyline({
        path: [],
        strokeColor: "#58FA58",
        strokeOpacity: 1.0,
        strokeWeight: 5
    });

现在您只需要遍历directionService的结果,然后填充polyLine。这可以这样做:

 var bounds = new google.maps.LatLngBounds();
 service.route({
        origin: startAddress,
        destination: endAddress,
        waypoints: wayPoints,
        region: "DE",
        travelMode: google.maps.TravelMode.DRIVING
    }, function (response, status) {
        //console.log(response.routes[0].legs);
        if (status == google.maps.DirectionsStatus.OK) {
            var legs = response.routes[0].legs;
            for (i = 0; i < legs.length; i++) {
                var steps = legs[i].steps;
                for (j = 0; j < steps.length; j++) {
                    //console.log(steps[j].instructions);
                    var nextSegment = steps[j].path;
                    for (k = 0; k < nextSegment.length; k++) {
                        poly.getPath().push(nextSegment[k]);
                        bounds.extend(nextSegment[k]);
                    }
                }
            }
        } else {
            alert("Something went wrong" + status);
        }
     });

最后在地图上设置polyLine:

poly.setMap(map).

应该这样做。

我不确定是否存在任何显着差异,因为没有使用DirectionsRender执行该任务,但是这个提供的代码描绘了考虑给定航点的两点之间的路线。