使用带谷歌地图的for循环添加标记

时间:2013-03-05 01:14:24

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

我想添加一个for循环以循环显示array并将标记添加到地图中,我试图涉足某些内容,但我只是不能休息,拉特/ lon正在以(##.#########,-##.########)格式回显我尝试了很多不同的方法,但它似乎不想将它添加到地图中。

<script>
var initialLocation;
var map;
var markersArray = [];
var gMarkerLatitude = new Array();
var gMarkerLongitude = new Array();
var markers = [];
<?php $i = 0; while($stmt -> fetch()) { ?>  
gMarkerLatitude[<?php echo $i; ?>] = ["<?php echo $gLatitude; ?>"];
gMarkerLongitude[<?php echo $i; ?>] = ["<?php echo $gLongitude; ?>"];
<?php $i++; } ?>
function initialize() {
 var mapOptions = {
  zoom: 15,
  center: new google.maps.LatLng(56.7626362, -111.379652),
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  disableDefaultUI: false,
  zoomControl: true,
  zoomControlOptions: {
    style: google.maps.ZoomControlStyle.LARGE
  }
};

  map = new google.maps.Map(document.getElementById('gmaps'),
  mapOptions);

  google.maps.event.addListener(map, 'click', function(event) {
    var latitude = event.latLng.lat();
    var longitude = event.latLng.lng();
    deleteOverlays();
    addMarker(event.latLng);
    updateTextFields(latitude, longitude);
  });


  google.maps.event.addListener(marker, 'click', function(event) {
    showInfo(window);
  });

}

function updateTextFields(lati, longi) {
  $('#inputLatitude').val(lati);
  $('#inputLongitude').val(longi);
}


function addMarker(location) {
  marker = new google.maps.Marker({
    position: location,
    map: map
  });
  markersArray.push(marker);
}

try {
for (i = 0; i < gMarkerLongitude.length; i++) {
  var marker = new google.maps.Marker({
    map: map,
    position: new google.maps.LatLng(gMarkerLatitude[i],gMarkerLongitude[i])
  })
  alert(new google.maps.LatLng(gMarkerLatitude[i], gMarkerLongitude[i]));
}

}
catch(err) {
  alert(err);
}

function deleteOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
    markersArray.length = 0;
  }
}

function loadScript() {
  var script = document.createElement('script');
  script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&' +
  'callback=initialize';
  document.body.appendChild(script);
}


$(document).ready(function() {
$(window).resize(function () {
    var h = $(window).height(),
        offsetTop = 190; // Calculate the top offset

    $('#gmaps').css('height', (h - offsetTop));
  }).resize();
  loadScript();
});


</script>

2 个答案:

答案 0 :(得分:0)

google.maps.LatLng将两个数字作为参数,但是您传递的数组中包含一个字符串。尝试

gMarkerLatitude[<?php echo $i; ?>] = <?php echo $gLatitude; ?>;
gMarkerLongitude[<?php echo $i; ?>] = <?php echo $gLongitude; ?>;

假设$gLatitude$gLongitude是数字

答案 1 :(得分:0)

哪一部分引发错误?您可以尝试在创建每个标记时将visible: true添加到markerOptions。还要确保您的lat / lng值在specified ranges

之内
Latitude is specified in degrees within the range [-90, 90].
Longitude is specified in degrees within the range [-180, 180].