Array of destinations with google direction API

廉价感情. 提交于 2019-12-13 04:43:49

问题


I'm new to javascript and I have this problem with google directions :

I have a table that contains the coordinates of different places like :

lieux = [
    {"nom": "place1", "icon": "galerie.png", "coordinates": [46.2018773, 6.1396896]},
    {"nom": "place2", "icon": "galerie.png", "coordinates": [46.1989726, 6.1371983]},
    {"nom": "place3", "icon": "galerie.png",    "coordinates": [46.1976313, 6.1382951]},
    {"nom": "place4", "icon": "galerie.png", "coordinates": [46.1997394, 6.1388766]}
];

I'd like to create direction button for each place that calculate the itinerary to it. Here is the function that calculate the path, it's outside initialiser()

function errorfunction(error){
    console.log(error);
};   

function successfunction(position){
    myLatitude = position.coords.latitude;
    myLongitude = position.coords.longitude;
};

calcul_itin = function() {                                                              
    origin = myLatitude+","+myLongitude;                                                
    for (i = 0; i < place.length; i++) {
        lieuxLat = place[i].coordinates[0];                                             
        lieuxLong = place[i].coordinates[1];
        destination = placeLat+","+placeLong;                                           
    }
    if(origin && destination){
        var request = {
            origin      : origin,
            destination : destination,
            travelMode  : google.maps.DirectionsTravelMode.WALKING                      
        }
        var directionsService = new google.maps.DirectionsService();                    
        directionsService.route(request, function(response, status){                    
            if(status == google.maps.DirectionsStatus.OK){
                direction.setDirections(response);                                      
            }
        });
    }; 
};

But, every button calculate itinerary for the last place of the table, and I don't know how to arrange my code to change that.


回答1:


If I understand correctly what you want is to calculate the shortest (or fastest) path from one location to many destinations, and you need to have detailed path information to actually display these paths on a map.

I think your problem is that you make only a request for one single trip from the origin to the last destination in your list of destinations. All other destinations are overwritten because the request to the Directions Service is located after your loop through the destinations. You need to make a separate request for each trip, and each directions result needs to be rendered separately, by using your own implementation or a separate DirectionsRenderer. Therefore, your call to the Directions Service needs to be inside the for loop. You also need to manage the renderers, as you probably want to remove old renderers when a new call to calcul_itin is made.

The following code illustrates this approach. Probably, you will want to personalise paths and markers.

var directionRenderers = [];    // array for keeping track of renderers
calcul_itin = function(origin) {
    // Remove previous renderers
    for (var i=0; i < directionRenderers.length; i++) {
        directionRenderers[i].setMap(null);
    }
    directionRenderers = [];
    // create a request for each destination
    for (i = 0; i < lieux.length; i++) {    // guess destinations are in lieux...
        var dest = lieux[i].coordinates[0] +','+ lieux[i].coordinates[1];
        var request = {
            origin: origin,     // assume origin is an instance of google.maps.LatLng
            destination: dest,
            travelMode: google.maps.DirectionsTravelMode.WALKING
        };
        var directionsService = new google.maps.DirectionsService(); 
        directionsService.route(request, function(response, status){                    
            if(status == google.maps.DirectionsStatus.OK){
                // create a new DirectionsRenderer for this route
                var dirRenderer = new google.maps.DirectionsRenderer({map: map});
                dirRenderer.setDirections(response);
                directionRenderers.push(dirRenderer);   // track the renderers
            }
        });
    }
};

Note also that Google Directions API has quota and rate limits, and the above approach makes many requests to this service, so be careful not to use too many destinations.

If you only need distance and travel time for multiple origins/destinations, you are better off using the Google Distance Matrix API. But you will not get detailed path information in this case.




回答2:


You keep overwritting the directionsService for each new request. You can't overwrite it until the request has come back from the server. So either chain your requests (call the next when the previous request finishes) or make a separate DirectionsService object for each request.

Note that the DirectionsService:

  1. is subject to a rate limit
  2. is subject to a quota
  3. is asynchronous, requires an interaction with the server. The callback runs when the response comes back from the server.


来源:https://stackoverflow.com/questions/19320146/array-of-destinations-with-google-direction-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!