将Google Maps api latLng坐标存储到js数组

时间:2016-03-10 16:45:49

标签: javascript html google-maps google-maps-api-3

我使用以下代码存储单击地图时创建的标记的坐标,但我似乎找到了将latLng对象转换为数字的方法。

<script>
  var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  var labelIndex = 0;
  var positions = [];

  function initialize() {
    var center = { lat: 37.9755211, lng: 23.7341191 };
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 16,
      center: center
    });
    google.maps.event.addListener(map, 'click', function(event) {
      addMarker(event.latLng, map);

    });
    addMarker(center, map);
  }
  function addMarker(location, map) {
    var marker = new google.maps.Marker({
      position: location,
      label: labels[labelIndex++ % labels.length],
      map: map
    });
    positions.push(location.latitude);
    positions.push(location.longitude);
  }

  google.maps.event.addDomListener(window, 'load', initialize);
</script>


<button onClick="document.write(positions)">DONE</button>

任何想法,为什么这不起作用

1 个答案:

答案 0 :(得分:1)

我认为你应该使用

positions.push(location.lat());
positions.push(location.lng());

请参阅:https://developers.google.com/maps/documentation/javascript/reference#LatLng