Friday, February 24, 2012

Finding the address for a given spot

Reverse geocoding estimates the address of a given map point. Result accuracy depends on what information is stored in Google Maps servers.

In this example, an address will be returned after each mouse click anywhere on land.

Click here to open

In addition to the minimal initialization with global variables map and geocoder, an event listener is added to initialize().

function initialize() {
        geocoder = new google.maps.Geocoder();
        map = new google.maps.Map($("map_canvas"),
          mapOptions);
        google.maps.event.addListener(map, 'click',
          function(event) {
            getAddress(event.latLng);
          }
        );
      }


The HTML body contains a form with a text field for the retrieved address, and two zoom controls. By default, the map is zoomed and centered with a mouse click.


A mouse click calls getAddress with the captured latLng. The geocoder checks for two things: whether there is a result for the location, and the status of the geocoding request. In this example, if either value returns zero or not OK, the error is shown in the address field.



      function getAddress(latLng) {
        geocoder.geocode(
          {latLng: latLng},
          function(results, status) {
            if(status == google.maps.GeocoderStatus.OK) {
              if(results[0]) {


                $("text_address").value =
                   results[0].formatted_address;


                // zoom controls, of secondary importance
                if(map.getZoom() < 16) {
                  if($("autoZoom").checked) {
                    map.setCenter(latLng);
                    map.setZoom(map.getZoom() + 2);
                  }
                }


              } 
              else {
                $("text_address").value = "No results";
              }
            }
            else {
              $("text_address").value = status;
            }
          }
        );
      }

No comments:

Post a Comment