Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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) {
        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')
        } 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() {

  // Add click listener to marker for reverse geocoding
  google.maps.event.addListener(map, 'click', function(event) {
    google.maps.event.addListener(marker, 'drag', function() {

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?

share|improve this question
up vote 1 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

Your Answer


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.