I'm trying to understand javascript, and the way variables are passed around, but I'm not doing too well. I'm trying to refresh a google map's markers with ajax, but nothing is happening.
I submit a form, which sends some variables to the controller. Some stuff is processed, and it responds with .js to...
find.js.erb
$('#collapseTwo ul').html("<%= j render partial: 'events/sidebar', collection: @events %>");
alert(<%= raw @hash.to_json %>);
clearMarkers();
markers = handler.addMarkers(<%= raw @hash.to_json %>, {
draggable: false
});
The render fires fine, so everything is working there, but I can't seem to get a hold of the markers to refresh the map. That alert shows [object Object]
, so that's likely correct, but no action on the markers.
I made some modifications to marker.coffee
in the form of
clear: ->
@getServiceObject().setMap(null)
show: ->
@getServiceObject().setVisible(true)
hide: ->
@getServiceObject().setVisible(false)
so that clearMarkers();
works. It's in another file, where I'm storing some other actions
events.js.coffee
jQuery ->
...
...
@clearMarkers = ->
for marker in Gmaps.store.markers
marker.clear()
Gmaps.store.markers = []
So... I call the map initially in with...
jQuery ->
handler = Gmaps.build 'Google'
handler.buildMap {
provider: {
minZoom: 3
}, internal: {id: 'map'} }, ->
markers = handler.addMarkers( $('#map').data('events'),
draggable: false
flat: false
)
#moves map to marker clicked + open infowindow
$(document).on 'click', '#sideBar li', ->
markers[$(this).data('marker')].panTo()
markers[$(this).data('marker')].click()
That function on the bottom there... the only way I had access to the markers
array was because it was inside the handler.buildMap
function. So, should the markers
variable be global? How else can I act on them?
Also, the handler
variable... that's it seems to me like that should be available everywhere. I tried manually putting the @hash
into .addMarkers()
, but the handler didn't build the markers.
You need a store accessible globally.
I suggest the following:
You can access the variables within your js.erb as well.