未捕获的TypeError:无法读取属性' fitBounds'未定义的谷歌地图(markerWithlabel js)

时间:2016-05-02 14:13:53

标签: javascript php google-maps

我想在Google地图上显示多个位置,但它会显示错误

  

"未捕获的TypeError:无法读取属性' fitBounds'未定义"

但它适用于单个位置。

我的JavaScript

jQuery( document ).ready( function($) {

    var  map;
    var bounds = [];



function initMap() {

        var latlng = new google.maps.LatLng(<?php echo $map_lat;?>,<?php echo $map_lng;?>);
        map = new google.maps.Map(document.getElementById('map_canvas'), {
                      zoom: 10,
                      center: latlng
                  });

        var marker = new MarkerWithLabel({
                       position:latlng,
                       draggable: false,
                       raiseOnDrag: true,
                       map:map,
                       labelContent:"test",
                       labelAnchor: new google.maps.Point(22, 0),
                       labelClass: "labels", // the CSS class for the label
                       labelStyle: {opacity: 0.75}
                     });

  bound.push(marker);

}


    google.maps.event.addDomListener(window, 'load', initMap());
        map.fitBounds(bounds); //binding all location on the map.
    });

2 个答案:

答案 0 :(得分:1)

您正在隐藏map变量,因为您有var map声明的2倍。删除var功能中的initMap()

答案 1 :(得分:0)

您的mapinitMap功能的本地。对map.fitBounds的调用也应该在该函数内。

<script type="text/javascript"> 
jQuery( document ).ready( function($) {
    var  map;
    var bounds = new google.maps.LatLngBounds();

    <?php

  /* fetch all location to display on map */
    foreach( $locations as $location ){
                        $name = $location['location_name'];
                        $addr = $location['location_address'];
                        $map_lat = $location['google_map']['lat'];
                        $map_lng = $location['google_map']['lng'];
                        $title = $location["title"];
                  ?> 
 function initMap() {
  <?php 

 if(!empty($map_lat)){
  ?>
               var latlng = new google.maps.LatLng(<?php echo $map_lat;?>,<?php echo $map_lng;?>);
             var map = new google.maps.Map(document.getElementById('map_canvas'), {
                      zoom: 10,
                   center: latlng
                   });
            var marker = new MarkerWithLabel({
                   position:latlng,
                   draggable: false,
                   raiseOnDrag: true,
                   map:map,
                   labelContent:"test",
                   labelAnchor: new google.maps.Point(22, 0),
                   labelClass: "labels", // the CSS class for the label
                   labelStyle: {opacity: 0.75}
            });
    bounds.extend(latlng);
      <?php } ?>
    map.fitBounds(bounds); //binding all location on the map.

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