2015-05-11 49 views
0

我最近開發了一個帶有Google Maps V3 Js API的經銷商地理位置平臺,但是我意識到當用戶輸入郵政編碼時,地理位置很差。Google Maps JS APIv3 - 地理編碼返回INSEE代碼的位置而不是郵政編碼

例如,如果用戶搜索13001(馬賽第一區),地理定位是在普羅旺斯艾克斯(其INSEE代碼爲13001)上完成的。 同上13007(馬賽第七區),返回距離馬賽20公里的Auriol。

看來,這是下面的代碼段返回錯誤的座標:

function GoogleGeocode(){ 
    geocoder = new google.maps.Geocoder(); 
    this.geocode = function(address, callbackFunction) { 
     geocoder.geocode({ 'address': address}, function(results, status) { 
      if (status === google.maps.GeocoderStatus.OK) { 
      var result = {}; 
      result.latitude = results[0].geometry.location.lat(); 
      result.longitude = results[0].geometry.location.lng();       
      callbackFunction(result); 
      } else { 
      if (settings.geocodeErrorAlert != "") { 
       alert(settings.geocodeErrorAlert + status); 
      } 
      callbackFunction(null); 
      } 
     }); 
    }; 
    } 

你有一個解釋和解決這一問題的解決方案?

謝謝大家

回答

0

我有同樣的問題,我設法通過將數字搜索字符串地址解析器的其它附加參數來解決這個問題。

var rawAddress = jQuery('#postcode').val(); 
    var components = {}; 

    // Test if the address only contains digits 
    if(/^\d+$/.test(rawAddress)){ 
     components.postalCode = address; 
    } 
    var geocoder = new google.maps.Geocoder(); 
     geocoder.geocode({address: address, componentRestrictions: components}, geocoderCallback); 

在本示例中,郵政編碼只有在搜索不包含任何其他內容時才能正確發送。

如果你想使用郵政編碼這是一個更復雜的搜索字符串,你需要從中提取數字的字符串是這樣的:

var rawAddress = jQuery('#postcode').val(); 
var digits = rawAddress.match(/\d+/g); 

if(digits != null && digits.length > 0){ 
      for(var i = 0 ; i < digits.length ; i++){ 
       if(digits[i].length == 5){ 
        components.postalCode = digits[i]; 
        address = address.replace(digits[i], ''); 
       } 
      } 
     } 
相關問題