因此,當用戶輸入地址時,它添加了很好的標記,用戶還可以將標記移動到新的位置並檢索它的lat和lng。但是它沒有做到的是:谷歌地圖API獲取經緯度和替換標記?
- 獲取緯度和經度從地址(當引腳被添加到頁面)
- 如果地址的變化,它增加了一個新的標誌,而不是替換現有的一個。
下面的代碼:
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: -34.397, lng: 150.644}
});
var geocoder = new google.maps.Geocoder();
document.getElementById('postcode').addEventListener('keyup', function() {
geocodeAddress(geocoder, map);
});
}
function geocodeAddress(geocoder, resultsMap) {
var address = document.getElementById('address1').value + '\xa0' + document.getElementById('address2').value +','+ document.getElementById('postcode').value;
console.log(address);
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
//if marker exist, replace it if not create it.
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: address,
draggable:true,
//get lng and lat and save it to 2 seperate variables?
});
google.maps.event.addListener(marker, 'dragend', function(marker){
var latLng = marker.latLng;
currentLatitude = latLng.lat();
currentLongitude = latLng.lng();
console.log(currentLatitude);
console.log(currentLongitude);
$("#latitude").val(currentLatitude);
$("#longitude").val(currentLongitude);
});
} else {
$('#error').append('<div class="alert alert-danger">Address not found please try again</div>');
$(".alert-danger").fadeOut(5000);
}
});
}
抱歉,我知道的setMap(空),這是愚蠢的闕但我的大腦拒絕正常工作,這段代碼去哪裏? –
您在哪個代碼中提到...現在有兩個部分.. – scaisEdge
您之前沒有使用過'new google.maps.Marker',該標記需要空值檢查 –