マーカーの位置を変更するとき、マーカーのアドレスを知る必要があります。
基本的に私は方法を持っています:
function addNewMarker(latLng) {
geocoder.geocode({'latLng': latLng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var address = results[0].formatted_address;
var marker = new google.maps.Marker({
position: latLng,
map: map,
draggable: true,
title: address,
});
google.maps.event.addListener(marker, 'dragend', function() {
//marker.setTitle(getGeocodeResults(marker.getPosition()));
marker.setTitle(***THIS IS NEW ADDRESS OF THIS MARKER***);
});
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
ジオコーディング コードを新しいメソッドに抽出すると、次のようになります。
function addNewMarker(latLng){
var address = getGeocodeResults(latLng);
var marker = new google.maps.Marker({
position: latLng,
map: map,
draggable: true,
title: address,
});
google.maps.event.addListener(marker, 'dragend', function() {
marker.setTitle(getGeocodeResults(marker.getPosition()));
});
}
function getGeocodeResults(latLng){
geocoder.geocode({'latLng': latLng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var address = results[0].formatted_address;
return address;
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
この呼び出しは非同期であるため、うまくいきません。そして、マーカーの移動を停止すると、その新しいアドレスが必要になります。これに対する解決策はありますか?