How can I stop popup labels from appearing in MapBox GL JS when I don't want them to be visible?

Having created an application using MapBox GL JS, I have placed numerous markers all around the globe. As the mouse hovers over these markers, a description box pops up, which is what I intended. However, I am encountering an issue where these labels flicker when zooming in/out or navigating the map, making it quite bothersome.

I am seeking a simple and effective solution to prevent this annoyance. One idea could be implementing a delay in displaying the description box after hovering over a marker for a certain number of milliseconds. Another approach could involve utilizing a built-in feature to determine whether the mouse cursor is stationary or moving. Clicking on the labels is not preferred as it would only add to the inconvenience.

Below is the current code snippet I am using:

map.on('mouseenter', layerId, (e) =>
{
    map.getCanvas().style.cursor = 'pointer';
    const coordinates = e.features[0].geometry.coordinates.slice();
    const description = e.features[0].properties.description;
    const name = e.features[0].properties.name;
    while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) { coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360; }
    popup.setLngLat(coordinates).setHTML(name).addTo(map);
});

map.on('mouseleave', layerId, () =>
{
    map.getCanvas().style.cursor = '';
    popup.remove();
});

This issue must be quite common. Is there any known or creative way to address this problem without causing further irritation? Requiring the cursor to remain still above the label before showing it would essentially mimic a click action, which is not ideal. Moreover, I am already using the click event for a different function ("open related URL").

Answer №2

If you want to track the map's movement state functions in your popup handler, there are convenient options available for you. You can utilize .isZooming(), isMoving(), and .isRotating() to access relevant information from e.target.

In a quick test on one of my ongoing projects, I confirmed that this approach works effectively.

map.on('mouseenter', layerId, (e) =>
{
    if (!
        (
          e.target.isZooming() ||
          e.target.isMoving() ||
          e.target.isRotating() 
        ) 
       )
    {
      map.getCanvas().style.cursor = 'pointer';
      const coordinates = e.features[0].geometry.coordinates.slice();
      const description = e.features[0].properties.description;
      const name = e.features[0].properties.name;
      while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) { coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360; }
      popup.setLngLat(coordinates).setHTML(name).addTo(map);
    }
});

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

What is the best way to create a mirrored effect for either a card or text using CSS

Can anyone assist me with this CSS issue? When I hover over to view the movie details, the entire word flips along with it. Is there a way to make only the word flip initially, and then have it return to normal when hovered? The HTML code is included belo ...

Guide on retrieving information from Spark and showcasing it through Angular

Trying to navigate the world of Spark framework and AngularJS as a beginner, I set out to create a basic REST application. However, I hit a roadblock when it came to retrieving data from the server and displaying it using Angular. My initial task was simp ...

Is the provided code snippet considered a function-statement, function-expression, and function-expression-statement?

Currently, I am examining some code snippets from the EcmaScript.NET project. Specifically, I am delving into the definitions within FunctionNode.cs file. The comment above the definitions provides a detailed explanation of the three types of functions tha ...

Oops! Next.js Scripts encountered an error: Module '../../webpack-runtime.js' cannot be located

Looking to develop an RSS script with Next.js. To achieve this, I created a script in a subfolder within the root directory called scripts/ and named it build-rss.js next.config.js module.exports = { webpack: (config, options) => { config.m ...

Create a Rest API and implement server-side rendering concurrently using SailsJs

I am exploring the potential of utilizing the SailsJs framework for nodeJs in order to create an application. Initially, my plan was to construct a REST API in Sails and utilize AngularJs for managing the Front-End. This API would also be beneficial for o ...

What is the best way to populate a dropdown menu with data and enable users to search for specific items by typing them in?

I need assistance with populating data in a drop-down box that is not pre-defined. The data needs to be dynamically created and then displayed in the drop-down box. Currently, the data is being shown using check boxes, but I want it to appear in a drop-dow ...

Alternate routing based on conditions in Angular

I've used the "$urlRouterProvider.otherwise('{route here}')" syntax in angular to create a catch-all route in Angular UI-Router. One thing I'm curious about is whether it's possible to have conditional "otherwise" routing based o ...

Utilize the composition API in Vue.js 3 to call a function and pass in a parameter

I'm having trouble calling a function from another component. When I click on a button in my parent component, formTelemarketing(), it should send data to my other component nAsignedCalls() and call the function getCalls(param) in that component. Thi ...

What is the best way to iterate over JSON data and organize the output based on the key value?

Let's say I want to filter through the JSON data below and only push the home_team_conference if it matches Southeastern. My goal is to organize the data by home_team_conference in order to display each array on different pages of my website. Currentl ...

Background loading of child application in single-spa

I'm currently working on setting up a Single-Spa micro frontend with Dynamic Module Loading in React. The user journey I have in mind is as follows: Root Application -> Authentication Application -> User Enters Details -> API Call -> Redirect -> Admin ...

Troubleshooting problem with populating data in Mongoose Database

Here is the code snippet: app.get("/cart", checkAuthentication, function (req, res) { Orders.find({ user: req.user._id }) .populate('user') .populate('order') .exec((err, orders) => { console.log(orders); ...

unable to retrieve the chosen item from the dropdown menu

How can I retrieve the value of the selected item from a dropdown menu without getting an undefined error? You can find my code on Jsfiddle. Can anyone spot what might be causing this issue? <select class="ddl_status" id="status_ddl_20" style="display ...

Retrieving items from an array based on their class association

My challenge involves handling a list of items obtained using the following code: var searchResultItems = $(resultContainerId + ' li'); Each item in the search results can have different classes. How can I extract all items with a specific clas ...

Arrange my Firebase Angular users based on a specific value, encountering an error stating "sort is not a function

I'm working on an application using Firebase and Angular, and I have a database containing information about my users: My goal is to sort the users based on their "ptsTotal". In my users.service file, I have a function called getUsersByPoints. Howev ...

The validation of radio input signals results in an error being returned

For a while now, I've been trying to solve the issue with radio button validation in my current project. Surprisingly, it works fine when there are no other functions in the form besides the radio buttons themselves. I suspect that the problem lies wi ...

What is preventing me from successfully sending form data using axios?

I've encountered an issue while consuming an API that requires a filter series to be sent within a formData. When I test it with Postman, everything works smoothly. I also tried using other libraries and had no problems. However, when attempting to do ...

Refreshing data and manipulating arrays using AngularJS

Currently, I am developing an application utilizing AngularJS and LocalStorage. I've encountered a challenge that seems a bit too intricate for me to handle. The app involves managing lists of people with the ability to add arrays of names. The proce ...

Looping through JSON keys using ng-repeat in AngularJS

I am currently working on a project where I need to populate some JSON data retrieved from the Google Tag Manager API and then send this information to the frontend which is developed in AngularJS. At the moment, I am utilizing ng-repeat on a card compone ...

Transferring information to a view using ExpressJS and Reactjs

I have created an application that requires users to log in with Twitter credentials. Once logged in successfully, I typically pass the user data to the template using the following code: app.get('/', function(req, res, next) { log("The ...

Making sure to detect page refresh or closure using jQuery or JavaScript

Could there be a way to determine if a page has been refreshed or closed using jQuery or javascript? The current scenario involves having certain database values that need to be deleted if the user either refreshes or leaves the page. AJAX calls are bein ...