Encountering an error known as 'Uncaught Promise Rejection'

I encountered an issue while trying to create a live tracking feature on my MapBox map.

The error seems to be related to using the same API elsewhere in the file. I suspect this is causing the problem. Is there a way to resolve this issue?

Error -

Error: There is already a source with this ID
    at i.addSource (mapbox-gl.js?e192:33)
    at r.addSource (mapbox-gl.js?e192:33)
    at VueComponent._callee5$ (Dashboard.vue?98fa:142)
    at tryCatch (runtime.js?96cf:45)
    at Generator.invoke [as _invoke] (runtime.js?96cf:271)
    at Generator.prototype.<computed> [as next] (runtime.js?96cf:97)
    at asyncGeneratorStep (asyncToGenerator.js?3b8d:5)
    at _next (asyncToGenerator.js?3b8d:27)

Mounted call -

  mounted() {
    this.createMap();
      window.setInterval(() => {
        this.getLocation()
      }, 500)
  },

First API call -

async getLocation() {
  const res = await getLocations()
  this.center = [res.data[0].longitude,res.data[0].latitude];

  // Reverse Geocoding using MapBox API
  axios.get(`https://api.mapbox.com/geocoding/v5/mapbox.places/${this.center}.json?access_token=${this.access_token}`)
      .then(async (response) => {
         this.loading = false;
         this.lat = response.data.query[1].toFixed(6);
         this.lng = response.data.query[0].toFixed(6);
         this.place_name = response.data.features[0].place_name;
         this.uncertainty_radius = res.data[0].uncertaintyRadiusInMeters;
         this.map.flyTo({center: [this.lng, this.lat], zoom: 16.5});
      });
  await this.mapMarker();
  await this.targetTrackingLine()
},

Implemented function for displaying tracking line -

async targetTrackingLine() {
  if (this.lng !== "0.000000" && this.lng !== "") {
    const response = await fetch(
        `https://api.mapbox.com/geocoding/v5/mapbox.places/${this.center}.json?access_token=${this.access_token}`
    );
    const data = await response.json();
    // save full coordinate list for later
    const coordinates = data.query;
    console.log(coordinates)
    // start by showing just the first coordinate
    data.query.coordinates = [coordinates[0]];
    // add it to the map
    this.map.addSource('trace', {type: 'geojson', data: data});
    this.map.addLayer({
      'id': 'trace',
      'type': 'line',
      'source': 'trace',
      'paint': {
        'line-color': '#000',
        'line-width': 4
      }
    });
    // on a regular basis, add more coordinates from the saved list and update the map
    let i = 0;
    const timer = setInterval(() => {
      if (i < coordinates.length) {
        data.query.coordinates.push(coordinates[i]);
        this.map.getSource('trace').setData(data);
        i++;
      } else {
        window.clearInterval(timer);
      }
    }, 10);
  }
}

Answer №1

To ensure uniqueness, the code below generates a new ID each time the targetTrackingLine function is called in order to pass it to map.addSource:

let targetTrackingCalls = 0;
async targetTrackingLine() {
   const sourceId = "trace" + ++targetTrackingCalls; // unique per call

   //... lines of source
   this.map.addSource(sourceId, {type: 'geojson', data: data});

   //... inside timer callback;

      this.map.getSource(sourceId).setData(data);

    //...
}

By utilizing a unique identifier for the source ID, it helps prevent potential errors when using the addSource method, assuming that the data being passed is a valid geojason object as specified by MapBox guidelines.

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

Golden items catch the eye in the field of view - THREE JS

I am facing an issue with ThreeJS. I have a scene set up like this: var scene = new THREE.Scene(); scene.fog = new THREE.Fog(0xf7d9aa, 100, 950); var aspectRatio = GLOBAL.WIDTH / GLOBAL.HEIGHT; var camera = new THREE.PerspectiveCamera( 45, aspe ...

I am looking for a way to automatically close an existing window and open a new window whenever a button is clicked in Angular. How can I achieve this

Looking to use window.open() to open a new window, but need to ensure that if the same window is already open from before, it must be closed before opening a new one. ...

What is the best way to reveal the square's id value upon hovering over it exclusively?

In this assignment, I am refraining from using HTML and focusing on JavaScript to create functionality. Here's my progress so far: document.addEventListener("DOMContentLoaded", function () { let button = document.createElement('button' ...

Fixing TypeError: Object #<IncomingMessage> has no method 'flash' in ExpressJS version 4.2

Currently, I am utilizing ExpressJS 4.2 and PassportJS for authenticating local users. Everything seems to be working smoothly except for when attempting to display a failureFlash message. Below is my configuration setup, thank you in advance! ==== Necess ...

Make the text appear hazy as it moves behind a see-through object

I'm attempting to create a blurred text effect that transitions behind a semi-transparent container label. I've experimented with combining the backdrop-filter and filter properties along with the filter function blur(), but I haven't been ...

Unusual occurrences in ngx-datatable (Strange row backgrounds and blurry fonts)

Attached are images for reference of this issue. I have utilized ngx-datatable to showcase data. Upon continuous hovering over visible rows, three scenarios occur: The background of one row turns black; The text of one row becomes pixelated; The text of ...

How can you access the preloaded resolve value in AngularJS ui-router when the $stateChangeSuccess event is triggered?

$stateProvider.state('home', { url: '/', resolve: { person: function() { return 'good' } } Can you help me figure out how to access the value of 'person' in the $stateChangeSuccess callback f ...

Create a duplicate of the prop object by transferring it to a fresh data

Structure of Vue components; UserList.Vue (parent component) UserEditor.vue (child component) A table displaying users is present, when a user is selected, the selectedUser property is updated with the chosen user (within UserList.vue); selectedUser: ...

Troubleshooting Issue with JQuery Date Picker: Date Not Valid

Encountering an issue when using the date from JQuery DatePicker in an SQL Statement variable, resulting in an error of invalid datetime string. Even after attempting to format it with DateTime.Parse or Convert.DateTime. JQuery DatePicker <script> ...

Arrange objects in an array by the date field using Meteor

I have updated my user collection in my Meteor app with an array of objects named contacts. This is how it looks now: { "_id" : "p6c4cSTb3cHWaJqpG", "createdAt" : ISODate("2016-05-11T11:30:11.820Z"), "services" : { ..... }, ...

The jQuery AJAX function is not functioning properly when using an ASP.net server side

Having issues with my code. The jquery ajax is not functioning properly. Here is my jquery script: $('#AddPermission').click(function () { var _permissionId = $('#PermissionId').val(); var _roleId = $('#Role_Id& ...

Issue with window.location.href and unexpected behavior in Firefox 7

I can't seem to figure out the issue I'm encountering on FF7 My ajax calls are returning a json object (jquery). if(data.result=='ok') { var url = baseURL + "azioni/makeForm/" + data.actcode + "/DIA/" + data.az_id; console.log ...

Is it possible to use velocity js to add a gradient color effect to text content?

Can I use velocity js to apply gradient color to text? I've looked at https://css-tricks.com/snippets/css/gradient-text/ My specific need is to dynamically add a changing gradient using js. Thank you in advance. ...

The AJAX request fails to trigger following the onbeforeunload event except when the page is manually refreshed

I'm currently working on implementing a solution for handling the onbeforeunload event to display a custom message when the user tries to close the browser tab. I want a prompt like: Are you sure you want to leave this page? (I don't want to use ...

Wrapping header text in Vuetify's v-data-table

Struggling with wrapping the header text on a v-data-table component. I've tried applying styles, but only tbody elements are affected. The header (thead element) remains unchanged. Any suggestions on how to get custom styling for the header? For ins ...

Is there any benefit to fetching data in `{#await}` or `onMount` instead of `load` in SvelteKit, especially considering the impact on `+server`?

keyword: displaying loading spinner Imagine accessing a route like /dashboard, where most of the page content remains constant but certain sub-components require real-time data. If I retrieve this data within a load function, the entire route will remain ...

React: Issue with applying inline styles to child components

Goal: My objective involves dynamically resizing the textarea and its parent container based on the scrollHeight of the textarea within a Main component. I also have a Button component as a child of Main for clearing text from the textarea, though that is ...

Retrieve the data attribute from the last three tag names using the Jquery Prev() method

Hi there! I'm currently trying to map out the route for going from clicking a button on the ADDtab_138269500 and then navigating back (to the previous) all the way to the first encountered span tag but in reverse order. If you want to view the code, ...

Incorporating a Registration Popup Form in ASP.NET

Looking to implement an Ajax popup for a registration form on my ASP.NET page. What is the recommended approach to achieve this? How can I ensure that my database is updated without needing to refresh the page? ...

Convert an array of objects into JSON format

Presented here is an array containing objects: (the array can contain any number of objects...) [Object, Object] 0: Object 0: "2" 1: "Laza Lazic" id_tabele: "2" naziv: "Laza Lazic" __proto__: Object 1: Object 0: "1" 1: "Pera Per ...