Google map API - Search by Postcode

感情迁移 提交于 2021-01-29 07:11:59

问题


I am using Google Map Javascript API and it is working fine.

 var geocoder = new google.maps.Geocoder();

geocoder.geocode({ 'address': address }, function (results, status) {
  if (status == 'OK') {
    map.setCenter(results[0].geometry.location);

The only issue is I cannot search by only Postcode. For example in Australia if I only search by 2000 (address = 2000) which is Sydney postcode, it doesn't return any results but if I go to the Google map page and type 2000, it shows the correct area. I was wondering if there is any way to search by Postcode.


回答1:


Have you tried restricting the country first?

Try this and let me know:

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://stackoverflow.com/questions/52887023/google-map-api-search-by-postcode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!