Javascript 触发谷歌地图标记点击
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6794405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
trigger google maps marker click
提问by mheavers
I have a google map set up to find the user's current location, and center the map at that closest marker to their location. The markers, when clicked, open up an infobox (note this is a little different than an infoWindow - http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/docs/examples.html). What I want to do, however, is automatically open up the nearest marker without the user actually clicking. Here's the code to trigger a marker opening:
我设置了一个谷歌地图来查找用户的当前位置,并将地图居中放置在离他们位置最近的标记处。单击标记时,会打开一个信息框(请注意,这与信息窗口略有不同 - http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/docs/examples.html)。然而,我想要做的是自动打开最近的标记,而无需用户实际点击。这是触发标记打开的代码:
//loop through all locations to add a marker:
addMarker = function(loc) {
var markerLoc = new google.maps.LatLng(loc.Lat, loc.Long);
var marker = new google.maps.Marker({
map: map,
position: markerLoc
});
google.maps.event.addListener(marker, "mousedown", function() {
var infoOpts = {
content: loc.markerText,
boxStyle: { background: "none transparent", width: "180px"},
pixelOffset: new google.maps.Size(-90, 0),
closeBoxMargin: "5px"
};
var ib = new InfoBox(infoOpts);
ib.open(map, marker);
});
markers.push(marker);
};
So somehow I have to trigger the mouseDown function of the appropriate marker, but it has to be done in a function outside of this one. I will have a reference to the appropriate marker in the array (markers[closestmarker]).
所以我必须以某种方式触发适当标记的 mouseDown 函数,但它必须在这个函数之外的函数中完成。我将引用数组中的适当标记(markers[closestmarker])。
回答by kevinstueber
i see that this question has been sitting for quite awhile, but, just in case, this answer may be helpful: trigger google maps marker click
我看到这个问题已经有一段时间了,但是,以防万一,这个答案可能会有所帮助: 触发谷歌地图标记点击
The code would look like this:
代码如下所示:
var marker = new google.maps.Marker({});
new google.maps.event.trigger( marker, 'click' );
Good luck!
祝你好运!
回答by A Averill
I found I needed to attach a click event to the marker like so
我发现我需要像这样将点击事件附加到标记上
var marker = new google.maps.Marker({});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
new google.maps.event.trigger( marker, 'click' );