我需要在两个地方展示谷歌地图。 我对两个地图使用相同的代码(我的意思是我重复使用两个地图的相同代码)。 以下是可以找到这两张地图的屏幕截图的链接。
https://drive.google.com/file/d/0B2JnvvXsAALUdlVzemRVMzNMajF4OFB1V0JXc0RuN1p4eWFV/view - map1
https://drive.google.com/file/d/0B2JnvvXsAALUVGRhNm1HSldhQnpZT3k4S2I2R1YyQkp4OWZz/view - map2
我在bootstarp模式中显示第二张地图(map2)
第一张地图(map1)工作正常。但是在第二张地图(map2)中,虽然我使用了setCenter方法,但是标记没有显示在地图的中心(而是显示在左上角)。 我该怎么做才能将标记放在地图的中心(在第二张地图中)?
下面是我的代码..
initialize: function(options){
//initializing the geocoder
this.geocoder = new google.maps.Geocoder();
this.map;
},
//on show of the view
//onShow is a marionette method, which will be triggered when view is shown
onShow: function(){
var address = this.model.get("address");
//render the map with dummy latLang
this.renderMap();
//render the Map with Proper address
if(address!== ""){
this.renderMapWithProperAddress(address);
}
},
renderMap: function(){
var mapCanvas = document.getElementById("mapCanvas"), self = this,
mapOptions = {
center: new google.maps.LatLng(64.855, -147.833),//dummy latLang
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: false,
mapTypeControl: false,
streetViewControl:false
};
//initializing google map
self.map = new google.maps.Map(mapCanvas, mapOptions);
$("#myModal").on("shown.bs.modal",function(){
google.maps.event.trigger(self.map, "resize");
});
},
renderMapWithProperAddress: function(address){
var self = this,marker;
self.geocoder.geocode( { "address": address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
self.map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: self.map,
position: results[0].geometry.location,
title: address
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
答案 0 :(得分:6)
我的猜测是,在没有看到你的代码的情况下,你需要在显示bootstrap模式后触发map resize事件。
$('#myModal').on('shown.bs.modal', function () {
google.maps.event.trigger(map, 'resize');
});
修改强>:
这是一个完整而有效的例子。根据我的评论,您应该1)触发地图调整大小,2)将地图中心设置为您的标记坐标。
var center = new google.maps.LatLng(59.76522, 18.35002);
function initialize() {
var mapOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: center
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
map: map,
position: center
});
}
$('.launch-map').on('click', function () {
$('#modal').modal({
backdrop: 'static',
keyboard: false
}).on('shown.bs.modal', function () {
google.maps.event.trigger(map, 'resize');
map.setCenter(center);
});
});
initialize();