Leaflet: An issue occurred when attempting to retrieve a GeoJSON file from a multipolygon Layer

Here's the current issue:

I have successfully implemented a MultiPolygon Layer in Leaflet, but I am encountering an error when trying to convert it to a GeoJSON object.

This is my code snippet:

let colecccionPoligonos=[];
    const multiPolygonOptions = {color:'red', weight:2, fillOpacity: 0.5};
    
    function swapCoords(coords){
        
        for (const val of coords[0]){
            const aux=val[0];
            val[0]=val[1];
            val[1]=aux;
        }
        return coords;
    }

    function addPolygon(polygon){

        colecccionPoligonos.push([[swapCoords(polygon.geometry.coordinates)]]);
        
        if(multipolygon){
            map.removeLayer(multipolygon);
        }

        multipolygon=L.polygon(colecccionPoligonos,multiPolygonOptions);
        console.log(multipolygon);
        
        
        map.addLayer(multipolygon);
        console.log(colecccionPoligonos);
        console.log(multipolygon.toGeoJSON(8));
        
    }

I introduced the 'swapCoords' function because I am working with a GeoJSON file that has inverted lat/lng values.

The output includes the layer addition, the array structure passed to L.polygon, and the error shown in this image link:

The error details are as follows:

GeoJSON.js:272 Uncaught TypeError: Cannot read properties of null (reading 'alt')
    at Mi (GeoJSON.js:272:16)
    at zi (GeoJSON.js:288:4)
    at zi (GeoJSON.js:287:4)
    at zi (GeoJSON.js:287:4)
    at e.toGeoJSON (GeoJSON.js:368:16)
    at addPolygon (busqueda:477:28)
    at <anonymous>:1:1

Any insights on what might be causing this error? Let me know if you need more information.

Thanks a lot! Leandro

Answer №1

I've identified the issue.

The problem was related to the nesting levels of the array provided as an argument to L.polygon.

Even if we pass an array with more nesting levels than required, it will still create the desired layer correctly. However, when calling 'toGeoJSON()' from the Layer object created, an error occurs because it tries to access the '_latlngs' attribute and crashes during the generation of the GeoJSON object.

Therefore, I added this line:

colecccionPoligonos.push(swapCoords(poligono.geometry.coordinates));

I removed the extra brackets in the argument passed to 'push', which were present before.

The method causing the error looked like this:

// @function latLngToCoords(latlng: LatLng, precision?: Number|false): Array
// Reverse of [`coordsToLatLng`](#geojson-coordstolatlng)
// Coordinates values are rounded with [`formatNum`](#util-formatnum) function.
export function latLngToCoords(latlng, precision) {
    latlng = toLatLng(latlng);
    return latlng.alt !== undefined ?
        [Util.formatNum(latlng.lng, precision), Util.formatNum(latlng.lat, precision), Util.formatNum(latlng.alt, precision)] :
        [Util.formatNum(latlng.lng, precision), Util.formatNum(latlng.lat, precision)];
}

I believe the issue stemmed from the fact that the 'latLngToCoords' method expected a 'latlng' object as its first parameter, but due to the previous issue, this object wasn't properly generated, resulting in a NULL value being passed, causing the error.

Now, the outcome looks like this:

https://i.sstatic.net/ZHafq.png

Take note of the current nesting levels of the array now being passed to L.polygon in the console. This array will be the value of the '_latlngs' property of the created layer.

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

Issue with Discord.js (14.1) - Message Handling Unresponsive

After developing a sizable Discord Bot in Python, I decided to expand my skills and start learning JS. Despite thoroughly studying the documentation and comparing with my original Python Bot regarding intents, I am facing difficulties getting the message ...

Browse through the options in the dropdown list -Angular 6

I am looking to implement a filtering feature in my Angular app where data can be filtered based on the selected product number from a dropdown menu. The product data is structured in JSON format as shown below. component.ts productlistArray = [{ num ...

Best practices for declaring variables in ReactJS

I need help understanding how to declare a variable in a React JS class so that it is accessible in different functions. Here is my code snippet: class MyContainer extends Component { constructor(props) { super(props); this.testVariable ...

Having trouble with the find method when trying to use it with the transform

In my code, I have three div elements with different values of the transform property assigned to them. I store these elements in a variable using the getElementsByClassName method and then try to find the element where the value of the transform property ...

Complete interaction with child processes in Node.js

I have a basic C++ program compiled using the command gcc 1.cpp -o 1.exe. // 1.cpp #include <stdio.h> int main(){ int num = 0; scanf("%d", &num); printf("%d", num + 1000); scanf("%d", &num); printf("\n%d", num + 1000); ...

Receiving an error when attempting to utilize a value from the .env file in createSecretKey function

Currently, my code looks like this: const secretKey = crypto.createSecretKey( Buffer.from(process.env.SECRET, "hex") ); However, I am encountering the following error message: "The value of 'key.byteLength' is out of range. It must be > ...

Ensure that a div remains active even after it has been selected through AJAX using jQuery

I am currently utilizing ajax to display information from a database. The application I am working on is a chat app, where clicking on a specific conversation will append the data to a view. The structure of my conversation div is as follows: <div clas ...

React and React Router are causing the login screen layout to persistently display

The MUI Theme Provider I have includes a Layout with Dashboard and Order screens. Even though the user hits the '/' endpoint, the Login Screen should be displayed instead of the Layout. -App.js <ThemeProvider theme={theme}> <Router> ...

Implementing an event listener on an anchor element dynamically inserted through Javascript

I made an Ajax call that retrieves a list of movie titles. I am trying to click on a button next to each title in order to add it to my "currently watching" list. However, my "add" link is not responding to the event handler. What steps can I take to suc ...

Implementing multiple modules within a shared parent route in Angular

Currently, I am seeking a method to load multiple modules under the same path in Angular. Let's say I have three modules: AModule, BModule, and CModule, each with its own RouterModule.forChild call. My goal is to combine these modules under the route ...

Initialize global variables for jQuery objects

Here is an example of some jQuery code that I have been working on. In this code, variables are declared at a global scope, but I have been wondering if it is possible to declare jQuery objects in a similar way to how classes are declared with the cn prefi ...

jQuery does not support the addition of new fields in HTML

Recently, I've been working on creating a lucky number generator. Initially, I developed it using C# and now I'm in the process of transitioning it to JavaScript and jQuery. You can view the latest version here. However, I've encountered an ...

The attempt to cast to a number for the value of "[object Object]" at the specified path failed in mongoose

My schema is structured like this: module.exports = mongoose.model('Buyer',{ username: String, password: String, email: String, url: String, id: String, firstName: String, lastName: String, credit: Number, }); Wh ...

I am configuring Jest in my Vite and TypeScript-powered React project

I am having trouble with the relative path of the file I imported in App.test.tsx. It keeps showing me this error message: Cannot find module '@/components/items/card.tsx' from 'src/__tests__/App.test.tsx' Below is the code snippet: // ...

how to prevent autoscrolling in an angular application when overflow-x is set to

In my socket event, I am using $scope.items.unshift(item) to place the new item at the top of the list. The html code includes <ol ng-repeat="item in items"><li>{{item.name}}</li></ol> An issue arises when a new item is added whil ...

Retrieve the component information from the JavaScript function located outside of the main code

Is there a way to retrieve the component data using an external JavaScript function? I am looking to access markers, labels, and images. Vue.component('home', { template: '#home', data: () => ({ markers: [ ...

Importing a .js file into HTML with AJAX

The following JavaScript code is located within index.html between "<script type="text/javascript">" function callanular() { peticion_http = new XMLHttpRequest(); peticion_http.onreadystatechange = showContent; peticion_ht ...

Leveraging props to set the initial value of component data in Vue 3 Composition API

Currently, I am in the process of developing a search page in Vue 3 using the composition API. One of my components is responsible for displaying a snippet of data that includes specific keywords provided by the parent component. To achieve this, I need to ...

Asynchronous operations and recursive functions in the world of Node.js

When working with express and mongoose, I frequently find myself needing to perform batch operations on collections. However, the typical approach involves callbacks in nodejs concurrency coding, which can be cumbersome. // given a collection C var i = 0 ...

Tips for shifting a fabricjs element generated within a nextjs useState hook?

I encountered an issue where creating a fabric canvas in a useEffect() function prevents me from moving the added images. However, if I create the canvas elsewhere (even though it may be subject to useState asynchrony issues), I am able to move the image ...