phegman / vue-mapbox-gl

A Vue.js component for Mapbox GL JS

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Layers disappear when style is changed

JWDobken opened this issue · comments

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>

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()
},

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()
      })
    }
  }

COTCHA: @map-styledata="loadLayers"

This repo is awesome