URL parameter for Mapbox GL JS

We have successfully integrated mapbox gl js into our system. Our map displays locations/stores that are clickable, showing a mapbox popup with contact information and opening hours when clicked.

https://i.sstatic.net/QYyBf.png

We aim to use parameters in the URL to easily access specific listings (stores/locations). For instance, by accessing "store locator" with ID 1 in the URL, we want the map to focus on that location and display the corresponding mapbox popup for location 1. In this scenario, let's assume the JSON property "LocationX" is assigned an ID of 1

I attempted to achieve this using the code below, but it was unsuccessful

const queryString = window.location.search;
        const urlParams = new URLSearchParams(queryString);
        const storeID = urlParams.get('branch')
        console.log(storeID);

        $(document).ready(function() {
                if (storeID == "1") {
                  $("#link-0").click();
                };
        })

#Link-0 is the id for one of the locations/listings.

<div id="listing-0" class="item active"><a href="#/" class="title" id="link-0">Broxburn</a><div>

Mapbox GL JS

/**
       * Add the map to the page
       */
      const map = new mapboxgl.Map({
        container: 'map',
        style: 'mapbox://styles/mapbox/light-v10',
        center: [-1.5466858011960802, 53.478230478528126],
        zoom: 5,
        scrollZoom: true
      });

// Add geolocate control to the map.
map.addControl(
new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
// When active the map will receive updates to the device's location as it changes.
trackUserLocation: true,
// Draw an arrow next to the location dot to indicate which direction the device is heading.
showUserHeading: true
})
);

      const stores = {
        'type': 'FeatureCollection',
        'features': [
          {
            'type': 'Feature',
            'geometry': {
              'type': 'Point',
              'coordinates': [-3.4524379167753025, 55.942792181678804]
            },
          'properties': {
          'refName': 'Broxburn',
              'phoneFormatted': 'xxxxxxxxxxxxxxxxxx',
              'phone': 'xxxxxxxxxxxxxxxxxx',
              'phone2': 'xxxxxxxxxxxxxxxxxx',
              'address': 'xxxxxxxxxxxxxxxxxx',
              'city': 'xxxxxxxxxxxxxxxxxx',
              'country': 'xxxxxxxxxxxxxxxxxx',
              'postalCode': 'xxx xxx',
              'email': 'xxxxxxxxxxxxxxxxxx',
              'service1': 'xxxxxxx',
              'service2': 'xxxxxxx',
              'weekday': 'xxxxxxx - xxxxxxx',
              'weekend': 'xxxxxxx - xxxxxxx',
              'sunday': 'Closed'
            }
          },
          {
            'type': 'Feature',
            'geometry': {
              'type': 'Point',
              'coordinates': [-2.9544548591328614, 54.92245269446434]
            },
          'properties': {
          'refName': 'Carlisle',
              'phoneFormatted': 'xxxxxxxxxxxxxxxxxx',
              'phone': 'xxxxxxxxxxxxxxxxxx',
              'phone2': 'xxxxxxxxxxxxxxxxxx',
              'address': 'xxxx...

Answer №1

Although your code appears to be well-written, there might be a potential race condition occurring between the $(document).ready(...) and the map.on('load', ...) events. The former event fires before the latter one, causing the JavaScript to attempt clicking on a link that hasn't been created in the DOM yet. To resolve this issue, consider rearranging your code so that the section responsible for "clicking" on links comes after the link creation.

You could create a function like this:

function clickSelectedStore() {
  const queryString = window.location.search;
  const urlParams = new URLSearchParams(queryString);
  const storeID = urlParams.get('branch')
  console.log(storeID);
  
  if (storeID) {
    $('#link-' + storeID).click();
  }
}

Then, call this function at the end of the map.on('load', ...) event (after the buildLocationList(...) function has finished execution).

If this adjustment doesn't solve the issue, consider creating a Minimal Reproducible Example, which will help others analyze your code more effectively.

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

Different choices for data attributes in React

Recently, I downloaded a new app that requires multiple API calls. The first API call retrieves 20 Objects, each with its own unique ID. The second API call is made based on the IDs from the first call. To display this data in my component: <div> ...

Implementing Dual Submit Buttons in Node.js using Express Framework

Struggling with implementing a like and dislike function in my node js app. Currently, I can only do one at a time. Below is the HTML code snippet: <form method="post" name="ratings"> <input type="submit" name="vote" value="like"> < ...

Can someone provide guidance on utilizing the index correctly within this v-for to prevent any potential errors?

I am encountering an issue with using index in a v-for loop to implement a function that deletes items from an array. The linter is flagging "index is defined but never used" as an error. I am following the instructions provided in a tutorial, but I am un ...

What's the best way to trigger useEffect whenever a useRef variable gets updated?

I am facing an issue where the variable changes are lost on every re-render when trying to have useEffect run every time it modifies a variable. Using useRef to store the variable between renders leads to useEffect not detecting changes to a ref. I came a ...

Making an HTTP POST request in AngularJS

Upon sending a POST request with headers specified as content-type: application/JSON, the cookie is not being set in the Request Headers. However, when I modify the headers to be content-type: application/x-www-form-urlencoded, the cookie is successfully ...

Struggling with showcasing Trips in my React Native project and looking for guidance on the best approach to implement it beautifully

API: app.get('/trip', async (req, res) => { try { const employeeId = req.query.user; const empId = new ObjectID(employeeId); // Retrieving Fleet associated with the driver's ID const fleet = await Fleet.findOne({ a ...

When resetting a form, the styled radio buttons remain selected and do not deselect

I have a set of three styled radio buttons for car rental pickup locations: <div class="col-md-12 form-group"> <label for="car-rental-pickup-location" class="mb-2">Pickup Location<small class="text-danger">*</small></label>&l ...

The scroll function is failing to activate at the desired location

I've been trying to fine-tune a window scroll function I created. Initially, I attempted to use waypoints for this, but unfortunately, I couldn't get it to work as expected. The main issue I'm facing is that the function triggers too early ...

Traversing through intricate weather data in JSON with AngularJS

I've been diving into learning angularJS and have hit a roadblock when it comes to extracting values from specific objects in a JSON file. Despite searching online for solutions, all I've found are basic examples that don't quite fit my curr ...

How can I update my outdated manifest v2 code to manifest v3 for my Google Chrome Extension?

Currently, I am developing an extension and using a template from a previous YouTube video that is based on manifest v2. However, I am implementing manifest v3 in my extension. Can anyone guide me on how to update this specific piece of code? "backgro ...

Angular JWT token validation error

I am currently experiencing an issue with the Angular JWT token. It works perfectly fine on my API when tested using Postman, but for some reason it is not working when called from Angular. Here are the request details: https://i.sstatic.net/L6Tsr.png I c ...

PHP and AJAX allow for seamless data retrieval without the need for page refreshing, and the data can be easily displayed in a modal window

I am currently encountering an issue with sending data to another page without refreshing. I am able to send the data as text, but for some reason, I am unable to send it as a modal. Why might this be happening? Here is an image of my current page https:/ ...

Iterate through the form fields and save the information into an object

I am attempting to create a JavaScript object by looping through form inputs. const data = {}; // loop through each input found in form $('#form_name').filter(':input').each(function() { const $id = $(this).attr('id'); c ...

Issue with variable not being refreshed within requestJS's data event

I have been attempting to store the response from a URL in a variable for caching purposes and then send it upon subsequent requests. I am currently writing to the variable during the data event of the request. The variable does get updated, but I am encou ...

What are the reasons behind the failure of this regex matching in Angular specifically on Safari browser?

In my angular project, I have the following code. It works perfectly fine in Chrome and Firefox, but in Safari, it throws an exception. var shour = "9:00:00 PM CDT"; var ehour = "12:00:00 AM CDT"; var conver_shour = shour.match(/^(\d+):(\d+)/)[ ...

Ways to convert various methods of storing JSON text strings

In order to cater for localization in my Unity game to be used in WebGL, I am looking to store all the game dialogues and text in a JSON file. To assist with building the narrative structure of dialogues, I have opted for the Fungus framework within Unity. ...

Adjust parent div size based on image size increase

I am currently facing a situation where I have a page displaying an image, but sometimes it appears too small. In order to make the image larger, I have utilized CSS Transform and it is working well. However, the issue lies in the fact that the parent DIV ...

Positioning Div at the Bottom of a Interactive Flip Card Using Bootstrap 4

My current project features a creative flip image card created using bootstrap and js. On the back of the card, there is a title, a main text body, and a few small additional pieces of information. My goal is to have these three small bits of information a ...

Improving the visualization of large GPS tracks on Google Earth Plugin

I need to display GPS routes on Google Earth using the Google Earth API. However, with approximately 20,000 points per route, the performance is not optimal. The code I have implemented successfully draws the tracks but struggles with rendering time and tr ...

The controller is failing to receive the post data

I am currently experiencing an issue with my implementation of the jquery UI datepicker, specifically when trying to send the from and to dates to the controller. The problem lies in the fact that the controller is not receiving the necessary post data. H ...