Push lat/long coordinates to an array for Google maps

核能气质少年 提交于 2019-12-24 19:31:31

问题


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>


来源:https://stackoverflow.com/questions/49035097/push-lat-long-coordinates-to-an-array-for-google-maps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!