首页 > 解决方案 > 谷歌地理编码自动完成限制在马里兰州

问题描述

我正在尝试将 Google 自动完成结果限制在特定状态,在这里使用 Cornad 的答案 - Google GeoCode Autocomplete limit State。它在加利福尼亚州工作,而不是与马里兰州的坐标合作。任何人都可以看看和帮助。完整代码在这里- https://jsfiddle.net/zuhpwjcq/以下是工作和不工作的片段

工作代码 -

var stateBounds={
        ca: ["32.812736", "-119.216815", "34.608128", "-117.039301"]
        // lat/long boundaries list for states/provinces.
    };

    function getStateBounds(state) {
        return new google.maps.LatLngBounds(
          new google.maps.LatLng(stateBounds[state][0], 
                                 stateBounds[state][1]), 
          new google.maps.LatLng(stateBounds[state][2], 
                                 stateBounds[state][3])
        ); 
    }

    new google.maps.places.Autocomplete(document.getElementById('search'), {
        types: ['address'],
        componentRestrictions: {country: 'us'},
        bounds: getStateBounds('ca') // get LatLngBounds for ca.
    });

不工作的代码 -

var stateBounds={
        md: ["39.0457549", "76.64127119999999"]
        // lat/long boundaries list for states/provinces.
    };

    function getStateBounds(state) {
        return new google.maps.LatLngBounds(
          new google.maps.LatLng(stateBounds[state][0], 
                                 stateBounds[state][1])
        ); 
    }

    new google.maps.places.Autocomplete(document.getElementById('search'), {
        types: ['address'],
        componentRestrictions: {country: 'us'},
        bounds: getStateBounds('md') // get LatLngBounds for ca.
    });

标签: jquerygoogle-maps-api-3autocompletegoogle-geocoder

解决方案


根据@geocodezip的解释,我只能使用“位置”来限制马里兰州,因为边界不合适。这是有效的代码

var myLatlng = new google.maps.LatLng(39.0457549,-76.64127119999999); service.getPlacePredictions({
            input: value,
            types: type,
            componentRestrictions: {
              country: 'us'
            },
            location: myLatlng,
            radius: 500,
            strictBounds: true
          }

推荐阅读