Erica Stockwell-Alpert
Erica Stockwell-Alpert

Reputation: 4853

Using Google Maps Places API in autocomplete; API not working

I'm trying to hook up the Google Maps Places API to a search box. To test jquery autocomplete, I got it working with this simple example:

function bindAutocomplete() {
    var locationSearch = $("input#Location");

    locationSearch.autocomplete({
        source: ["Massachusetts", "New Hampshire", "Boston"],
        minLength: 2
    });
}

I'm trying to figure out how to use the results of the google maps API as the source though, and I'm not sure what to do. I can get results from the API in my browser:

https://maps.googleapis.com/maps/api/place/autocomplete/xml?types=(regions)&input=mas&key=xxx

These are the things I've tried:

locationSearch.autocomplete({
    source: function (request, response) {
     $.getJSON("https://maps.googleapis.com/maps/api/place/autocomplete/json?types=(regions)&key=xxx&input=mass", {
            term: "mass"
        }, response),
    minLength: 2
});

but I got a "Access Control Allow Origin" security error. I tried doing jsonp like this:

locationSearch.autocomplete({
    source: function (request, response) {
        $.ajax({
            url: "https://maps.googleapis.com/maps/api/place/autocomplete/json?types=(regions)&key=xxx&input=mass",
            type: "GET",
            dataType: 'jsonp',
            cache: false,
            success: function (response) {
                console.log(response);
            }
        });
    },
    minLength: 2
});

but I got an error trying to log the response, because the response is json but it's expecting jsonp. (Also, even if this did work, I wasn't sure how to set the output of the ajax call as the source)

The last thing I tried was this:

locationSearch.autocomplete({
    source: new google.maps.places.Autocomplete("mass"),
    minLength: 2
});

with these scripts on my page:

<script src='http://maps.googleapis.com/maps/api/js?libraries=places&key=xxx'></script>
<script>$(bindAutocomplete)</script>

but when the page loads I get the error "google is not defined" as well as a bunch of errors saying "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience" and "Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened"

Upvotes: 2

Views: 6894

Answers (1)

Dr.Molle
Dr.Molle

Reputation: 117314

When you want to request these data via JS you must use the AutocompleteService of the Places-library

Sample-implemetation:

function bindAutocomplete() {

  var acService = new google.maps.places.AutocompleteService(),
    placesService = new google.maps.places.PlacesService(document.createElement('div'));

  $("input#location").autocomplete({
    source: function(req, resp) {

      acService.getPlacePredictions({
        input: req.term,
        types:['(regions)']
      }, function(places, status) {
        if (status === google.maps.places.PlacesServiceStatus.OK) {
          var _places = [];
          for (var i = 0; i < places.length; ++i) {
            _places.push({
              id: places[i].place_id,
              value: places[i].description,
              label: places[i].description
            });
          }
          resp(_places);
        }
      });
    },
    select: function(e, o) {
      placesService.getDetails({
        placeId: o.item.id
      }, function(place, status) {
        if (status === google.maps.places.PlacesServiceStatus.OK) {
          alert(o.item.value +
            '\n is located at \n ' +
            place.geometry.location.toUrlValue());
        }
      });


    }
  });
}
$(window).load(bindAutocomplete);
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&libraries=places"></script>
<input id="location" />

Note: this service doesn't support the types-filter

However: the places-library also inludes an Autocomplete

Upvotes: 5

Related Questions