我正在使用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);
});
当用户搜索某个位置时会触发此处理程序。它会在最接近的结果上创建一个标记。
我想返回标记,以便稍后在其他处理程序中使用它:
google.maps.event.addListener(marker,'dragend',function() {
$('#inputLocalisation').val(marker.getPosition());
});
拖动标记时触发此项,但我需要标记对象。如何访问以前创建的标记?
答案 0 :(得分:1)
所以你应该在创建我假设的标记的同时添加该事件监听器?
在事件监听器功能中,您可以使用关键字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());
});