SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Jun 2010
    Posts
    34
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Loop in an Array??

    I would like to put all my coordinates into an array and have a loop display each one but with a Google function.


    Here's the code, which draws the points on google map:

    Code:
     var flightPlanCoordinates = [
        new google.maps.LatLng(37.772323, -122.214897),
        new google.maps.LatLng(21.291982, -157.821856),
        new google.maps.LatLng(-18.142599, 178.431),
        new google.maps.LatLng(-27.46758, 153.027892)
      ];
    I would like to be able to do something like this:

    Code:
    var arrPos = new Array([37.772323, -122.214897], [21.291982, -157.821856], [-18.142599, 178.431], etc. );
    
    var flightPlanCoordinates = [ + 
       for (i=0; i<arrPos.length; i++){
          new google.maps.LatLng(arrPos[0]) + ", "
       }
       + "];"

    I know you can put a loop in an array but is there an alternate method to retrieving the points from the array??

    tks

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,714
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by hiyatran View Post
    I know you can put a loop in an array but is there an alternate method to retrieving the points from the array??
    You can use the push method to add items to an array.

    Note: I've changed arrPos to store the coords as object references, so that it's easier to work with them.

    Code javascript:
    var arrPos = [
        {lat: 37.772323, long: -122.214897},
        {lat: 21.291982, long: -157.821856},
        {lat: -18.142599, long: 178.431}
    ],
        flightPlanCoordinates = [];
     
    for (i = 0; i < arrPos.length; i += 1) {
        flightPlanCoordinates.push(new google.maps.LatLng(arrPos[i].lat, arrPos[i].long));
    }

    Or if you want something more expressive, you can use the forEach method instead of the loop, but in cases such as what you're doing here, a more preferred way is to combine forEach and push by using the map method which uses one array to create another array.

    Code javascript:
    function createGoogleCoords(coords) {
        return new google.maps.LatLng(coords.lat, coords.long);
    }
     
    var arrPos = [
        {lat: 37.772323, long: -122.214897},
        {lat: 21.291982, long: -157.821856},
        {lat: -18.142599, long: 178.431}
    ],
        flightPlanCoordinates = arrPos.map(createGoogleCoords);
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •