我正在使用谷歌地图API V3。
使用JavaScript,如何根据标记的坐标打开信息窗口?
我正在使用谷歌地图API V3。
使用JavaScript,如何根据标记的坐标打开信息窗口?
以下是一个Jsfiddle示例,展示了如何在地图之外与标记进行JavaScript交互。需要将标记及其信息窗口保存在数组中以便访问。我创建了两个随机标记,并使用数组ships中的坐标。
以下为HTML代码和两个通用链接,点击链接1会将地图居中到标记1并弹出其信息窗口,点击链接2则相反:
<div id='map_canvas'></div>
<a href='#' onClick="gotoPoint(1);">Click for marker 1</a><br/>
<a href='#' onClick="gotoPoint(2);">Click for marker 2</a>
在 createMarker 函数中,我存储了创建的标记及其关联的信息窗口,并将其推入全局范围的标记数组。悬停在标记上时,它将打开其关联的信息窗口:
function createMarker(lat, lon, html) {
var newmarker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lon),
map: map,
title: html
});
newmarker['infowindow'] = new google.maps.InfoWindow({
content: html
});
google.maps.event.addListener(newmarker, 'mouseover', function() {
this['infowindow'].open(map, this);
});
marker.push(newmarker);
}
在gotoPoint函数中,我传入一个标记号码作为参数。我基本上通过使用new google.maps.LatLng
将地图的中心设置为标记的位置,然后调用marker[myPoint-1].position.lat();
和marker[myPoint-1].position.lng();
来获取标记的经纬度,并使用marker[myPoint-1]['infowindow'].open(map, marker[myPoint-1]);
打开与之关联的信息窗口:
function gotoPoint(myPoint){
map.setCenter(new google.maps.LatLng(marker[myPoint-1].position.lat(), marker[myPoint-1].position.lng()));
marker[myPoint-1]['infowindow'].open(map, marker[myPoint-1]);
}
如果对这个示例有任何问题,请告诉我。