2014-02-28 137 views
0
<!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> 

我瞭解谷歌地圖API,而我只是試圖讓一個簡單的地址搜索工作,我缺少什麼?我看過類似的帖子,但找不到什麼不對,可能需要一些新鮮的眼睛。地理編碼地址輸入谷歌地圖API

回答

0

變量mapgeocoderinitialize()函數之外不可見。如果打開控制檯有錯誤寫:

ReferenceError: geocoder is not defined 

他們應該會成爲全局,如:

 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標籤是不是自閉。

<div id="map-canvas"/> 

應改爲

<div id="map-canvas"></div> 
+0

我改變了它因此,正確地加載,但不執行搜索。 – user3366192

+0

如果您輸入,例如Allentown並按搜索按鈕,您會得到什麼?你必須在地圖上得到標記。在控制檯窗口中是否出現錯誤? –