我创建了一个Google地图表单,允许用户在文本字段中输入地址并对该条目进行地理编码。然后将标记放在地图上。这工作正常,但我想添加一个额外的addListener,所以当用户点击地图时,它会在他们点击的位置添加另一个引脚。出于某种原因,我的'click'addListener无效。我怎么会有多个像这样添加听众呢?
我附上了我的代码:
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(40.7,-74.0),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var marker = new google.maps.Marker({
map: map,
draggable: true
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(16);
}
var image = "http://www.google.com/mapfiles/marker_green.png";
marker.setIcon(image);
marker.setPosition(place.geometry.location);
var address = '';
if (place.address_components) {
address = [(place.address_components[0] &&
place.address_components[0].short_name || ''),
(place.address_components[1] &&
place.address_components[1].short_name || ''),
(place.address_components[2] &&
place.address_components[2].short_name || '')
].join(' ');
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addListener(map, 'click', function() {
//alert("Hello! I am an alert box!!");
var marker1 = new google.maps.Marker({
map: map,
draggable: true
});
var image = "http://www.google.com/mapfiles/marker_green.png";
marker1.setIcon(image);
marker1.setPosition(new google.maps.LatLng(40.7,-74.0));
map.addOverlay(marker1);
});
谢谢
答案 0 :(得分:1)
您可以使用
google.maps.event.addListener(map,'click', function()...
将onclick事件添加到地图对象。这是一个参考: http://code.google.com/apis/maps/documentation/javascript/reference.html#Map
您还可以使用Google地图绘图工具库: http://code.google.com/apis/maps/documentation/javascript/overlays.html#drawing_tools
答案 1 :(得分:1)
地图点击事件将返回鼠标点击的位置。
更新:要在添加新标记时删除旧标记,您需要将标记的实例存储在侦听器范围之外,然后可以在侦听器事件开始时将其删除。
var singleMarker;
google.maps.event.addListener(map, 'click', function(event) {
//if marker exists, erase marker
if(singleMarker){
singleMarker.setMap(null);
}
singleMarker = new google.maps.Marker({
position: event.latLng, //mouse click position
map: map,
draggable: true,
icon: "http://www.google.com/mapfiles/marker_green.png"
});
});