Reputation: 3075
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.119562],
[51.499633,-0.124755]
];
Here's what I have tried so far:
var markers = [];
$(function() {
$('.location').each(function() {
var lat = $(this).attr('data-lat'),
lng = $(this).attr('data-lng');
markers.push(lat,lng);
});
console.log(markers);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="location" data-lat="51.503454" data-lng="-0.119562"></div>
<div class="location" data-lat="51.499633" data-lng="-0.124755"></div>
How do I get the lat/lng coordinates in pairs instead of 4 separate values?
Upvotes: 0
Views: 1852
Reputation: 850
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);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="location" data-lat="51.503454" data-lng="-0.119562"></div>
<div class="location" data-lat="51.499633" data-lng="-0.124755"></div>
Upvotes: 0
Reputation: 122037
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)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="location" data-lat="51.503454" data-lng="-0.119562"></div>
<div class="location" data-lat="51.499633" data-lng="-0.124755"></div>
Upvotes: 3