开发者

Modify array with jQuery to get sequenced indexes

开发者 https://www.devze.com 2023-04-07 12:19 出处:网络
This javascript array contains coordinates that I send to Google Maps API to draw a path in the map. Sometimes coordinates[0] is empty because it depends on a previous route that might exist or not (u

This javascript array contains coordinates that I send to Google Maps API to draw a path in the map. Sometimes coordinates[0] is empty because it depends on a previous route that might exist or not (using Google Maps).

This is my code:

coordinates = [];

(between here I look for a previous path (coordinates[0]). In this case we are asuming that it is null. So we have these values:

coordinates[1] = '50,20'; //route 1
coordinates[2] = '10,18'; //route 2
coordinates[3] = '27,34'; //route 3

After that, I draw the path in the map like this:

travel_path = new google.maps.Polyline({
  path: coordinates
});
travel_path.setMap(map);

The problem: When there is no coordinates[0] (that happens when there is no previous segment of the travel path) the .Polyline method throws an error because it needs to receive an array with sequenced indexes starting from 0.

The question: How can I convert my original array to this (compare indexes):

开发者_如何学C
coordinates[0] = '50,20'; //route 1
coordinates[1] = '10,18'; //route 2
coordinates[2] = '27,34'; //route 3


coordinates.shift() removes the first element from the array.

var coordinates = [];
//coordinates[0] = undefined;
coordinates[1] = '50,20'; //route 1
coordinates[2] = '10,18'; //route 2
coordinates[3] = '27,34'; //route 3
coordinates.shift();

coordinates.shift() causes this to happen:

coordinates[0] = coordinates[1];
coordinates[1] = coordinates[2];
coordinates[2] = coordinates[3];
//coordinates[3] is removed.


Like rob said, use shift(), you can do a check to see if coordinates[0] is undefined first.

if( !coordinates[0] )
    coordinates.shift(); 


You can do it by using slice:

coordinates.slice(1);

See it in action.


Use:

travel_path = new google.maps.Polyline({
  path:(function(){
        var arrayCoord=[],k=0;
        for(var key in coordinates){
            arrayCoord[k]=coordinates[key];
            ++k;
        }
        return arrayCoord;
  })()
});
travel_path.setMap(map);
0

精彩评论

暂无评论...
验证码 换一张
取 消