stack details ruby 1.9.2p180, rails 3.0.9, gmaps4rails 1.0.2, jquery.json-2.3.min.js
Background I am a newbie to gmaps4rails and really like the gem. All is working well so far, but I am trying to update markers dynamically for the first time. I am doing the following in application.js:
var markers_json = $.toJSON(markers_array);
Gmaps.map.replaceMarkers(markers_json);
This does not work and gives the following error
Uncaught TypeError: Cannot read property 'position' of undefined
extendBoundsWithMarkers in gmaps4rails.googlemaps.js:204
Gmaps4Rails.adjustMapToBounds in gmaps4rails.base.js:443
Gmaps4Rails.create_markers in gmaps4rails.base.js:321
Gmaps4Rails.addMarkers in gmaps4rails.base.js:389
Gmaps4Rails.replaceMarkers in gmaps4rails.base.js:381
Investigation done so far
Confirmed that the initial creation of the map is done by providing the markers as a json string.
Confirmed that I am giving a json string of the same format in the replaceMarkers call
Confirmed that in the source, when addMarkers is called on initial page load, the markers are in the form of an object array, but the replaceMarkers call (as I mentioned above) contains a JSON string
Other attempts Tried to pass the markers without converting to JSON
Gmaps.map.replaceMarkers(markers_array);
but that didn't work as well.
I broke my brain over this for quite a while being new to both JS and Rails ... I was unable to get my head around converting from a RAILS jSON string created in my controller to a JavaScript array of JSON objects.
I tried just grabbing the string generated by _to_gmaps4rails but it was full of escaped characters. I now know this was due to changes in Rails to prevent scripts from getting inserted by data.
I tried lots of things, like parsing the JSON on the browser side, passing the data elements individually, etc.
Turns out all I needed was the raw() function which prevented the string from being escaped. Here's my working code:
in my controller:
in my JS (returned from format.js Ajax call):
Hope this helps someone else!
This issue is resolved by upgrading to gmaps4rails 1.3.0. Another problem I faced was to make sure that the replaceMarkers method is given an array of markers, not a JSON string
Note that when you are creating a new map (on the server side), you must give a JSON string for the markers.
When you are calling replaceMarkers on the client side (in JS), you must give an array of marker objects.