Skip to content Skip to sidebar Skip to footer

Push Lat/long Coordinates To An Array For Google Maps

I am trying to generate map markers for a Google map based off data attributes of a set of divs. I need the array to end up looking like this: var markers = [ [51.503454,-0.119

Solution 1:

You could use map method and return array with lat, lng values for each element.

const markers = $('.location').map(function() {
  return [[$(this).data('lat'), $(this).data('lng')]]
}).get();

console.log(markers)
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="location"data-lat="51.503454"data-lng="-0.119562"></div><divclass="location"data-lat="51.499633"data-lng="-0.124755"></div>

Solution 2:

Like that?

var markers = [];

$(function() {
  $('.location').each(function() {
    var lat = $(this).attr('data-lat'),
        lng = $(this).attr('data-lng');
        
    markers.push([+lat,+lng]);
  });
  
  console.log(markers);
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="location"data-lat="51.503454"data-lng="-0.119562"></div><divclass="location"data-lat="51.499633"data-lng="-0.124755"></div>

Post a Comment for "Push Lat/long Coordinates To An Array For Google Maps"