gmaps4rails and autocomplete google place API inco

2019-07-20 02:17发布

问题:

I've a problem of compatibility between gmaps4rails gem and google place API

Basically if I put in my view a gmpas4rails like this:

<%=gmaps%>

then this script doesnt work anymore (it normaly activate an autocomplete on user_address field:

 $(document).ready(initialize_gmaps_autocomplete_user_address());

function initialize_gmaps_autocomplete_user_address() {
var input = document.getElementById('user_address');
var defaultBounds = new google.maps.LatLngBounds(new google.maps.LatLng(42.71422,-4.222666), new google.maps.LatLng(51.179343,8.47412));
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.setBounds(defaultBounds);
autocomplete.setTypes(['geocode']);
}

I've tried to call the script by gmaps4rails.call_back and to change the var names in my scripts...

Any idea?

回答1:

I guess you make a second call to the google api which mess things up.

Two solutions here:

1) don't include the js from the partial:

<%= gmaps({your_hash}, true, false) %>

And include all the js files manually but be sure to write:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&amp;libraries=geometry,places"></script>

Here is the original partial so you don't forget any file.

2) Grab the current version on git and add places directly:

<%= gmaps({ "map_options" => { "libraries" => ["places"] } }) %>

I'll update the gem later, so versions above 0.10.2 will have this included.



回答2:

Actually 2) should be

<%= gmaps({:map_options => {:libraries => ["places"]}}) %>

because in the source code of gmaps4rails symbols are used instead of strings.

To make it work with strings you'd have to use HashWithIndifferentAccess:

<%= gmaps(HashWithIndifferentAccess.new("map_options" => {"libraries" => ['places']}))%>