Google地图 - Viewport显示数据库内容中的标记

时间:2014-07-04 14:41:01

标签: ajax google-maps

我需要帮助在视口上显示标记,其中标记信息(title,lat,lng ..)基于数据库。我的工作基于https://developers.google.com/maps/articles/toomanymarkers教程,但当我到达我需要调用服务器的部分时,我遇到了问题。

这是我的脚本,它在空闲时执行。

google.maps.event.addListener(map, 'idle', showMarkers);

function showMarkers(str) {
var bounds = map.getBounds();

 if (window.XMLHttpRequest) {
 // code for IE7+, Firefox, Chrome, Opera, Safari
 xmlhttp=new XMLHttpRequest();
 } else { // code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
 xmlhttp.onreadystatechange=function() {
 if (xmlhttp.readyState==4 && xmlhttp.status==200) {

  var locations =  xmlhttp.responseText;

var marker, i;

for (i = 0; i < locations.length; i++) {  
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),        
  });
  marker.setMap(map);
}
}
}
 xmlhttp.open("GET","locations.php?lat1="+bounds.getNorthEast().lat()+"&lat2="+bounds.getSouthWest().lat(),true);
xmlhttp.send();
}

这是我的locations.php文件

<?php 
$lat1 = $_GET['lat1'];
$lat2 = $_GET['lat2'];

 $sql = "SELECT * FROM product WHERE lat BETWEEN '".$lat2."' AND '".$lat1."'";

  $result = mysqli_query($con,$sql);

 echo '[';
 while($row = mysqli_fetch_array($result)) {  
   echo "['".$row['title']." , ".$row['lat']." , ".$row['lng']."]";
 }
 echo']';
 ?>

我认为问题是我希望locations.php的响应是一个数组,但是xmlhttp.responseText将数组转换为字符串。你有解决方案从我的locations.php获取一个字符串吗? 我已经尝试拆分我的字符串以获得一个数组,但它不能很好地工作。

1 个答案:

答案 0 :(得分:0)

  1. 确保响应有效JSON使用json_encode()

    $result = mysqli_query($con,$sql);
    
    $arr = array();
    
     while($row = mysqli_fetch_array($result)) {
       $arr[] = array($row['title'], $row['lat'], $row['lng']);
     }  
    
    echo json_encode($arr);
    
  2. 使用JSON.parse()将返回的字符串转换为数组

    var locations =  JSON.parse(xmlhttp.responseText);