Restrict places autocomplete results to within COUNTRY and STATE

醉酒当歌 提交于 2020-07-03 16:21:38

问题


I'm currently using this URL to get my results restricted within Australia:

https://maps.googleapis.com/maps/api/place/autocomplete/json?input=393&components=country:AUtypes=address&key=[my_api_key]

But I'd like to say limit my searches to the current state let's say New South Wales.

I tried this: https://maps.googleapis.com/maps/api/place/autocomplete/json?input=393&components=country:AU&state=NSW&types=address&key=[my_api_key]

But it's returning the same number of results with items from Victoria, which is not from NSW.

According to the docs:

https://developers.google.com/places/web-service/autocomplete

It does not indicate restricting the state though.


回答1:


My solution is filter the incoming result by comparing the state and the country with description being returned from Places API. Sample implementation is below:

        JSONObject jsonObj = new JSONObject(jsonResults.toString());
        JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
        // Extract the Place descriptions from the results
        resultList = new ArrayList<>(predsJsonArray.length());
        for (int i = 0; i < predsJsonArray.length(); i++) {
            if(predsJsonArray.getJSONObject(i) != null){
                String description = predsJsonArray.getJSONObject(i).getString("description");
                if(description != null){
                    if(description.contains(state + ", " + country))
                    resultList.add(new Place(description,
                            predsJsonArray.getJSONObject(i).getString("place_id")));
                }
            }
        }



回答2:


Hey friend!

I was facing the same problem and ended up building a solution in javascript, capable to restrict an address for whatever you want.

Problem

The real thing is that Google API autocompletes methods don't give us a complete restrict address options, only for desired country and for bounds (if you have the coordinates).

And it still a little tricky for users type all the complete address (neighborhood, city, state, etc.) every time he needs to get a correct address, at least in my case of use (firefighters emergency calls attendance).

Solution

It's not 100% that it wont return undesirable results, but it will save a lot off users typing efforts.

Basically this script tricks Google APIs and users by adding behind the scenes the necessary restrictions within the request, before it goes to google servers.

It uses service.getPlacePredictions and google.maps.places.AutocompleteService and was implemented in a way that the billing stands for "Autocomplete without Places Details - Per Session", that means you'll be billed only once since when user start typing, till he clicks on an address prediction (the cheaper option available).

Another advantage of using a custom autocomplete, instead the google default widget, is that it won't block the text input if there's a problem with the API Key, like out of limits. So user can type the address and in future the system adms can give the correct treatment to the unverified address.

It's required that Places API and Maps JavaScript API is activated on your console.cloud.google.com.

Well, below is all you'll need to do to use the component.

<html>
   <head>
      <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
      <meta content="utf-8" http-equiv="encoding">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <link rel="stylesheet" type="text/css" href="style.css">
   </head>
   <body>
      <p>This example uses service.getPlacePredictions and google.maps.places.AutocompleteService what means that the billing stands for "Autocomplete without Places Details - Per Session"</p>
      <!--Make sure the form has the autocomplete function switched off:-->
      <form autocomplete="off" action="/action_page.php">
         <div class="autocomplete" style="width:300px;">
            <p><input id="estado" type="text" name="estado" placeholder="Estado" value="SC"></p>
            <p><input id="cidade" type="text" name="cidade" placeholder="Cidade"value="FLORIANOPOLIS"></p>
            <p><input id="bairro" type="text" name="bairro" placeholder="Bairro" value="CENTRO"></p>
            <p><input id="numero" type="text" name="numero" placeholder="Numero" value="10"></p>
            <input id="logradouro" type="text" name="logradouro" placeholder="Logradouro">
         </div>
         <input type="submit">
      </form>
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
      <script async defer src="https://maps.googleapis.com/maps/api/js?key=GOOGLE_API_KEY&libraries=places" type="text/javascript"></script>
      <script src="./autocomplete.js" type="text/javascript"></script>
      <script type="text/javascript">
         let autocomplete = new RestrictedAutocomplete(document.getElementById("logradouro"), function () {
            console.log(this.lastResultBusca);
            console.log(this.lastResultEnderecoCompleto);
            console.log(this.lastResultNumero);
            console.log(this.lastResultNumeroA);
            console.log(this.lastResultLogradouro);
            console.log(this.lastResultLogradouroA);
            console.log(this.lastResultBairro);
            console.log(this.lastResultBairroA);
            console.log(this.lastResultCidade);
            console.log(this.lastResultCidadeA);
            console.log(this.lastResultEstado);
            console.log(this.lastResultEstadoA);
            console.log(this.lastResultPais);
            console.log(this.lastResultPaisA);
            console.log(this.lastResultCEP);
            console.log(this.lastResultCEPA);
            console.log(this.lastResultId);
            console.log(this.lastResultLatitude);
            console.log(this.lastResultLongitude);
         });
         autocomplete.setRestrictions(document.getElementById("estado"), 
            document.getElementById("cidade"), 
            document.getElementById("bairro"), 
            document.getElementById("numero"));
      </script>
   </body>
</html>

Autocomplete working:

Autocomplete after a address selection:

More details you can see on the GitHub project.

Hope it helps!



来源:https://stackoverflow.com/questions/41206185/restrict-places-autocomplete-results-to-within-country-and-state

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