scope of markers variable for google maps (gmaps4rails gem)

偶尔善良 提交于 2019-12-25 01:24:51

问题


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.


回答1:


You need a store accessible globally.

I suggest the following:

Gmaps.store = {}
jQuery ->
  Gmaps.store.handler = Gmaps.build 'Google'
  Gmaps.store.handler.buildMap...
    Gmaps.store.markers = Gmaps.store.handler.addMarkers(...)

You can access the variables within your js.erb as well.



来源:https://stackoverflow.com/questions/19737094/scope-of-markers-variable-for-google-maps-gmaps4rails-gem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!