我想在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.
});
答案 0 :(得分:1)
您正在隐藏map
变量,因为您有var map
声明的2倍。删除var
功能中的initMap()
。
答案 1 :(得分:0)
您的map
是initMap
功能的本地。对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>