0

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!

3 Answers 3

1

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);
 });
0

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.

2
  • its giving me problems with the .each() function. It seems to be populating the array a lot more than it should? Commented Nov 22, 2012 at 23:58
  • Yes, $(this) works too. You can just omit the div argument then. Commented Nov 23, 2012 at 0:31
0
var beaches = [];    
$('div[data-location][data-id]').each(function() {
    beaches.push([
        [$(this).attr('data-id')]
            .concat(
                $(this).attr('data-location').split(","),
                [2]
            )
    ]);
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.