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

147
Views
Remove previously selected geoJSON layer when selection changes

I have a Leaflet map with a select tag that, when a country is selected, the border is drawn around it. I can't seem to get it to remove the previous border when the selection changes though.

Here's my code so far:

//When country selected, show its border
  $("#countrySelector").change(function(){
    //Verify the function is picking up the iso_a3 value in the console
    var selectedCountry = $('#countrySelector').val();
    console.log("You have selected the country " + selectedCountry);

    //AJAX call to JSON data
    $.ajax({
      url: "countryBorders.php",
      dataType: "json",
      type: "POST",
      success: function(result) {
        var data = result["data"];

        //Create the polygon/border for the relevant country
        for(let i = 0; i < data.length; i++) {
          if(selectedCountry === result.data[i].properties.iso_a3) {
            var country = result.data[i];
            var countryStyle = {
              color: "green",
              weight: 0.7
            }
            let countryLayer;
            if(countryLayer) {
              map.removeLayer(countryLayer);
            }
            countryLayer = L.geoJSON(country, countryStyle).addTo(map);
          }
        }
      }
    })
  })

Am I doing something wrong towards the end?

I have seen other similar questions but can't seem to apply it to my example exactly.

Any help would be much appreciated.

about 4 years ago · Juan Pablo Isaza
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!