1
我是基于位置和标记拖动事件的地理编码数据。Google Maps Drag Marker GeoCode
我有以下代码工作正常。
var geocoder;
var map;
var markersArray = [];
var mapOptions = {
center: new google.maps.LatLng(12.971599, 77.594563),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var marker;
function initialize() {
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
codeAddress();
}
google.maps.event.addDomListener(window, 'load', initialize);
$("#gmaps").submit(function() {
codeAddress();
return false;
});
function codeAddress() {
var address = $("#place").val();
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
if (marker) marker.setMap(null);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
draggable: true
});
markersArray.push(marker);
google.maps.event.addListener(map, 'click', function(event) {
clearOverlays() ;
map.panTo(event.latLng);
map.setCenter(event.latLng);
marker = new google.maps.Marker({
map: map,
position: event.latLng,
draggable: true
});
markersArray.push(marker);
document.getElementById('lat').value = marker.getPosition().lat().toFixed(6);
document.getElementById('lng').value = marker.getPosition().lng().toFixed(6);
google.maps.event.addListener(marker, "dragend", function() {
document.getElementById('lat').value = marker.getPosition().lat().toFixed(6);
document.getElementById('lng').value = marker.getPosition().lng().toFixed(6);
});
});
google.maps.event.addListener(marker, "dragend", function() {
document.getElementById('lat').value = marker.getPosition().lat().toFixed(6);
document.getElementById('lng').value = marker.getPosition().lng().toFixed(6);
});
document.getElementById('lat').value = marker.getPosition().lat().toFixed(6);
document.getElementById('lng').value = marker.getPosition().lng().toFixed(6);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
// Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
}
}
我两次注册的拖动事件,只有注册它的点击标记之外的犯规让我捕捉到新创建的标记的拖动事件。
如何通过点击事件添加新标记并重构代码以消除标记的注册事件并将不必要的标记数据存储在数组中时,如何在标记上注册拖动。
你说的“我如何定义和重构代码,以消除标记的阵列中的注册事件和存储不必要的标记数据。”是什么意思?你认为什么是不必要的?为什么? – geocodezip
对于这个问题,你是怎么试图做到这一点的?你遇到了什么问题? – geocodezip
@geocodezip代码工作正常。一旦我初始化标记,我正在注册一个拖动事件。一旦我点击地图上的一个区域,我想删除旧的标记并使其可拖动。两次,我需要注册同一个事件,我觉得自己做错了。 –