hellomello
hellomello

Reputation: 8585

Using javascript/jquery to populate array from a dynamic list for Google Maps API

I have a search application that gets a list of places. These locations and names will be in a attribute tag such as

<div data-location="22.4245,-15.000" data-id="place_name_1">Place Name 1</div>
<div data-location="23.4435,-13.000" data-id="place_name_2">Place Name 2</div>
<div data-location="27.42755,-13.000" data-id="place_name_3">Place Name 3</div>

And I'm using this information to get markers in Google Maps. I'm looking at their documentation and I was wondering how do I get this information into an array in javascript? If you look at the link, there's an array like so:

var beaches = [ 
  ['Bondi Beach', -33.890542, 151.274856, 4], 
  ['Coogee Beach', -33.923036, 151.259052, 5], 
  ['Cronulla Beach', -34.028249, 151.157507, 3], 
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2], 
  ['Maroubra Beach', -33.950198, 151.259302, 1] 
]; 

What would I need to do to get data from html to array in javascript?

Thanks!

Upvotes: 0

Views: 2330

Answers (3)

Andrew
Andrew

Reputation: 2780

Using jQuery, you can parse the HTML:

var beaches = [];

// iterate over all <div>s (assuming they're always in that format)
$('div').each(function (index, div) {

    // break apart the comma-separated coordinates in the data-location attribute
    var coords = $(div).data('location').split(',');

    // add this location to the beaches array (with z-index 0)
    beaches.push([$(div).text(), coords[0], coords[1], 0]);

});

Some applications may encode coordinates as longitude, latitude. If that's the case, you'll want to swap the positions of coords, that is: beaches.push([$(div).text(), coords[1], coords[0], 0]);.

Keep in mind that the array is quite specific to the example (actually the setMarkers() function) you're referring to.

Upvotes: 0

GiantHornet
GiantHornet

Reputation: 102

try this:

var $beaches = [];

$.find("div").each(function(){

     var $loc = [];

    $loc.push($(this).html());
    $loc.push($(this).attr("data-location"));
    $loc.push($(this).attr("data-id"));
    $loc.push(2);

    $beaches.push($loc);
 });

Upvotes: 1

sroes
sroes

Reputation: 15053

var beaches = [];    
$('div[data-location][data-id]').each(function() {
    beaches.push([
        [$(this).attr('data-id')]
            .concat(
                $(this).attr('data-location').split(","),
                [2]
            )
    ]);
});

Upvotes: 0

Related Questions