Pregunta

I am using the Gmaps4rails gem to build a map around one central location. I am using check boxes to allow the user to show/hide nearby place markers, restaurants, schools etc. The issue is that if I display a category, then hide it again, and then zoom in or out, those markers will re-appear, even though they had previously been hidden.

My issue is similar to this question, though I have not been able to solve it. I wonder if anyone else could tell me where I am going wrong. My CoffeeScript is as follows.

google_map1_handler = null
google_map1_markers = []

$ ->

  $('#map-tab').click (e) ->
    unless google_map1_handler?
      markers_data = $('#map1').data('markers')
      markers = []
      handler = Gmaps.build('Google', { markers: { maxRandomDistance: null } })

      handler.buildMap { provider: { zoom: 15 }, internal: {id: 'map1'} }, ->
        $.each markers_data, (i, marker) ->
          if marker.type == 'Property'
            markers.push handler.addMarker( marker )
            handler.map.centerOn({ lat: marker['lat'], lng: marker['lng'] })

        $('.map-checkbox').prop('checked', false)

      google_map1_handler = handler
      google_map1_markers = markers


  # Hide and show map markers with key checkboxes
  $('.map-checkbox').click (e) ->
    keywords = []
    $('.map-checkbox').each (i, el) ->
      keywords.push el.id if el.checked == true

    toggleMapMarkers(keywords)


  toggleMapMarkers = (keywords) ->
    markers_data = $('#map1').data('markers')
    handler = google_map1_handler
    markers = google_map1_markers

    # clear old markers
    _.each markers, (marker, i) ->
      marker.setMap(null)
    markers.length = 0

    _.each markers_data, (marker, i) ->
      if marker.type == 'Property' or marker.type in keywords
        markers.push handler.addMarker(marker)

    google_map1_markers = markers
¿Fue útil?

Solución

Basically, when you use a clusterer, it stores all markers.

  • When you zoom out, it sets their map to null and adds cluster pics.

  • When you zoom in, it removes the cluster pic and sets the map again in the markers.

So when you do marker.setMap(null), it's not enough: you have to remove the markers from the clusterer too!

_.each markers, (marker, i) ->
  marker.setMap(null)
  handler.clusterer.removeMarker(marker)

But I also needed this scenario, so just do:

_.each markers, (marker, i) ->
  handler.removeMarker(marker)

Or even:

handler.removeMarkers(markers)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top