Mapbox and Vue.js are causing an issue: the style is still in the process of loading

My current challenge involves using Mapbox with Vue.js. Despite my efforts, I continue to encounter the following error message when attempting to add a geojson layer to the map:

Uncaught (in promise) Error: Style is not done loading

I have experimented with different approaches but have not found a lasting solution. The main issue I face is ensuring the correct order of execution so that the layer is consistently added without encountering errors. In an attempt to address this, I have wrapped the function in a Javascript Promise and included a setTimeout() as a workaround to allow time for the map/style to finish loading. However, despite being within a Mapbox listener, the error still resurfaces periodically. Below is a snippet of my current component code (omitting certain functions for clarity):

export default {
  mounted() {
    new Promise(resolve => {
      this.loadMap([this.subjectProperty.longitude, this.subjectProperty.latitude])
      if(this.mapLoaded === true) resolve()
    }).then(() => {
      setTimeout(() => {
        this.showParcel()
      }, 3000)
    })
  },
  methods: {
    loadMap(center) {
      var self = this   
      mapBox = new mapboxgl.Map({
        container: 'map',
        zoom: 12,
        pitch: 45,
        center: center,
        style: 'mapbox://styles/mapbox/streets-v10'
      })
      mapBox.on('style.load', function() {
        self.mapLoaded = true
      })                    
    },
    showParcel() {
      mapBoxBounds = new mapboxgl.LngLatBounds()
      this.parcel.geo_json['geometry']['coordinates'][0].forEach((coord) => {
        mapBoxBounds.extend(coord)
      })
      MapBoxObject.addGeoJsonParcels(this.parcel.geo_json)
      MapBoxObject.fitBounds()
    }
  }
}

Answer №1

Here is a code snippet to try out:

export default {
  mounted() {
    this.loadMap([
      this.subjectProperty.longitude,
      this.subjectProperty.latitude
    ]).then(_=>{
      this.showParcel()
    })  
  },
  methods: {
    loadMap(center) {
      return new Promise(resolve=>{
        let mapBox = new mapboxgl.Map({
          container: 'map',
          zoom: 12,
          pitch: 45,
          center: center,
          style: 'mapbox://styles/mapbox/streets-v10'
        })

        mapBox.on('style.load', _ => {
          resolve()
        })
      })
    },
    showParcel() {
      mapBoxBounds = new mapboxgl.LngLatBounds()
      this.parcel.geo_json['geometry']['coordinates'][0].forEach((coord) => {
        mapBoxBounds.extend(coord)
      })
      MapBoxObject.addGeoJsonParcels(this.parcel.geo_json)
      MapBoxObject.fitBounds()
    }
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble getting Angular-UI-Select to work with a basic variable on $scope?

How can you reset an array with selected values so that the values can be reselected from the dropdown? I am working with a people array where the values are initially displayed in a select dropdown. When I choose certain names, they get transferred to th ...

Is a Buefy carousel with vertical thumbnails what you're looking for

How can I change the orientation of thumbnails in the b-carousel tag from horizontal to vertical? This is my current code: <template> <b-carousel :indicator-inside="false"> <b-carousel-item v-for="(item, i) in 6" :key="i"> ...

Using Angular to display the initially selected option value in a select dropdown menu

Struggling to set the default selected option in a select input using Angular. I've tried several solutions with no success. It's baffling why this is proving so difficult for me. Any assistance would be greatly appreciated, thank you. The selec ...

Navigating through arrays to access nested objects

Currently, I am attempting to retrieve a specific field within a nested array using the following code: var array1 = []; const data = { [userId]: [{ id: id, name: fullName, email: userEmail }, ], ...

Ways to retrieve information and functions from defineExpose in Vue

`I am attempting to call a method from a child component within the parent component in Vue using the composition API. I have defined the method inside defineExpose, but I am unable to access it in the parent component. Hero.vue (ChildComponent) <templ ...

What is the best way to ensure that my text and clickable URLs can be effectively sent through a Teams chat webhook without any truncation issues?

My ultimate aim is to achieve in Teams what can easily be accomplished with Slack Webhooks, like this: await fetch(slackWebhook, { method: 'POST', headers: { 'Content-Type': 'application/json' ...

Encountered a 404 error (not found) while making a GET request with axios

I encountered an issue with my pizza shop application built with Next.js. Whenever I run the app on my computer, I come across this error: https://i.sstatic.net/tsQzZ.png The error disappears after refreshing the page. Here is my index.js file: import ax ...

I am interested in altering the color of table rows using either JQuery or CSS

Looking to update row colors based on grouping. For example: Color the TR accordingly for every 5 rows: First 5 rows in green (0-4 Rows), Next five rows in red (5-9 Rows), Following five rows in yellow (10-14 Rows) and repeat the pattern... ...

Utilize jQuery to save the toggleClass state within a list

Presented is a function: function toggle(event) { $(`#${event.target.id}`).toggleClass('fa-power-on fa-power-off'); } Accompanying this function is a set of buttons: <i id="id1" onclick="toggle($event)"></i> & ...

Create a dynamic progress bar that integrates seamlessly with the ajaxupload functionality for a smoother video uploading

Is there a way to display an accurate time estimate alongside a visually appealing progress bar during video uploads? Currently, I am utilizing the ajaxupload javascript library in conjunction with PHP CodeIgniter for server-side functionality. ...

What is the best way to programmatically select a checkbox that was created dynamically using jQuery?

I've been scouring the internet trying to find information on what I'm attempting to accomplish, but so far I haven't come across anything helpful. The issue I'm facing is with a form that has a section dynamically added using JavaScri ...

Tips for passing a timestamp to a Postgresql DB using a Button in a Form instead of a traditional rails time_select box

I am currently developing a CAD App in Rails 4 with Ruby 2. The goal is to provide users with a button on the screen to log an on-scene time and clear scene time, especially since most users will be using touch screen computers. Instead of using the defaul ...

Emphasize specific letters in a word by making them bold, according to the user

In my app, there is a search feature that filters data based on user input and displays a list of matching results. I am trying to make the text that was searched by the user appear bold in the filtered data. For example, if the user searches 'Jo&apos ...

Ways to update child components dynamically from parent in Vue.js

In my project, I have created a form that includes custom components such as custom-input and custom-button, all wrapped in my custom-form component. Each custom component, with the exception of custom-form, features a disabled prop. My goal is to automati ...

Error: The function sort cannot be applied to the result of calling the calendar method on the moment object

I retrieve the data from this URL. I am looking to display the data sorted by a recent date. I attempted to use the map method to render the data and then proceeded to sort it based on the date, but encountered an error. To organize the dates, I made use ...

Ways to activate onChange multiple times for a single item within material ui's autocomplete feature

I am utilizing the autocomplete component in the Material UI. Upon selecting an item, the onChange props are triggered and certain actions are performed. However, I am encountering an issue where I can select the same object multiple times without the on ...

The operation of arithmetic addition (+) is malfunctioning within the ng-bind functionality

There is a specific object with the following data: objData.pendingCount = '2', objData.refundCount = '1', objData.saleCount = 43; I have successfully implemented the functionality to calculate and display the pending count percentage ...

How can I access the marker's on-screen location in react-native-maps?

Looking to create a unique custom tooltip with a semi-transparent background that can overlay a map. The process involves drawing the MapView first, then upon pressing a marker on top of the MapView, an overlay with a background color of "#00000033" is dra ...

Adding a C# variable to a URL in a Razor view using jQuery

My Razor page looks like this: @{ ViewData["Title"] = "mypage"; string ApiAddress = "https://localhost:8114/api/"; } <div> ... </div> @section Scripts{ <script> functio ...

Having trouble creating an axios instance in Vue

I recently came across a helpful tip in an article about using axios for AJAX requests in Vue. The author mentioned that by setting Vue.prototype.$http = axios, we can then use this.$http within the Vue instance, which worked perfectly for me. However, wh ...