我可以成功地在一个页面上显示谷歌地图,它工作正常。
我的问题是:
我试图在Bootstrap 3模态中显示谷歌地图。为了达到这个效果,我已经实现了解决方案,但仍然不能让它按照
工作:$('#myModal_map').on('shown.bs.modal', function(){
initMap();
});
这是我到目前为止的编码工作:
<div class="container">
<div class="modal fade" id="myModal_map" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="pull-right btn btn-default" data-dismiss="modal">Close</button>
</div>
<div class="modal-body">
<div id="map"></div>
<script>
var customLabel = {
V: {
label: 'P'
}
};
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(-33.863276, 151.207977),
zoom: 11
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl('map.php', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var id = markerElem.getAttribute('id');
var name = markerElem.getAttribute('name');
var address = markerElem.getAttribute('address');
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customLabel[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
label: icon.label,
title : 'welcome'
});
marker.addListener('click', function() {
infoWindow.setContent('<b>'+name + "</b><br>" + address);
infoWindow.open(map, marker);
});
});
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
/*
$('#myModal_map').on('shown.bs.modal', function(){
initMap();
});
*/
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=my keys-goes-here&callback=initMap">
</script>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
通过为#mapdiv添加一个大小并初始化initmap()来解决这个问题函数内部shown.bs.modal文中
#map {
width:500px;
height:500px;
}
$("#myModal").on("shown.bs.modal", function () {initMap();});