未捕获的类型错误:无法读取属性';fitBounds';谷歌地图(markrWithlabel js)中未定


Uncaught TypeError: Cannot read property 'fitBounds' of undefined with google map( markerWithlabel js)

我想在谷歌地图上显示多个位置,但它给出了错误

"未捕获的类型错误:无法读取未定义"的属性"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.
    });

由于有两次var map声明,因此您正在对map变量进行阴影处理。删除initMap()函数中的var

您的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>