2013-10-19 43 views
1

我是JavaScript新手。我正在嘗試使用Google api的Gmap v3來實現反向地理編碼。我讀過很多教程並編寫了一個簡單的代碼。問題是傳遞給geocoder.geocode()的匿名函數有時會起作用,但有時卻不行。謝謝你的幫助!。不調用地理編碼反向回調函數

function geoCode(latStr,lngStr){ 


     var lat = parseFloat(latStr); 
     var lng = parseFloat(lngStr); 
     var latlng = new google.maps.LatLng(lat, lng); 

    codeLatLng(latlng,function(addr){ 
     alert(addr); // sometimes message appears. 
    }); 
    } 


    function codeLatLng(latlng,callback) { 
     if (geocoder) { 
     geocoder.geocode({'latLng': latlng}, function(results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
      if (results[1]) { 
       callback(results[1].formatted_address); 
      } else { 
       alert("No results found"); 
      } 
      } else { 
      alert("Geocoder failed due to: " + status); 
      } 
     }); 
     } 
    } 
+0

你是什麼意思「有時工作,但有時不」?發生這種情況時,你在哪裏使用它?你會得到其他警報嗎? – geocodezip

+0

我的意思是,我沒有得到任何其他警報......有時不叫它的匿名函數。 – AntarticMonkey

回答

0

我不知道該谷歌服務是否將返回null或空數組,但爲了安全起見,你可以同時檢查使用:if (results && results.length >)。另外,你是否忘記了Javascript中的數組是基於零的?你可能想results[0]

if (results && results.length > 0) { 
    callback(results[0].formatted_address); 
} else { 
    alert("No results found"); 
} 

通過解釋:你的代碼會出錯if (results[1]),在「結果」是一個長度爲0或1的陣列的情況下,所以我猜的間歇性故障。

+0

你說得對,基於零。我根據一個例子對它進行編碼,該例子的結果[1]。我會嘗試使用[0] ...謝謝! – AntarticMonkey

0
var geocoder = new google.maps.Geocoder(); 
     geocoder.geocode({ 
      'latLng' : position 
     }, function(results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       if (results[1]) { 
        address = results[1].formatted_address; 
        // alert("Wow ! Got it"); 
       } else { 
        // alert("No results 
        // found"); 
        infowindow.setContent("No address found"); 
       } 
      } else { 
       // alert("Geocoder failed due 
       // to: " + status); 
       infowindow.setContent("Geocoder failed due to: " + status); 
      } 
      infowindow.setContent(address + '<br/>' + Timestamp); 
     }); 

     infowindow.open(marker.get('map'), marker, this); 
     currentInfoWindow = infowindow; 

    }); 
} 

一次嘗試與上面的代碼

+0

它的infowindow是什麼?我沒有使用Google地圖來顯示地圖。我使用OpenLayers我只想使用谷歌進行反向地理編碼。謝謝你的幫助。 – AntarticMonkey