Exploration of features through leaflet interaction

Attempting to plot bus routes on a map using leaflet with geojson for coordinates. Facing issues with making the bus line bold when clicked, and reverting the style of previously clicked features back to default.

Current Progress

function $onEachFeature(feature, layer) {
   layer.on({
    click: function(e) {
        //highlight the clicked feature
        var $layer = e.target;

        var highlightStyle = {
            opacity: 1,
            weight: 5
        };

        $layer.bringToFront();
        $layer.setStyle(highlightStyle);
    }
 }); 
}

//leaflet map tile code would be here

//adding features with $oneachfeature function
var busFeature = L.geoJson(busRoutes, {
     style: defaultBusRouteColor,
     onEachFeature : $onEachFeature
});

busFeature.addTo(map);

The current implementation successfully changes the style of the clicked feature to highlightStyle. However, the issue is that this style persists even after clicking another feature. How can I remove the previously clicked feature's style so only one remains highlighted at a time?

Attempts so far include using jQuery's addClass/removeClass, layer.resetStyle() with leaflet, among others. Keep in mind, this needs to work smoothly on mobile devices as well; the desktop version already has a hover-based feature highlighting without any problems.

function $oneachfeature(feature, layer){
   layer.on({
      mouseover: function (e){makes feature bold}
 });
   layer.on({
      mouseout: function (e){makes feature normal again}
 });
}

Any suggestions?

Answer №1

Make sure to keep a reference to the highlighted layer so you can easily reset its style later on:

// Create a variable to store the selected layer
var selected;

// Create a new GeoJSON layer
new L.GeoJSON(collection, {
  // Define the default style
  'style': function () {
    return {
      'color': 'yellow',
    }
  }
}).on('click', function (e) {
  // Check if there is already a selected layer
  if (selected) {
    // Reset the selected layer's style to default
    e.target.resetStyle(selected);
  }
  // Set the newly selected layer
  selected = e.layer;
  // Bring the selected layer to the front
  selected.bringToFront();
  // Style the selected layer
  selected.setStyle({
    'color': 'red'
  });
}).addTo(map)

Answer №2

If you're looking for a simpler solution, consider using the resetStyle() method to reset the layer's style before applying a new one to the feature. You can achieve this by adding just one line of code to your existing function:

function $onEachFeature(feature, layer) {
    layer.on({
    click: function(e) {
        //retrieve the clicked feature
        var $layer = e.target;

        var highlightStyle = {
            opacity: 1,
            weight: 5
        };
        busFeature.resetStyle();
        $layer.bringToFront();
        $layer.setStyle(highlightStyle);
    }
}); 
}

Answer №3

Clearing Previous Highlight Before Adding a New One:

To remove the existing geoJSON selection set by .addTo(), you can use the .removeLayer() method.

map = myMap.Map
geoJson = myMap.geoJSON();

handleClick() {
    const newHighlight = {
      'color': '#FF8407',
      'fillColor': '#B522E2',
      'fillOpacity': 0.5
    };

    this.map.removeLayer(this.geoJson);

    this.geoJson = myMap.geoJSON( NewFeature, {
       style: newHighlight
    });
        
    this.geoJson.addTo(this.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

Immersive full-screen YouTube video embedded as hero background

Seeking a solution in HTML & CSS to display this embedded video as a 75vh height hero background. Currently, the iFrame maintains its width: 100% and height: 75vh, but the images themselves do not cover the entire header width. Essentially, I want it ...

Exploring Angular $resource with a playful twist

Is there a recommended method for mocking the $resource object? I've looked online, but all my attempts ended with KARMA testing. It's not what I'm looking for. I'm thinking of creating a fake object so that I can easily switch betwee ...

`Dealing with Java Servlet Exception in Kendo UI Environment`

I am facing an issue with displaying date in my Kendo UI grid. The data is coming from a Java servlet, and I have set the status code to 500 whenever an error occurs. Although I can see the error on the console, I am unable to handle it in JavaScript. My g ...

Retrieving data from PHP MySql Query and importing it into JavaScript

Currently, I am in the process of developing a count-up timer for one of our office dashboards that tracks the time since the last incident or reset. There is a page dedicated to allowing senior admins to input a new timestamp. This timestamp then gets up ...

What is the reasoning behind CoffeeScript automatically adding a function when extending an Object?

I'm currently working on a helper method to identify the intersection of two hashes/Objects in this manner... Object::intersect = (obj)-> t = {} t[k] = @[k] for k of obj t x = { a: 1, b: 2, c: 3 } w = { a: true, b: 3 } x.intersect(w) #=> ...

Error 504: The timeout issue occurred during an ajax call

When I make an ajax call to process a large amount of data and then reload the page upon success, I encounter a 504 Gateway Timeout error. The ajax call is initiated with the following parameters: $.ajax({ type:'POST', cache:false, a ...

Utilizing jQuery/AJAX to implement the :patch method on the index page in Rails

Can anyone provide insights on how to implement a feature where there is a table named Post with a column called status (having values publish or unpublish)? On the posts#index page, I want to display buttons to mark a post as publish or unpublish. <%= ...

Executing the countdown function within the catch/error block of $http.post does not work as expected in Vue.js

I encountered an issue with a simple code snippet that involves calling a countdown timer within the catch function of $http.post. this.$http.post('/api/task/post', updatedTask ,function(data){ alert('success!') }).catch( ...

Troubleshooting: NextJS Typescript getInitialProps returning null value

I am currently working with NextJS 'latest' and TypeScript to extract the token from the URL, but I am encountering an issue where it returns undefined. To achieve this, I am utilizing the getInitialProps method. The URL in question looks like th ...

Issue with Java Script inheritance in google.maps.OverlayView not functioning as expected

UPDATE: After spending another day working on this, I believe I have identified the issue, although it is not yet confirmed. Once I have verified the solution, I will update this post with an answer. My current understanding is that the problem arises fro ...

Exploring Node's Configuration File Reading Process

Trying my best to provide all the details for my question. Being a newbie to NodeJS, I appreciate your kind guidance :D In the process of developing an application in Node, focusing on enabling users to view stats regarding their Plex Media Libraries. The ...

Preserve setTimeout() Functionality Across Page Refreshes and Navigations

I am trying to display an alert message after a 15-minute delay, but the functionality is disrupted when the page refreshes or if I navigate to a different page. This all takes place on a single web page. When a specific button is clicked, it should trig ...

Using the 'useMediaQuery' function from Material UI in a class component

Currently experimenting with Material UI's useMediaQuery feature to adjust the styles of a specific component, in this case the Button component. The objective is to eliminate the outline surrounding the button when the screen size decreases. The atte ...

Maintain parent hover effect while child is being hovered over

After exploring various solutions to fix an issue, I've hit a roadblock. Adding CSS and jQuery code seemed promising at first, but upon refreshing the browser, a new problem emerged. The parent element retained its hover state background color, but th ...

I am having trouble retrieving the properties of "2d" objects using tiles[i-1], unlike standard objects in JavaScript

I've been working on constructing a random map generator by utilizing a grid composed of tiles within a canvas. In my process, I'm investigating the properties of each tile tiles[i] before handling tiles[i-1]. While this procedure seems to functi ...

Load HighCharts dynamically in a sequential manner

Currently, I am working on dynamically loading a variety of series based on user-selected projects. My tech stack includes Laravel 5.2, PHP 5.6, and HighCharts. I've successfully loaded one JSON file generated upon project selection. However, I aim to ...

When the direction is right-to-left (rtl), the floating labels in Bootstrap slide towards the center

Seeking to implement floating labels in Hebrew using bootstrap v5.2, I encountered a challenge. When switching the direction to rtl and clicking on the input box, the label slides towards the center. Here is my code snippet: <div class="form-f ...

Ways to add extra dots to your listing style

Is there a CSS property or list style that can display an expanding list? For example: Order now for a discount! <ol style="list-style: none"> <li>* Available only for the first 12 months</li> <li>** Only for new customers ...

The angular component cannot be bound as it is not recognized as a valid property

In an attempt to conditionally assign a class based on the value of a boolean variable, I have declared the variable in the parent component: public alteredSidebar: boolean; This is my approach for dynamically setting the classname: <div [class ...

React - what propType should be used for the Material UI icon?

I am planning to send a Material-UI icon to the Test component and I need to define the correct proptype for it. App.js import "./styles.css"; import VisibilityIcon from "@material-ui/icons/Visibility"; import Test from "./Test&q ...