我是 Javascript 和 google map api 的新手,我一直在关注这个 link删除标记,但有些我无法使其工作。
基本上我想在用户输入地址并单击按钮时使用按钮生成标记。当用户输入新地址并再次单击按钮时,旧标记将被移除,新标记将固定在新地址上。标记也可拖动。
这是我的js代码:
$('#geocode').live('click',function() {
codeAddress();
return false;
});
function codeAddress() {
var address = document.getElementById('location').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
if (marker) marker.setMap(null);
if (marker) delete marker;
var marker = new google.maps.Marker({
draggable:true,
map: map,
position: results[0].geometry.location
});
var newlat = results[0].geometry.location.lat();
var newlng = results[0].geometry.location.lng();
document.getElementById('mwqsflatlng').value = (newlat+' , '+newlng);
draggeablemarker(marker);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
更新 当我检查 inspect 元素时,它给了我这个错误:
Uncaught TypeError: Cannot call method 'setMap' of undefined
最佳答案
您需要引用您的 marker
对象以便以后能够访问它。如果您想将 map 限制为一次显示一个 marker
,您可以更新标记的 Position
属性,而不是删除并重新创建它。
这是一个可以更改标记位置或创建新标记(如果 map 上不存在标记)的函数。 location 参数是一个 Google LatLng
对象,它与 Geocoder results[0].geometry.location
返回的对象相同。
注意 marker
变量是在函数范围之外定义的。这使您可以在以后引用标记。
var marker;
function placeMarker(location) {
if (marker) {
//if marker already was created change positon
marker.setPosition(location);
} else {
//create a marker
marker = new google.maps.Marker({
position: location,
map: map,
draggable: true
});
}
}
因此对于您的地理编码成功函数,您只需将结果传递给此函数即可。
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
placeMarker(results[0].geometry.location);
}
...
Here is a fiddle of of the concept.您可以单击 map ,标记将移动到所需位置。
关于javascript - Google map api v3 - 在进行地理编码时删除旧标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16571273/