2017-03-25 160 views
0

我試圖設置一個郵政編碼,以獲得拉特和長座標,並在其上放置一個標記。到現在爲止,一切都很好。谷歌地圖API在特定國家搜索郵編

問題來了,當我給一個郵政編碼輸入,它最終在世界的另一個地方的某處做標記。

例:I型2975-435,我得到: https://maps.googleapis.com/maps/api/geocode/json?address=2975-435&key=YOURKEY

"formatted_address" : "Balbey Mahallesi, 435. Sk., 07040 Muratpaşa/Antalya, Turquia", 

我想使這個郵政編碼葡萄牙只進行搜索。

https://maps.googleapis.com/maps/api/geocode/json?address=2975-435+PT 這樣我得到:

"formatted_address" : "2975 Q.ta do Conde, Portugal", 

正是我想要的。

問題是,我如何在JS代碼中做到這一點? 這裏是我必須在之前的代碼現在

function codeAddress() { 
    var lat = ''; 
    var lng = ''; 
    var address = document.getElementById("cp").value; 
    geocoder.geocode({ 'address': address}, 

    function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      lat = results[0].geometry.location.lat(); 
      lng = results[0].geometry.location.lng(); 
      //Just to keep it stored 
      positionArray.push(new google.maps.LatLng(lat,lng)); 
      //Make the marker 
      new google.maps.Marker({ 
       position:new google.maps.LatLng(lat,lng), 
       map:map 
      }); 

     }else { 
      alert("Geocode was not successful for the following reason: " + status); 
     } 
    }); 
} 

謝謝

回答

1

要限制導致某些國家,你可以申請一個分量濾波:

https://developers.google.com/maps/documentation/javascript/geocoding#ComponentFiltering

所以,你的JavaScript代碼將是

function codeAddress() { 
    var lat = ''; 
    var lng = ''; 
    var address = document.getElementById("cp").value; 
    geocoder.geocode({ 
     'address': address, 
     componentRestrictions: { 
      country: 'PT' 
     } 
    }, 

    function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      lat = results[0].geometry.location.lat(); 
      lng = results[0].geometry.location.lng(); 
      //Just to keep it stored 
      positionArray.push(new google.maps.LatLng(lat,lng)); 
      //Make the marker 
      new google.maps.Marker({ 
       position:new google.maps.LatLng(lat,lng), 
       map:map 
      }); 

     }else { 
      alert("Geocode was not successful for the following reason: " + status); 
     } 
    }); 
} 

您可以使用地理編碼工具在行動中看到一個分量濾波:

https://google-developers.appspot.com/maps/documentation/utils/geocoder/#q%3D2975-435%26options%3Dtrue%26in_country%3DPT%26nfw%3D1

希望它能幫助!

相關問題