Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
Javascript: Correct syntax for making editable custom properties (on click, toggle colour of Leaflet GeoJSON object)

I've written the following javascript code using leaflet to make multiple red polylines with each having property called "active" which starts as true.

    for (let i = 0; i < railLinks.length; i++) {
        var polyline = new L.geoJSON(railLinks[i].polyline, {
          linkNumber: railLinks[i].linkNumber,
          active: true, //THIS LINE DOESNT DO WHAT I THOUGHT IT WOULD
          style: function(active) {
            return {
              weight: 2,
              color: 'red'
            };
          }
        }).addTo(map);
        
        polyline.on('click', function() {
          set = !this.active
          this.active = set;
          this.setStyle({
            color: getColor(set)
          });
          
        });
    }
    
    function getColor(x) {
      return x  ?   'black':
                    '#888888';
    };

I'm tring to implement a toggle so that when you click a true polyline it turns to false and vice versa.

With this I would expect the first click to make grey ("false"), then black, then grey etc. Instead the first click makes black (representing true), suggesting the initial state was not true.

I would imagine the problem is with my syntax and that

active: true

is not the same property being changed as the later

this.active

as I can set the first active to any value without affecting the on click behaviour. Any ideas what this should be?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

For anyone's information who comes across a similar problem, I've now solved my issue with the code below:

    for (let i = 0; i < railLinks.length; i++) {
        var polyline = new L.geoJSON(railLinks[i].polyline, {
          linkNumber: railLinks[i].linkNumber,
        }).addTo(map);
        polyline.active = true;
        polyline.setStyle({
            weight: 2,
            color: 'red'
        });
        polyline.on('contextmenu', function() {
          set = !this.active
          this.active = set;
          this.setStyle({
            color: getColor(set)
          });
        });
    }
    
    function getColor(x) {
      return x ? 'black':'#888888';
    };
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!