سؤال

Hi I am using google map javascript api v3

here is my code to draw polylines.

for(var i=0; i < addressArr.length; i++){
     geocoder.geocode( { 'address': addressArr[i]}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {

        point = results[0].geometry.location;
        place.push(results[0].address_components[1].long_name);

        flightPlanCoordinates.push(point);
        if(flightPlanCoordinates.length == addressArr.length){
        flightPath = new google.maps.Polyline({path: flightPlanCoordinates,strokeColor: "#FF0000",strokeOpacity: 0.50,strokeWeight: 2 });
        flightPath.setMap(map);
        }

addressArr is an Array of addresses

The problem is in my flightPlanCoordinates ,they are not in the order in which i am passing the addressArr from the for loop.
suppose i am passing addressArr=[1,2,3,4] the my flightPlanCoordinates becomes [2,3,1,4]. Can any suggest what is happening.

هل كانت مفيدة؟

المحلول

That's simply because inside of loop you make asyncronous call(geocoder.geocode) which takes different ammount of time to accomplish. So suggest that it takes 1 second to geocode second element in array and 3 seconds to geocode first element. Then obviously the second element's callback function will be called before the first and thus will push it into flightPlanCoordinates on first position.

Just call sort() method on the array inside of second if statement in your code to solve the issue.

UPDATE:

var i = 0;
function geocode(){
    geocoder.geocode({
        'address': addressArr[i]
    },
    function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            point = results[0].geometry.location;
            place.push(results[0].address_components[1].long_name);
            flightPlanCoordinates.push(point);
            i++;
            if(addressArr[i] != null)
                geocode();

            if (flightPlanCoordinates.length == addressArr.length) {
                flightPath = new google.maps.Polyline({
                    path: flightPlanCoordinates,
                    strokeColor: "#FF0000",
                    strokeOpacity: 0.50,
                    strokeWeight: 2
                });
                flightPath.setMap(map);
            }
        }
    }
}
geocode();

نصائح أخرى

No too sure why its returning the values like that but you could just sort the array and that will resolve your problem. flightPlanCoordinates.sort();

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top