Push lat/long coordinates to an array for Google m

2019-08-27 18:53发布

问题:

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?

回答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)
<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>



回答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);
});
<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>