在Google Maps v3 Api上显示lat long

时间:2011-12-28 23:55:40

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

我的数据库中有纬度和经度现在我想在Google地图v3上显示多个标记,但问题是当我检索我的值(lat,long)时,只有一个标记在地图上显示,因为它的最后一个值是循环和其他值被覆盖..

我的代码就是这个..

 <?php foreach($this->searchResult as $result): ?>
 <ul>
 <li><?php echo $result['user_id']; ?>

 <li><?php echo $result['name']; ?></li>
 <li><?php echo $result['Latitude']; ?></li>
 <li><?php echo $result['Longitude']; ?></li>


<li><?php if($result['country'] == '1'){echo "America"; }else{ echo "";} ?></li>
 <a href="<?php echo 
 $this->url(array('controller'=>'search',  'action'=>'get-Details',            'id'=>$result['id']))?>">Details</a> 
</ul>
<script type="text/javascript">
 var berlin = new google.maps.LatLng(40.7144, -74.0061);

  var lat = new Array();
  var lon = new Array();
  var lat = <?php echo $result['Latitude']; ?>;
  var lon = <?php echo $result['Longitude']; ?>;


 var neighborhoods = [

  new google.maps.LatLng(lat,lon)

 ];


 var markers = [];
 var iterator = 0;

 var map;

 function initialize() {
var mapOptions = {
  zoom: 4,
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  center: berlin
};


  map = new google.maps.Map(document.getElementById("map_canvass"),
        mapOptions);

}

 function drop() {
for (var i = 0; i < neighborhoods.length; i++) {
  setTimeout(function() {
    addMarker();
  }, i * 200);
}

}

  function addMarker() {
  markers.push(new google.maps.Marker({
  position: neighborhoods[iterator],
  map: map,
  draggable: false,
  animation: google.maps.Animation.DROP
}));
   iterator++;
}
</script>


<?php endforeach;?>



<?php  echo $this->paginationControl($this->searchResult, 'Sliding', 'pagination.phtml'); ?>

<div id="map_canvass" style="width:800px; height:300px"></div>

<button id="drop" onclick="drop()">Drop Markers</button>

1 个答案:

答案 0 :(得分:0)

不要在foreach循环中创建脚本标记。更好的方法是生成数据对象并将其作为JS变量呈现到脚本块中。然后,您可以在JS中遍历此数据对象并添加标记。

json_encode是打印数据对象的好方法。 http://www.php.net/manual/en/function.json-encode.php

伪代码:

<script type="text/javascript">
    (function () {
        var neighborhoods = <?php echo json_encode($allHoodsIWantToAdd);?>;
        ...
    }());
</scritp>