Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Here's my javascript. It 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 suggest.

  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?

Many thanks.

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted
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.

share|improve this answer
    
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? –  Victor Dec 5 '12 at 14:44
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.