Googlemap javascript v3 + php

时间:2015-11-18 09:08:16

标签: javascript php jquery

我已经在数据库顶部建立连接,并以关联数组

获取记录
<? php include_once('dbconnect.php');
$sql = "SELECT * FROM maps";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
    $arr[] = $row;
}
?>

我的底部有一个脚本,但下面是</body>标记:

  <script>
  function initialize(){
  var map;
   var locations = <?php echo json_encode($arr); ?>;
  var strfy=JSON.stringify(locations);

   var location=JSON.parse(locations);

   var mapoption={
    zoom: 10,
   center: new google.maps.LatLng(-33.92, 151.25),
   mapTypeId: google.maps.MapTypeId.SATELLITE
   };
   map = new google.maps.Map(document.getElementById('map'), mapoption);

   var infowindow= new google.maps.InfoWindow();
   var marker,i;
   for(i=0;i<location.length;i++){

     marker = new google.maps.Marker({
    position: new google.maps.LatLng(location.query.lat,location.query.longits),
      map: map
      });
    google.maps.event.addListener(marker, 'click', (function(marker, i) {
      return function() {
      infowindow.setContent(location.name);
      infowindow.open(map, marker);
      }
     })(marker, i));
     }

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

我身体部位在中间

<div id="map" style="width:100%;height:380px;"></div>

记录已在关联数组中成功获取,但我遇到了问题。当我运行localhost时,它不会向我显示googlemap但会显示错误

enter image description here

是什么导致了这个问题?

2 个答案:

答案 0 :(得分:0)

添加google maps api时,请检查您是否明确设置了协议。 对于localhost,它应该以http://或https://开头。它会告诉浏览器从Web加载库而不是文件系统。

答案 1 :(得分:0)

似乎var位置是一个全局变量 - window.location,因此当您尝试分配值时,浏览器会重定向,只需重命名,或执行类似的操作

(函数(){  YOUR_CODE_HERE })();

用于封装

你需要这样的想法:

function initialize() {
    var map;
    var locations = <? php echo json_encode($arr); ?> ;// $arr must be not an associative array

    //2 next strings doesn't metter
    //var strfy = JSON.stringify(locations);
    //var location = JSON.parse(strfy);

    alert(locations);
    var mapoption = {
        zoom: 10,
        center: new google.maps.LatLng(-33.92, 151.25),
        mapTypeId: google.maps.MapTypeId.SATELLITE
    };
    map = new google.maps.Map(document.getElementById('map'), mapoption);

    var infowindow = new google.maps.InfoWindow();
    var marker;
    for (var i = 0; i < locations.length; i++) {
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i].lat, locations[i].longits),
            map: map
        });
        google.maps.event.addListener(marker, 'click', (function (marker, i) {
            return function () {
                infowindow.setContent(locations[i].name);
                infowindow.open(map, marker);
            }
        })(marker, i));
    }
}
google.maps.event.addDomListener(window, 'load', initialize);