【发布时间】:2018-02-26 12:06:06
【问题描述】:
我在一个页面上有一个谷歌地图,上面有几个标记(ajax'ed)。当我单击标记时,会打开一个信息窗口,其中包含详细信息(也是 ajax 处理的)。
我不知道如何使地图居中以使此信息窗口位于地图中间。
GoogleMap 是这样加载的:
var map = new google.maps.Map(document.getElementById('map'), {
zoom: zoomSteps[0],
center: new google.maps.LatLng(46.227638, 2.213749000000007),
mapTypeId: google.maps.MapTypeId.TERRAIN,
mapTypeControl: false,
streetViewControl: false,
styles: [{
featureType: "poi",
stylers: [{
visibility: "off"
}]
}]
});
另外,InfoWindow GoogleMap 对象的生成方式如下:
var infowindow = new google.maps.InfoWindow({
maxWidth: 400,
});
然后我执行一个 ajax 请求来获取数据以在 success: function(data) {} 中的地图上定位标记:
for (i = 0; i < data.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(data[i].latitude, data[i].longitude),
map: map
});
// ...
}
在这个for() {} 循环中,我在每个生成的marker 上添加一个EventListener:
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
// open the info window
infowindow.open(map, marker);
// get css load spinner HTML from ajax and populate a div
var $loader = $('<div/>').addClass('loader').css('overflow', 'hidden').html(data[i].htmlLoader);
// inject this div html code into the infowindow
infowindow.setContent($loader.prop('outerHTML'));
// (1)
// Main function to retrieve data from the SOAP WebService :
// it takes infoWindow html template from data[i].htmlTemplate,
// populates it with data fetched from SOAP WebService and sends it back to here
MainSearchTool.prototype.loadEntityResults(data[i].ws.data, data[i].htmlTemplate, function (htmlTemplate) {
// inject newly fetched results into the infowindow
infowindow.setContent(htmlTemplate);
/**
* Here is where I would like to reposition the center
* of the map to fit the infoWindow
* (2)
*/
});
}
})(marker, i));
在(2) 我尝试(无济于事):
- 调用
map.setCenter(LatLng)与LatLng为marker.getPosition()- 在(1)中调用时有效,但infoWindow 填充了加载微调器,而不是此时的最终模板; - 将 infoWindow
offset()left 和 top 转换为new google.maps.Point()并按照 this question 将其转换回LatLng对象; - 使用多种技术根据特定值重新定位
map;
我似乎找不到任何特定的方法来根据 LatLng 对象来使地图居中,该对象将与 infoWindow 的中心相匹配。
如果您觉得有用,请随时询问任何其他信息。
谢谢。
【问题讨论】:
标签: javascript jquery google-maps google-maps-api-3 position