1

My understanding is that the error is due to the my code attempting to initialize the map before the HTML element is rendered. Supposedly, initializing the map as a var in mounted() should fix it. I tried the suggested fix in this post, but it is not working for me.

I set my refs value in my HTML:

<div class="map-container-column">
    <div class="map banner-map" id="map" ref="myMap"></div>
</div>

And I declared my map variable in mounted as well. I tried using the suggested syntax of L.map(this.$refs['myMap'] { and L.map(this.$refs.myMap { and it doesn't seem to make a difference either way.

mounted() {
var map = L.map(this.$refs.myMap, {
                    zoomControl: false,
                    closePopupOnClick: false
                }).setView(regionCoords, 10);
                this.tileLayer = L.tileLayer('https://api.mapbox.com/styles/v1/mapbox/streets-v9/tiles/256/{z}/{x}/{y}?access_token={accessToken}', {
                    minZoom: 9,
                    maxZoom: 15,
                    accessToken: MapBoxApiKey,
                    style: 'mapbox://styles/mapbox/streets-v9',
                    attribution: '<a href="https://www.mapbox.com/about/maps/" target="_blank">&copy; Mapbox</a> <a href="http://www.openstreetmap.org/about/" target="_blank">&copy; OpenStreetMap</a> <a class="mapbox-improve-map" href="https://www.mapbox.com/feedback/?owner=mapbox&amp;id=streets-v9&amp;access_token=pk.eyJ1IjoiaGlnaGxhbmRob21lc2RpZ2l0YWwiLCJhIjoiY2psNzJrdmwwMzN0ZDNxcWpwNnRteDJ5aiJ9.ENhvxwa1PF2i8f6xCcgLLA" target="_blank">Improve this map</a>',
                });
                this.tileLayer.addTo(map);
                L.control.zoom({
                    position: 'topright'
                }).addTo(map);
}

Am I doing somethings wrong? If not, what else could be causing this error?

jarrodwhitley
  • 826
  • 10
  • 29

1 Answers1

0

The same thing was bugging me for the last few days. My main learning point is that Leaflet can't inject itself into the #map element if it doesn't exist in the DOM, which is what everyone on StackOverflow will tell you. What isn't so apparent is that #map doesn't exist in the DOM if - perhaps by virtue of a v-if on an ancestor element or use of Vue Router - the element isn't 'visible' (in the Vue sense of the word).

A good way to ensure that the Leaflet code injects only when #map has been rendered is to make #map into a component instead, with its own mounted() hook. That way you know that mounted() will only apply and run when the component is rendered, and every time it is rendered (eg. toggled by a v-if somewhere).

MSC
  • 3,286
  • 5
  • 29
  • 47