get Place Id from coordinates

by Cynx EchoSteg

HTML

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp.&amp;sensor=false&amp;.js"></script>
<div id="map_canvas"></div>

CSS

html,
body,
#map_canvas {
  margin: 0;
  height: 100%;
}

JavaScript

function initialize() {
        var mapOptions = {
          zoom: 14,
          center: new google.maps.LatLng(38.8862447, -77.02158380000003),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('map_canvas'),
          mapOptions);

        geocoder = new google.maps.Geocoder;

        //keep a reference to the original setPosition-function
        var fx = google.maps.InfoWindow.prototype.setPosition;

        //override the built-in setPosition-method
        google.maps.InfoWindow.prototype.setPosition = function() {

          //this property isn't documented, but as it seems
          //it's only defined for InfoWindows opened on POI's
          if (this.logAsInternal) {
            google.maps.event.addListenerOnce(this, 'map_changed', function() {
              var map = this.getMap();

              //the infoWindow will be opened, usually after a click on a POI
              if (map) {

                //trigger the click
                google.maps.event.trigger(map, 'click', {
                  latLng: this.getPosition()
                });
              }
            });
          }
          //call the original setPosition-method
          fx.apply(this, arguments);
        };

        google.maps.event.addListener(map, 'click', function(e) {
          //alert('clicked @' + e.latLng.toString())
          geocoder.geocode({
            'location': e.latLng
          }, function(results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
              if (results[0]) {
                
                alert('place id: ' + results[0].place_id);


              } else {
                console.log('No results found');
              }
            } else {
              console.log('Geocoder failed due to: ' + status);
            }
          });

        });
      }

      google.maps.event.addDomListener(window, 'load', initialize);