我正在实施Google Map API,并在jQuery对话框中显示地图。地图显示正常,但标记位置不在中心,所以请指导我。
如何将标记位置和地图置于中心?
地图代码:
var myCenter = new google.maps.LatLng('@Model.Latitude', '@Model.Longitude');
function initialize() {
var mapProp = {
center: myCenter,
zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var marker = new google.maps.Marker({
position: myCenter,
draggable: false,
animation: google.maps.Animation.DROP,
});
marker.setMap(map);
}
代码打开对话框:
$("#googleMap").dialog({
autoOpen: false,
height: 600,
width: 1000,
resizeStop: function (event, ui) {
google.maps.event.trigger(googleMap, 'resize')
}, open: function (event, ui) {
google.maps.event.trigger(googleMap, 'resize'); },
});
$("#btnLocation").click(function () {
$("#googleMap").dialog("open");
});
HTML:
<div id="googleMap" style="width: 1000px; height: 500px"></div>
<img src="map.jpg" alt="Set Location" id="btnLocation" style="cursor: pointer; height: 35px; width: 35px;" />
答案 0 :(得分:9)
尝试以下方法:
1)在函数map
之外定义marker
和initialize
,我们稍后会调用它们以使地图居中
var myCenter = new google.maps.LatLng('@Model.Latitude', '@Model.Longitude');
// DEFINE YOUR MAP AND MARKER
var map = null, marker = null;
function initialize() {
var mapProp = {
center: myCenter,
zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
marker = new google.maps.Marker({
position: myCenter,
draggable: false,
animation: google.maps.Animation.DROP,
});
marker.setMap(map);
}
2)修改对话框的“打开”事件,以在打开对话框时强制执行地图中心:
$("#googleMap").dialog({
autoOpen: false,
height: 600,
width: 1000,
resizeStop: function (event, ui) {
google.maps.event.trigger(googleMap, 'resize')
},
// OPEN EVENT MODIFIED !
open: function (event, ui) {
google.maps.event.trigger(googleMap, 'resize');
// Force the center of the map
map.setCenter(marker.getPosition());
},
});
尝试让我知道这是否有效;)
答案 1 :(得分:2)
您必须将地图的中心设置为您刚刚点击的坐标的位置。
通过将以下代码添加到click事件处理程序来执行此操作。
map.setCenter('MARKER'.getPosition());
这需要像这样添加到eventlistener:
google.maps.event.addListener(marker, 'click', function() {
map.setCenter(marker.getPosition());
});
完整示例请查看google maps api示例:
https://developers.google.com/maps/documentation/javascript/examples/event-simple