Question

    <!DOCTYPE html> 
    <html>
      <head>
          <title></title>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
        <style type="text/css">
          html { height: 100% }
          body { height: 100%; margin: 0; padding: 0 }
          #map-canvas { width: 1000px; height: 600px }  /* ID */
    </style>
      <!--Include the Maps API JavaScript using a script tag.-->
    <script type="text/javascript"
      src="http://maps.google.com/maps/api/js?sensor=false">
    </script>
     <script type="text/javascript">
         //Function called when the window loads shown below in the addDomlistener
         function initialize() {
             var geocoder = new google.maps.Geocoder();
             var mapOptions = { center: new google.maps.LatLng(40.5, -75.5), zoom: 8 };
             var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
         }

         function calcAddress(address)
         {
             var address = document.getElementById("address").value;
             geocoder.geocode({ 'address': address }, function (results, status) {
                 if (status == google.maps.GeocoderStatus.OK) {
                     //Got result, center the map and put it out there
                     map.setCenter(results[0].geometry.location);
                     var marker = new google.maps.Marker({
                         map: map,
                         position: results[0].geometry.location
                     });
                 } else {
                     alert("Geocode was not successful for the following reason: " + status);
                 }
             });
         }

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

  </head>
  <body>
      <div id="panel">
      <input id="address" type="text">
       <input type="button" value="Search" onclick="calcAddress()" />
   </div>
    <div id="map-canvas"/>
  </body>
</html>

I'm learning about google maps API, and I am just trying to get a simple address search to work, what am I missing? I've seen similar posts, but can't find what isn't right, might need some fresh eyes.

No correct solution

OTHER TIPS

Varaibles map and geocoder are not visible outside of initialize() function. If you open console there is error written:

ReferenceError: geocoder is not defined 

They should be made global like:

     var map,
         geocoder;

     function initialize() {
         geocoder = new google.maps.Geocoder();
         var mapOptions = { center: new google.maps.LatLng(40.5, -75.5), zoom: 8 };
         map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
     }

Additionaly, div tag is not self-closing.

<div id="map-canvas"/>

should be changed to

<div id="map-canvas"></div>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top