Doing a Google Maps reverse geocode and displaying the result as part as HTML content inside an infowindow

1.1k views Asked by At

I have put together this script (note: I'm using jQuery 1.11.2) that gets lat long coordinates from a PHP operation (used for something else) and displays a map with a customized marker and infowindow that includes HTML for formatting the information that is displayed.

<script src="https://maps.googleapis.com/maps/api/js?v=3.20&sensor=false"></script>
<script type="text/javascript">
    var maplat = 41.36058;
    var maplong = 2.19234;

    function initialize() { 
        // Create a Google coordinate object for where to center the map
        var latlng = new google.maps.LatLng( maplat, maplong ); // Coordinates    

        var mapOptions = {
            center: latlng,
            zoom: 3,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            scrollwheel: false,
            streetViewControl: false,
            zoomControl: false,
            mapTypeControl: false,
            disableDoubleClickZoom: true
        };

        map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);

        // CREATE AN INFOWINDOW FOR THE MARKER
        var content = 'This will show up inside the infowindow and it is here where I would like to show the converted lat/long coordinates into the actual, human-readable City/State/Country'
        ;  // HTML text to display in the InfoWindow

        var infowindow = new google.maps.InfoWindow({
            content: content,maxWidth: 250
        });

        var marker = new google.maps.Marker( { 
            position: latlng,     
            map: map,
            title: "A SHORT BUT BORING TITLE",
        });

        google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map,marker);
        });

        infowindow.open(map,marker);
    }

    google.maps.event.addDomListener(window, 'load', initialize);
</script>

What I'm trying to achieve is to do a reverse geocode on the coordinates stored in the latlng variable and get back the results of that in a "City, State, Country" format and insert that into the HTML for the informarker stored in the "content" variable.

Have tried multiple approaches without success. Please note that I've deliberately left out the reverse geocoding script I tried to use for clarity purposes.

Edit: I've adjusted the script presented here to comply with the rules about it being clear, readable and that it actually should work. I also include a link to a CodePen so that you can see it in action: Script on CodePen

Regarding including the script for reverse geocoding, what I did was a disaster, only breaking the page and producing "undefined value" errors. I'd like to learn the correct way of doing this by example, and that's where the wonderful StackOverflow community comes in. Thanks again for your interest in helping me out.

2

There are 2 answers

6
Hamed On

Here's how I would do it:

function reverseGeocoder(lat, lng, callback) {
    var geocoder = new google.maps.Geocoder();
    var point = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));
    geocoder.geocode({"latLng" : point }, function(data, status) {
        if (status == google.maps.GeocoderStatus.OK && data[0]) {
            callback(null, data[0].formatted_address);
        } else {
            console.log("Error: " + status);
            callback(status, null);
        }
    });
};

And basically you would call the function like:

reverseGeocoder(lat, lng, function(err, result){
    // Do whatever has to be done with result!
    // EDIT: For example you can pass the result to your initialize() function like so:
    initialize(result); // And then inside your initialize function process the result!
});
2
Dr.Molle On

Use a node instead of a string as content , then you may place the geocoding-result inside the content, no matter if the infoWindow is already visible or not or when the result is available(it doesn't even matter if the InfoWindow has already been initialized, a node is always "live").

Simple Demo:

function initialize() {
  var geocoder = new google.maps.Geocoder(),
    latlng = new google.maps.LatLng(52.5498783, 13.42520);
  map = new google.maps.Map(document.getElementById('map-canvas'), {
      zoom: 18,
      center: latlng
    }),
    marker = new google.maps.Marker({
      map: map,
      position: latlng
    }),
    content = document.createElement('div'),
    infoWin = new google.maps.InfoWindow({
      content: content
    });
  content.innerHTML = '<address>the address should appear here</address>';
  google.maps.event.addListener(marker, 'click', function() {
    infoWin.open(map, this);
  });
  geocoder.geocode({
    location: latlng
  }, function(r, s) {
    if (s === google.maps.GeocoderStatus.OK) {
      content.getElementsByTagName('address')[0].textContent = r[0].formatted_address;
    } else {
      window.alert('Geocoder failed due to: ' + status);
    }

  });
}



google.maps.event.addDomListener(window, 'load', initialize);
      html,
      body,
      #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="map-canvas"></div>