1
\$\begingroup\$

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?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Dec 5, 2012 at 14:23
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$
google.maps.event.addListener(marker, 'drag', fgetAddressComponents);

And you don't need to add it twice. No need to add it in the click handler again.

Otherwise it's mostly ok, except for the == (instead of ===), I just have styling nitpicks to say about this code.

answered Dec 5, 2012 at 14:37
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.