Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Places Autocomplete Remove State and Country from Result

https://google-developers.appspot.com/maps/documentation/javascript/examples/places-autocomplete

I have a page similar to the above google places autocomplete demo url whereby if i type Buckingham Palace. It will return results of

  1. Buckingham Palace Road, London, United Kingdom
  2. Buckingham Palace Shop, Buckingham Palace Road, Victoria, London, United Kingdom

and etc. How do i remove London, United Kingdom from the results?

like image 557
user1809157 Avatar asked Oct 23 '22 03:10

user1809157


1 Answers

It seems Google have no interest in sorting it out anytime soon. I have had to resort to the following, might be sufficient for others' needs as well:

document.addEventListener('DOMNodeInserted', function(event) {
    var target = $(event.target);
    if (target.hasClass('pac-item')) {
        target.html(target.html().replace(/, Australia<\/span>$/, "</span>"));
    }
});

note that pac-item is the class used on each suggestion. See Google Reference for other classes used. The container with pac-container class seems to drop the items when it is not shown and add new ones when it displays so if these pac-items are getting added to the DOM, it means suggestions are on their way to be displayed and pac-container is about to become visible.

just worked this out so open to improvements.

This also is not a complete solution. When selecting a suggestion with the country removed, autocomplete still adds the country to the geocoding! place_changed is too late a stage to change that so please see the solution above as only part of the answer. I'll update this again once I figure out the rest.

--- update

personally, i ended up not using the google autocomplete at all as i couldn't find a way around the problem of the autocomplete still showing the country once a modified suggestion is selected. a more usable approach was to use twitter typeahead and use the google APIs for getting the suggestions only. this gave me more control over the suggestions but obviously requires more manual work to make up for lost functionality

like image 170
Ozgur Susoy Avatar answered Oct 31 '22 12:10

Ozgur Susoy