2013-03-03 94 views
0

我的腳本有問題。 我有一切正確設置,但地理編碼不起作用,當我在我創建的形式輸入一個城市的名稱,然後我點擊「geocoder」它沒有任何反應。 這是我的代碼:地理編碼谷歌地圖不起作用

變量:

var geocoder; 
var map; 
var markers = new Array(); 
var i = 0; 

天氣預報腳本:

<!-- GEOCODER --> 
    function codeAddress() { 
var address = document.getElementById("address").value; 
geocoder.geocode({ 'address': address}, function(results, status) { 
    if (status == google.maps.GeocoderStatus.OK) { 
      document.getElementById('lat').value = results[0].geometry.location.lat(); 
      document.getElementById('lng').value = results[0].geometry.location.lng(); 
    map.setCenter(results[0].geometry.location); 
    var marker = new google.maps.Marker({ 
     map: map, 
     position: results[0].geometry.location 
    }); 
      markers.push(marker); 
      if(markers.length > 1) 
       markers[(i-1)].setMap(null); 
      i++; 
    } else { 
    alert("Le geocodage n\'a pu etre effectue pour la raison suivante: " + status); 
    } 
    <!-- GEOCODER --> 

表:

<div> 
Adresse : <input id="address" type="text" value="paris"> 
&nbsp; <input type="button" value="Geocoder" onsubmit="codeAddress()"> 
</div> 

的完整代碼(僅HTML):http://jsfiddle.net/hCmQb/

+0

你撥弄不起作用。在網頁加載時,超過10個位置的地理編碼會遇到配額和速率限制,需要非常長的時間並且不鼓勵,將位置進行離線編碼,並使用生成的座標來顯示標記。 – geocodezip 2013-03-03 16:32:45

回答

2

地理編碼器不運行的原因是這樣的:

<input type="button" value="Geocoder" onsubmit="codeAddress()"> 

你不想要 「的onsubmit」 你想 「onclick」 事件:

<input type="button" value="Geocoder" onclick="codeAddress()"> 

你的另一個問題是你的「map」變量對你的初始化函數是本地的。更改:

var map = new google.maps.Map(document.getElementById('map_canvas'), 
            mapOptions); 

到:

map = new google.maps.Map(document.getElementById('map_canvas'), 
           mapOptions); 

working example

+0

它的工作原理!但是,您知道是否可以刪除地理編碼器標記?當我刪除var marker = new google.maps.Marker({地圖崩潰 – 2013-03-03 17:09:16

+1

當然,不要創建它或將它添加到地圖中(刪除在codeAddress函數中創建標記的代碼) – geocodezip 2013-03-03 17:10:16

+0

我已刪除位置:results [0] .geometry.location,它的工作原理感謝您的幫助geocodezip – 2013-03-03 17:28:43