javaspringspring-bootgoogle-placesgoogle-places-autocomplete

Restrict Google Places to country in JAVA


I am using GooglePlaces to get places

myController.java

@GetMapping("/connexionFR")
public String displayLoginPageFR(Model model) {
... 
client = new GooglePlaces("MY_KEY_GOOGLE");
...
return "/FR/MDB_VTC.html";
}


@GetMapping("/search")
public ResponseEntity<String> doAutoComplete(@RequestParam("q") final String input) {       
    List<String> proposition = new ArrayList<>(); 
    List<String> strings = new ArrayList<>(); 
    
    List<Prediction> predictions = client.getPlacePredictions(input);
    for(Prediction p : predictions) {
        proposition.add(p.getDescription());            
    }
    
    strings = getStrings(input, proposition) ; 
    ObjectMapper mapper = new ObjectMapper();
    String resp = "";

    try {
        resp = mapper.writeValueAsString(strings);
    } catch (JsonProcessingException e) {
    }
    return new ResponseEntity<String>(resp, HttpStatus.OK);
}

myHTML.html

...
<input type="text" name="search" id="searchBox" style="width: 560px; margin: auto;" />
...

<script>
    $(function() {
        $("#searchBox").autocomplete({
            source : function(request, response) {
                $.ajax({
                    url : "http://localhost:8092/search",
                    dataType : "json",
                    data : {
                        q : request.term
                    },
                    success : function(data) {
                        //alert(data);
                        console.log(data);
                        response(data);
                    }
                });
            },
            minLength : 1
        });
    });
</script>
...

I am only getting US result and i want to get other countries result.


Solution

  • As indicated in the comments provided in the question, probably are using the google-places-api-java library.

    As described in the API documentation, please, be aware that Google Places autocomplete will only return up to five results: perhaps you are looking for places that can be found in US and the API is returning them in first place, it can be related to the problem.

    In addition, please, try providing the country or countries you want to obtain results for to the API. You can do that using the components param, something like:

    List<Prediction> predictions = client.getPlacePredictions(
      input,Param.name("components").value("country:fr")
    );
    

    You can provide a list of countries as well:

    List<Prediction> predictions = client.getPlacePredictions(
      input,Param.name("components").value("country:fr|country:dz")
    );