I have a form in my Rails app where I use the Google Places API for autocompletion, but I can't get it to work everytime. Every time you load the page where the form is, it's like a roll of dice: sometimes the JS works, sometimes it doesn't.
By the way, I have several other javascripts that also fails to work sometimes, but the ones for google autocomplete are the most quirky and they are mission-critical.
Here is the setup:
1° My html header has:
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
<%= yield :javascript_includes %>
Then in my body, I have the content_for
tag that is yielded in the head
<% content_for :javascript_includes do %>
<%= javascript_include_tag "application", "https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places" %>
<script type="text/javascript">
function initializeAutocomplete(){
var input = document.getElementById('offer_location');
var options = {
types: ['(cities)']
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
var lat = place.geometry.location.lat();
var lng = place.geometry.location.lng();
$('#offer_latitude').val(lat)
$('#offer_longitude').val(lng)
});
}
google.maps.event.addDomListener(window, 'load', initializeAutocomplete);
</script>
<% end %>
I used to have the script with the initializeAutocomplete in a separate .js file that was loaded through the Asset Pipeline but that gave similar results: the autocomplete worked only half of the time... (in fact I feel it failed even more often)
I think the problem has to do with when the different elements are loaded, and when the callback is triggered. Here are examples of the things I tried to change :
using
$(window).load
and$(document).ready
instead ofaddDomListener(window, 'load', initializeAutocomplete)
putting the script in a separate
google-autocomplete.js
file loaded in the Asset Pipeline (meaning it was loaded BEFORE the link to the API provided in thecontent_for
tagputting the script in a separate
google-autocomplete.js
file NOT included in the Asset Pipeline and called right after the API link tag in thecontent_for
tag
Thanks a lot for your help!
-- EDIT --
In the end it turns out that it was turbolinks messing up with my jquery triggers, notably the one for google autocomplete. Found the answer there with which I fixed all my JS.