0

i am using google map api v3 for javascript. i managed to get the map on my webpage. now i need to perform reverse geocoding when the user clicks on the map. for that i have written the necessary event listener and reverse geocoding code

 <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=My_Key&sensor=false"></script>
 <script type="text/javascript"> 
    var map;
    function initialize() {
     var myLatlng = new google.maps.LatLng(-34.397, 150.644);
     var mapOptions = {
          zoom: 4,
          center: myLatlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
         }
     map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    }
     google.maps.event.addListener(map, 'click', function(event) {
     placeMarker(event.latLng);
     var myLatLng = event.latLng;
     var lat = myLatLng.lat();
     var lng = myLatLng.lng();
     var latlng = new google.maps.LatLng(lat, lng);

     //Code to reverse geocode follows
     geocoder.geocode({'latLng': latlng}, function( results, status ) {
     if ( status == google.maps.GeocoderStatus.OK ) {
        if ( results[1] ) {
           map.setZoom( 11 );
           marker = new google.maps.Marker({
               position: latlng,
               map: map
           });
           infowindow.setContent( results[1].formatted_address );
           infowindow.open( map, marker );
           document.forms["wheregoing"]["start"].value=results[1].formatted_address;
        }
     } else {
        alert("Geocoder failed due to: " + status);
     }
   });
  });


  function placeMarker( location ) {
    var marker = new google.maps.Marker({
        position: location,
        map: map
    });
    map.setCenter(location);
  }

The above mentioned code was for java script. in HTML i have declared a place where the map should be shown as follows

    <div id="map_canvas"></div>

The problem i am facing is that when a user clicks on the map a placemarker should be placed at that point and the address should appear in a textbox named "start" in the html form, but it does not happen so. The Map is getting loaded on the website but it is not detecting the click event. I am working on a localhost. I am testing this feature of map on localhost. Please help. Tell me where i am going wrong and why its not detecting the click event. i am a beginner in this

2
  • I'd say you have a race condition, ie the map is not initialized when the listener is added. I must go now so I can't answer in details, hope it helps you ! Put <script> at bottom of <body> maybe. Commented Mar 2, 2013 at 13:39
  • i shifted the entire script tag after body. in body i call the initialize function.. but still it doesnot work..and event listener code is after initialization, since i am initializing in the body onload function. your solution did not work Commented Mar 2, 2013 at 13:56

1 Answer 1

2

You need to set up your click listener inside the initialize function, after initializing the map:

    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=My_Key&sensor=false"></script>
    <script type="text/javascript"> 
    var map;
    var geocoder = new google.maps.Geocoder();
    var infowindow = new google.maps.InfoWindow();

    function initialize() 
    {
     var myLatlng = new google.maps.LatLng(-34.397, 150.644);
     var mapOptions = 
         {
          zoom: 4,
          center: myLatlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
         }
     map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

     google.maps.event.addListener(map, 'click', function(event) {
      placeMarker(event.latLng);
      var myLatLng = event.latLng;
      var lat = myLatLng.lat();
      var lng = myLatLng.lng();
      var latlng = new google.maps.LatLng(lat, lng);

      //Code to reverse geocode follows
       geocoder.geocode({'latLng': latlng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
         if (results[1]) {
          map.setZoom(11);
          marker = new google.maps.Marker({
            position: latlng,
            map: map
          });
          infowindow.setContent(results[1].formatted_address);
          infowindow.open(map, marker);
          document.forms["wheregoing"]["start"].value=results[1].formatted_address;
        }
       } else {
        alert("Geocoder failed due to: " + status);
       }
      });
     });
    }    

  function placeMarker(location) 
    {
    var marker = new google.maps.Marker({
    position: location,
    map: map
 });

  map.setCenter(location);
}
  </script>
  <body onload="initialize()">

working example

Sign up to request clarification or add additional context in comments.

6 Comments

thanks for the reply. now its only setting up the marker on the map, its not showing the info window nor its reverse geocoding and placing the address in the input text
Don't you get obvious javascript errors? (geocoder is not defined, infowindow is not defined) Fix those and it works for me.
i am a super beginner in using google maps with JS hence i could not get the errors, i will make it a point in the future to check those...only geocoder and infowindow is not defined or there are more errors as well, can u please post the code?
I updated my answer about the same time as I posted that, please read it again. The "working example" I added at that time might help you as well.
thanks alot, its working like a charm..one more thing, what to do if i want to show road direction on the map between two points?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.