[英]Return a value from Google maps addListener () function
I am using the Google Maps Javscript API : 我正在使用Google Maps Javscript API:
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
// For each place, get the icon, place name, and location.
markers = [];
var bounds = new google.maps.LatLngBounds();
var image = {
url: places[0].icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for the closest result
marker = new google.maps.Marker({
map: map,
icon: image,
draggable : true,
title: places[0].name,
position: places[0].geometry.location
});
$('#inputLocalisation').val(places[0].geometry.location);
markers.push(marker);
bounds.extend(places[0].geometry.location);
map.fitBounds(bounds);
});
This handler is triggered when the user searches a location. 用户搜索位置时触发此处理程序。 It creates a marker on the closest result.
它在最接近的结果上创建一个标记。
I would like to return the marker to use it later in an other handler : 我想返回标记,以便以后在其他处理程序中使用它:
google.maps.event.addListener(marker,'dragend',function() {
$('#inputLocalisation').val(marker.getPosition());
});
This one is triggered when the marker is dragged, but I need the marker object. 拖动标记时触发此事件,但是我需要标记对象。 How can I access the previously created marker?
如何访问先前创建的标记?
So you should be adding that event listener at the same time as you're creating the marker I assume? 因此,您应该在创建我假设的标记的同时添加该事件监听器?
In the event listener function you can refer to it using the keyword this
. 在事件侦听器函数中,可以使用关键字
this
引用它。
marker = new google.maps.Marker({
map: map,
icon: image,
draggable : true,
title: places[0].name,
position: places[0].geometry.location
});
google.maps.event.addListener(marker,'dragend',function() {
$('#inputLocalisation').val(this.getPosition());
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.