0

我允許用戶使用Google地圖向他們的帖子添加地址。使用Google地圖進行地址驗證 - 檢查地址

如果用戶在地圖進入或沒有進入奇特殊字符(#$ @#!)崩潰的網站,並給了我這個錯誤:

var lat = data.results[0].geometry.location.lat; 
       ^
TypeError: Cannot read property 'results' of undefined 

我試圖找出一個辦法在提交表單時檢查此錯誤。到目前爲止,我沒有運氣。是否有可能檢查這個錯誤?

我看過類似這樣的代碼,但所有內容都是未定義的,我不知道如何在這種情況下定義它,坦率地說我不確定以下代碼是如何運行的。

if (status == google.maps.GeocoderStatus.OK) { 
     var lat = results[0].geometry.location.lat(); 
     var lon = results[0].geometry.location.lng(); 
     searchStores(lat, lon); 
    } else { 
     $addressErrorP.removeClass('hide'); 
    } 

感謝您的幫助!

回答

0

想通了:簡單和完美的作品。

第1步:確保它在您的頁面上。

<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script> 

然後

$("#checkingAddress").click(checkGeocode); 

    function checkGeocode(){ 
     var addr = document.getElementById("location"); 
     // Get geocoder instance 
     var geocoder = new google.maps.Geocoder(); 

     // Geocode the address 
     geocoder.geocode({'address': addr.value}, function(results, status){ 
      if (status === google.maps.GeocoderStatus.OK && results.length > 0) { 
    alert('looks good') 
       // set it to the correct, formatted address if it's valid 
       addr.value = results[0].formatted_address;; 

     // show an error if it's not 
      }else alert("Invalid address"); 
     }); 
    };