Having an issue with onclick event when two polygons are being returned in Javascript

I am new to javascript and I have been attempting to modify the method of generating maps in leaflet using a Polish WKT database. The issue arises when multiple positions are returned, as the onclick function does not work properly. For example, when searching for "Koty 4," which has two villages with parcel number 4. What mistake am I making?


        function load(){
            map = L.map('mapa').setView([52, 19], 6);
            L.tileLayer('https://{s}.tile.osm.org/{z}/{x}/{y}.png', {
                attribution: '&copy; <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'
            }).addTo(map);
            var wmsLayer = L.tileLayer.wms('https://integracja.gugik.gov.pl/cgi-bin/KrajowaIntegracjaEwidencjiGruntow', {
                layers: 'geoportal,dzialki,numery_dzialek,budynki',format: 'image/png', transparent: true,
            }).addTo(map);
            window.osmMap = map;
        }

        function addPolygon(points){
            var gPoints = new Array();
            var _p = points.split(',');
            var cX = 0, cY = 0;
            var p0 = null;
            var gPoints2 = new Array();
            var geojson_pgons = Terraformer.WKT.parse(geomWKT);
            var xMin = 1000, yMin = 1000, xMax = -1000, yMax = -1000;
            for(var i=0;i<_p.length;i++){
                var point = _p[i].split(' ');
                if(p0==null) p0 = point;
                cX += parseFloat(point[0]);
                cY += parseFloat(point[1]);
                xMin = Math.min(xMin,point[0]);
                xMax = Math.max(xMax,point[0]);
                yMin = Math.min(yMin,point[1]);
                yMax = Math.max(yMax,point[1]);
                gPoints.push(new Array(point[1],point[0]));
            }
                map.eachLayer(function(polygon) {
                if( polygon instanceof L.GeoJSON )
                map.removeLayer(polygon);
                }); 
            var polygon = L.geoJson(geojson_pgons, {}).addTo(window.osmMap);
            var bounds = geojson_pgons.bbox();
            window.osmMap.fitBounds([ [bounds[1], bounds[0]], [bounds[3], bounds[2]] ]);    

Answer №1

Revise your code snippet to:

var featureGroup;

function load(){
//...
    featureGroup = L.featureGroup().addTo(map);
}

function addPolygon(points){
            var pointArray = new Array();
            var _points = points.split(',');

            featureGroup.clearLayers(); //Removing the existing polygons
            var polygon = L.polygon([]).addTo(featureGroup);

            for(var i=0;i<_points.length;i++){
                var pointCoord = _points[i].split(' ');
                polygon.addLatLng([pointCoord[1], pointCoord[0]]);
            }

            var boundary = polygon.getBounds();
            window.osmMap.fitBounds(boundary);
        }

To delete old polygons from the map, use featureGroup.clearLayers() after adding the polygon to a feature group.

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

retrieve the responseText in an ajax request

I am looking to receive Ajax feedback. var response = $.ajax({ url : 'linkAPI', type : 'get', dataType: 'JSON' }); console.log(response); Only the respo ...

Utilize React to efficiently reuse a single component instance multiple times within the DOM

In my React project, there is a component that consists of a styled div with text content. This same component is used multiple times in the DOM, but I am looking for a way to only render one instance and reuse it wherever needed. I attempted to use memoiz ...

Is it possible to configure the async.retry method to retry even upon successful queries, depending on a specific condition?

Currently, I am delving into the node.js async module and wondering if it's possible to modify the behavior of the async.retry method. Specifically, I'd like it to retry even on successful operations but halt based on a certain condition or respo ...

Enhancing search results with data retrieved from a jSON response

At the moment, I am using a logic to generate a list of titles. Now, I would like to include data from the response along with the code for each title in the list. const title = responseData.map(item => { return { label: item.title, val ...

What is the best way to locate the most negative integer within an array?

let test12 = [-1, -2, -3]; I'm having trouble with this one. I've been able to solve it for positive integers using the code below, but I'm not sure how to modify it for negative numbers. let test = [1 , 2, 3]; var largest= 0; for (i=0 ...

How can I extract specific elements from a string within an array of objects using a designated array of strings?

Every object must determine if a specific string exists within it. The automatic generation of the numbs array restricts my function to only extract individual numbers from the customers array (instead of each number with its corresponding name as intended ...

Implementing the array name property in a JSON object using ES5

I am currently working with a JSON object that has the following structure: {"Firstname":"john","Lastname":"doe"} My goal is to transform it into an array with a specific name 'abc': users: [{"Firstna ...

When working with Next.js Components, be aware that using a return statement in a forbidden context can lead to

Whenever I try to add a new component to my Next.js project, I encounter an error that displays the following: `./components/GridMember.js Error: error: Return statement is not allowed here | 6 | return (test); | ^^^^^^^^^^^^^^^^^^^^^^^^^ Caused ...

Combining various datasets with identical X values in a D3 bar graph

I'm currently working on creating a grouped bar chart to display performance test results using D3 for the first time. The X axis should represent parallelism, indicating the number of threads used, while the Y axis will show the duration in millisec ...

Data manipulation with Next.js

_APP.JS function MyApp({ Component, pageProps }) { let primary = 'darkMode_Primary'; let secondary = 'darkMode_Secondary' return ( <Layout primary_super={primary} secondary_super={secondary}> <Component {...page ...

Toggle on and off using a checkbox feature in conjunction with the straightforward form gem

Seeking assistance in toggling an action using a checkbox on a post form. Not well-versed in javascript or JQuery. Struggling with this task while working alone. If anyone can provide guidance, it would be greatly appreciated! Using Rails 4.2.8 an ...

After generating the dist folder using Webpack, how can we then transfer the bundle.js and css file into the statics folder?

When I execute the command npm run build or npm run build-dev https://i.sstatic.net/hy7Bm.png After running these commands, the index.html, manage2.bundle.js, and manage2.css files are generated in the root directory. However, I need to move these files ...

Step-by-step guide on visually comparing two iframes for differences

Scenario : In my project, I am dealing with 2 iframes that contain a significant number of divs and other controls, making both iframes similar in size to complete HTML websites. My goal is to compare these two iframes and identify any differences. Consi ...

Excellent Methods for Implementing a Double Click Functionality in JavaScript for Mouse

Is there a way to make the mouse double click by itself using JavaScript? I need this functionality for a Selenium project that requires testing, but unfortunately Selenium does not provide an option for double clicking. Can anyone suggest how I can achiev ...

"Incorporate live data into a line graph using highcharts and information fetched from a MySQL database

I am searching for a way to update my line chart with real-time data using ajax or json without having to reload the whole webpage. I came across some examples that demonstrate this functionality: jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highch ...

utilizing React.js, learn how to extract the most recent user input and store it within an array

My Input component generates input tags dynamically based on JSON data. I've implemented the onChange method in the input tag, which triggers a function called "handleChange" using contextAPI to record the values in another component. The issue aris ...

A guide on utilizing jQuery to select a checkbox by accessing a Laravel variable

I am seeking advice on how to automatically select the checkbox linked to a student identified through my jQuery search function. To provide context, here is an example of my "Ajax" request. Currently, it showcases the search result in an HTML 'span&a ...

`returning a functional component directly from a component's event listener`

Recently, I started exploring React and came across an issue with React Router integration. I have a React menu component that includes hyperlinks in a sidenav for navigation to other components. However, the standard React Routing method doesn't see ...

The JSON variable has been updated, however the index.js file still displays the previous value

interval = setInterval(function() { online = require("./../../server/oxide/data/online.json"); if (online.ONLINE == -1) { client.user.setStatus(`dnd`); client.user.setActivity("server offline"); } else if (online.ONLIN ...

What is the best method to make the first input field the focus in BootStrap?

Is there a way to prioritize the focus on the initial input element in an HTML form without specifying an ID? How to set the focus to the first input element in an HTML form independent from the id? I'm working with BootStrap and ASP.NET MVC4. De ...