How to make L.divIcon stand out on Leaflet map with mouse hover or through programming

Is there a way to highlight the L.divIcon svg markers on mouseover or trigger it from another action, such as clicking a button?

An example test case can be found here: https://jsfiddle.net/sxvLykkt/5/

The markers are dynamically generated (originally geoJson) and added to a L.FeatureGroup(). When hovering over a marker, a larger version of the icon (divIconActive) is displayed on a temporary layer but flickers instead of working smoothly. How can this issue be resolved?

Additionally, how can I access the markers when a button is clicked? Perhaps by their index? I'm struggling to understand this concept.

Below is a snippet of the code showing how the markers are created:

// initializing map and tileLayer -> jsfiddle
var coords = [[53, 13],[49, 10],[46, 12],[51, 16]];

$.each(coords, function(i,e){
  // create the button
  $('#controls').append('<button>'+i+'</button>')

  var marker = L.marker(e, {
    icon: divIcon,
    id: i
  });

  locationLayer.addLayer(marker);

  marker.on('mouseover', function(e){
    markerTemp = L.marker(e.latlng, {
        icon: divIconActive
    }).addTo(map);

  });

  marker.on('mouseout', function(e){
    markerTemp.remove();
  });

});

locationLayer.addTo(map);

$('button').on('click', function(e){
    alert('Highlight the right marker!')
});

Answer №1

To address the marker issue, make the following adjustment:

marker.on('mouseover', function(e){
    markerTemp = L.marker(e.latlng, {
        icon: divIconActive
    }).addTo(map);

  });

  marker.on('mouseout', function(e){
    markerTemp.remove();
});

Replace it with:

marker.on('mouseover', function(e){

    // Create a temporary layer for the hover state
    markerTemp = L.marker(e.latlng, {
        icon: divIconActive
    }).addTo(map);

    markerTemp.on('mouseout', function(e){
      markerTemp.remove();
    });

});

This modification ensures that the marker is removed when the mouse moves out of the main marker.

Another way to customize button clicks is:

Assign an ID to the buttons upon creation:

$('#controls').append('<button id="button'+i+'">'+i+'</button>');

After creating the marker, add the corresponding button code:

var marker = L.marker(e, {
    icon: divIcon,
    id: i
  });

  locationLayer.addLayer(marker);

  // Button functionality for this marker
  $('#button'+i).on('click', function(e){
    alert(i);
    // Implement desired actions here
  }); 

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

Storing complex data structures in Firebase using VUEX

I am struggling to properly store my 'players' data within my team data structure. Currently, it is being saved with the team id but I need it to be nested inside of teams. Essentially, I want the players to seamlessly integrate and be appended ...

How can Angular2 detect when an entity is clicked within a window?

There are multiple items generated using *ngFor: <my-item *ngFor="let item of myArray" [p]="item"></my-item> I am able to handle a click event like this: <my-item ... (click)="doWork(item)"></my-item> However, I want to avoid a ...

"Displaying the state value retrieved from a custom hook is not working as expected

Creating a custom hook, Custom.js: import React, {useState, useEffect} from 'react'; import Clarifai from 'clarifai'; const app = new Clarifai.App({ apiKey: 'XXXXXXXXXXXXXX' }) const CustomHook = () => { const [i ...

react-datepicker displaying error message "Preventing default action not possible within a passive event listener invocation"

I've integrated the react-datepicker library in portal mode. While it functions well on browsers, I encounter an error when using mobile browser mode. An issue arises stating: "Unable to preventDefault inside passive event listener invocation" Des ...

Vue: Customize data based on userAgent

As a newcomer to VUE, I am attempting to dynamically modify the disabled value based on the userAgent in order to display or hide the paymentMethod: data() { return { paymentMothods: [ { name: 'Visa che ...

Tips for postponing the execution of following tasks until the completion of the setState and ensuring that they are reliant on

I'm encountering an issue with the useEffect hook in my React app that uses useState. Here's the code snippet: const [jobTypes, setJobTypes] = useState([]); const getJobTypes = async () => { try { const response = await fetch(&a ...

The website on iPad automatically zooms in upon opening and then increases the zoom level even further when a specific button is tapped

I recently coded a website using html, css, and js. It seems to work perfectly on all devices except for the iPad. Interestingly, when I use the iPad emulator in Google Chrome, everything appears normal. However, when I open the website on an actual iPad, ...

I am unable to append a new attribute to an object

I am currently working on a project using Node, Express, and Mongoose. In my controller, I'm trying to retrieve all orders for the logged-in client from the database. I want to display the status of each order and based on the state, add the available ...

Looking to update the display of an array received in JSON format and then show it using ng-repeat?

Upon receiving a response from the backend, I am saving it in a variable called "allinfo" in my controller. The data received includes the name, date of birth, and hobby of a person. The hobby is an array that can contain any number of elements. In my vie ...

Retrieve information from a MongoDB document based on the specific month

If I have a user document with a createdAt field, how can I retrieve data by month in the condition? The format of the createdAt value is as follows: 2016-10-08T16:21:40.935Z Account.find({'what should be passed here?'}, function(err,response){ ...

When a base html tag is dynamically added, the browser mistakenly loads assets twice

When managing relative paths on a website, I utilize the <base> tag within the <head> section of each page. Although all resources loaded via relative-like paths in the documents are displayed correctly, my observations show that browsers such ...

Dealing with the challenge of managing multiple instances in a setup involving Ajax long polling (comet) and PHP on Lighttpd v1

I am a newcomer to this platform, so I hope to provide all the necessary details about my question. I have been attempting to set up a mechanism for "new message arrived notification" using long polling. Currently, I am triggering the polling request thro ...

Can RethinkDB and Node.js/Express handle parallel queries with multiple connections?

Is there a more efficient method for running parallel queries with the RethinkDB Node driver without opening multiple connections per request? Or is this current approach sufficient for my needs? I'd like to avoid using connection pools or third-party ...

Jade Compilation with Gulp

Currently utilizing gulp-jade, I have encountered an error with a particular template: 557| 558| > 559| 560| .tabs-wrap(ng-show="eventExists"): .contain-center 561| 562| #room-tabs-contain.contain-disable.contain: .contain-center unexpec ...

Adding and Removing Attributes from Elements in AngularJS: A Step-by-Step Guide

<input name="name" type="text" ng-model="numbers" mandatory> Is there a way to dynamically remove and add the "mandatory" class in Angular JS? Please note that "mandatory" is a custom class that I have implemented. Thank you. ...

What is the best method for adding anchors or appending items in aspx pages?

I have created code for an image gallery on my webpage, "gallery.aspx". The situation is that I have an external aspx page with various links. When a user clicks on one of these links, I want them to be redirected to the image gallery but to a specific ima ...

Using PHP to upload images through AJAX increases efficiency

Worked tirelessly on this script all night still unable to fix the bug. The issue is that when I select an image and click upload, it uploads the current image file. Then, if I select another image and click upload, it uploads two new files along with the ...

When using the jQuery datepicker with the minDate set to 0, any past dates entered in the text box will be automatically reset to the current date

How can I prevent users from selecting past dates in a jQuery datepicker, while keeping any existing past dates displayed as is? My current code looks like this: $("#t1").datepicker({ minDate:0 }); And the text box code is, <input type="t1" va ...

Incorporating .txt files into a static webpage using only HTML and JavaScript

Exploring the realm of web page creation for the first time has left me in need of some guidance. I have successfully added an upload feature for text files on my web page, but I am struggling to embed a text file directly into the page source. With Java s ...

Incorporate a Flask variable into a webpage seamlessly without refreshing the page

I am facing a challenge in importing the variable test_data from Flask to my webpage without having to reload it. I have tried clicking a button, but haven't been successful so far. Any suggestions? Flask: @blueprint.route('/data_analysis' ...