This nests Google Maps Event Listener for click or drag. How should I refactor the last part where it reuses the function getAddressComponents()
? If there are other parts to be refactored, please do offer suggestions.
function getAddressComponents() {
geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
clearValue();
if (results[0]) {
// Get address_components
for (var i = 0; i < results[0].address_components.length; i++)
{
var addr = results[0].address_components[i];
if (addr.types[0] == 'street_address')
$('#spot_street_address').val(addr.long_name);
}
} else {
alert('No results found. Please revise the address or adjust the map marker.');
}
}
});
}
// Add drag listener to marker for reverse geocoding
google.maps.event.addListener(marker, 'drag', function() {
getAddressComponents();
});
// Add click listener to marker for reverse geocoding
google.maps.event.addListener(map, 'click', function(event) {
marker.setMap(null);
addMarker(event.latLng);
getAddressComponents();
google.maps.event.addListener(marker, 'drag', function() {
getAddressComponents();
});
});
The map will have existing marker, which is draggable and geocodable. But once I click on the map to create a marker (thus, removing the existing marker), that new marker as I drag it, can't be geocodable. That's why I have to nest the listener to get it working. What have I done wrong?