phegman / vue-mapbox-gl

A Vue.js component for Mapbox GL JS
GNU General Public License v3.0
270 stars 33 forks source link

Layers disappear when style is changed #48

Closed JWDobken closed 6 years ago

JWDobken commented 6 years ago

I have a vue button to change the style, not fully sure if this is the correct way to implement. But the problem is that my layers disappear when the style is changed.

the script toggles the baseMapStyle value with a watch function:

<script>
import Mapbox from 'mapbox-gl-vue'

var baseMapStyles = [
  { label: 'light', value: 'mapbox://styles/mapbox/light-v9' },
  { label: 'dark', value: 'mapbox://styles/mapbox/dark-v9' },
  { label: 'streets', value: 'mapbox://styles/mapbox/streets-v9' }
]

export default {
  components: { Mapbox },
  data () {
    return {
      baseMapStyles: baseMapStyles,
      baseMapStyle: baseMapStyles[0].value,
      mapOptions: {
        center: [4.3666706, 51.9991184],
        zoom: 12
      }
    }
  },
  methods: {
    mapLoaded (map) {
      map.addLayer({
        'id': 'points',
        'type': 'symbol',
        'source': {
          'type': 'geojson',
          'data': ...
        }
      })
    },
    mapInitialized (map) {
      map.setStyle(this.baseMapStyle)
      this.map = map
    }
  },
  watch: {
    baseMapStyle: function (val) {
      this.map.setStyle(val)
    }
  }
}
</script>
JWDobken commented 6 years ago

Apparently I did not understood the concept of style correctly; and the above is actually the expected behavior and all layers should be added again after the style has changed.

is there a listener when to style is set? Like styleLoaded?

styleLoaded (map) {
      this.addLayers()
},
JWDobken commented 6 years ago

Now I use:

  watch: {
    baseMapStyle: function (val) {
      this.map.setStyle(val)
      this.map.on('style.load', () => {
        const waiting = () => {
          if (!this.map.isStyleLoaded()) {
            setTimeout(waiting, 200)
          } else {
            this.loadLayers()
          }
        }
        waiting()
      })
    }
  }
JWDobken commented 6 years ago

COTCHA: @map-styledata="loadLayers"

This repo is awesome