What is the best method for utilizing a single L.Shapefile/zip file Object and modifying the onEachFeature function for each layer?

I am currently facing an issue where I have multiple tileLayers each containing a shape file. These tile layers represent different datasets based on variables and adjust colors accordingly.

I have been able to achieve this by creating three separate Objects (L.shapefile("", { })...) and assigning each to its respective layer. However, the problem arises because my shapefile is quite large at 12MB. This means that when I follow this approach, the file gets downloaded three times.

Is there a way for me to download the zip file once and then create three instances from that single download?

    shpfile = new L.Shapefile('/mydata/shpfile.zip', {
        onEachFeature: function (feature, layer) {
            console.log(feature, layer)
            if (feature.properties) {
                var data_name = feature.properties.Name;
                val = -1
                if (data)
                    val = data[days+'DAY']
                if (val==-1)
                    val="No Data";
                var tooltip_Html = data_name + "<hr>" + days + " " + val;
                layer.bindPopup(tooltip_Html, {
                    maxHeight: 200
                });
                layer.prop = {data_name , days};
                layer.setStyle({fillColor : getColor(val), 
                                color: "black",
                                weight: 1,
                                opacity: 1,
                                fillOpacity: 0.3
                                });
                layer.on("click", layerClick);
                if (vw>768) {
                    layer.on("mouseover", function () {
                            info.update(layer.prop);
                            layer.bindTooltip('<b>'+layer.prop.loc + '</b> Name<br>' + layer.prop.val);
                    });
                                  
                    layer.on("mouseout", function () {
                        info.update();
                    });
                }
            }
        }});

    shpfile.once("data:loaded", function() {
        console.log("Shape File Downloaded! "+ days + ' days');
      
    });
    L.tileLayer(mapboxUrl, {id: 'mapbox.streets', attribution: mbAttr}).addTo(shpfile)

Answer №1

In the readme for Leaflet.shapefile, it states:

usage:

new L.Shapefile(arrayBuffer or url[,options][,importUrl]);

L.shapefile(arrayBuffer or url[,options][,importUrl]);

Users can provide either a URL to a shapefile, or an ArrayBuffer containing the zipped shapefile data.

Now, the question arises: how does one create an arrayBuffer of an external file? There are various approaches, however, using the fetch API and the Response.arrayBuffer() method is one preferred method, like so:

fetch(url)
  .then(function(response){
    return response.arrayBuffer();
}).then(function(buf){
  L.shapefile(buf, options1).addTo(map);
  L.shapefile(buf, options2).addTo(map);
  L.shapefile(buf, options3).addTo(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

Continuously invoking a function until jQuery's .post method has completed loading

As I am diving into the world of jQuery framework, I encountered a situation where I used the readyState() function while working with AJAX in regular JavaScript to display a loading gif image. However, when transitioning to using jQuery's .post() met ...

Steps for implementing a button to erase all created polygons in Leaflet and Geoman

I'm currently utilizing Geoman-free in conjunction with Leaflet to create a map where I can draw polygons. My objective is to develop a custom button within my Angular UI that can clear all the drawn polygons. How can this be achieved? Update: Let m ...

Refine results by searching through the text contained in the elements of every div

I recently came across a helpful fiddle that allows text to be hidden based on what is entered into a search box. However, I am struggling to apply this method to a div that contains multiple elements. Is there a way to modify the jQuery in the provided fi ...

RxJS BehaviorSubject allows you to retrieve the current value or obtain a new one depending on a specific condition

I am managing a subject that consumers subscribe to: private request$: Subject<Service> = new BehaviorSubject(null); Upon initialization, my components utilize this function: public service(id: number): Observable<Service> { return this. ...

In Visual Studio, the .js.map files and .js files seem to be mysteriously hidden, leaving only the TypeScript .ts files visible

In the past, I utilized Visual Studio Code for Angular 2 development and had the ability to hide .js and .js.map files from the IDE. Now, I am working on a project using VS 2017 Professional with Typescript, Jasmine, Karma, and Angular 4. Task Runner, etc. ...

Activate the Air-mode feature in Summernote in addition to the standard toolbar

Is it possible to have both the default toolbar and air-mode toolbar enabled in the Summernote editor? For instance, I would like the user to utilize the default toolbar for general text editing, but have the air-mode toolbar appear when they select a spe ...

error: local server did not return any data

I am currently using PHP on a Linux machine. In my HTML code, I have set up an AJAX request to the local Apache server (check http://localhost), with the intention of displaying the data from the server on the screen. However, for some reason, nothing is b ...

Can you explain the significance of 1x, 3x, etc in the Karma code coverage report for Angular unit testing?

I am a beginner when it comes to Unit Testing in Angular. Recently, I set up karma with code coverage using angular-cli. After running the command ng-test, I checked out the code coverage report and noticed references like 1x, 3x, etc. next to my code line ...

Switching button class when hovering over another div

When you click on the "collapsible-header" div, I want the text "TE LAAT" in the button to change to "NU BETALEN". Currently, the CSS code changes the text on hover, but I want it to change on click when the collapsible-header also has the active class. T ...

To prevent flickering when using child flex elements, it's best to use position fixed along with a dynamically updated scrollbar position using Javascript

My navigation component includes a slim banner that should hide upon scroll and a main-nav bar that should stick to the top of the screen and shrink when it does so. I initially looked into using Intersection Observer based on a popular answer found here: ...

An error occurred while attempting to reset your password on Parse.com (JS SDK) due to an

I am having trouble resetting my password in my angularjs App. I am utilizing Parse (js SDK) as the backend. Even though I am following the documentation and using Parse.User.requestPasswordReset, I keep encountering error 125 which states invalid email ad ...

There seems to be an issue with the useReducer value not updating when logging it in a handleSubmit function

I'm currently incorporating useReducer into my Login and Register form. Interestingly, when I attempt to log the reducer value, it only displays the default value. However, if I log it within the useEffect hook, it functions correctly. Below is a sn ...

React.js Form Validation issue: When using input type "number", the text field remains a single value even after attempting to delete characters with the backspace key

Experiencing difficulty in clearing the input field value, even after pressing backspace the value remains constant. One particular value persists in the input field. import * as React from "react"; import { Button, Form } from "react-boots ...

Create a lockscreen feature in AngularJS that becomes active after a period of inactivity

I am looking to integrate a lockscreen feature into my app using Angular.js. This lockscreen will consist of a route and an HTML template containing a form that prompts the user to re-enter their password in order to keep their session active. The purpose ...

trouble encountered while sending data to php using ajax and json

Despite trying multiple solutions, my script is still not working properly. It functions without the $_POST value and without JSON, but when both are included, it fails to work. The error message displayed by the function is as follows: <b>Notice< ...

Store the output of a mysql query in a variable for future reference

As I work on developing a backend API for a private message system, I have encountered a challenge with one of my functions. The issue arises when I attempt to store the result of an asynchronous call in a variable for future use. Here is the code snippet ...

Discover automatically generated titles for dynamic hyperlinks

I am looking to generate dynamic links for a collection of documents with varying names, such as Test, Test2, and so on. I want the link text to display as "Document TestN," where N is the specific document number. Currently, I am able to create the links ...

Determine with jQuery whether the img src attribute is null

My HTML structure is as follows: <div class="previewWrapper" id="thumbPreview3"> <div class="previewContainer"> <img src="" class="photoPreview" data-width="" data-height=""><span>3</span> </div> </div> ...

What is the best way to retrieve the current state from a different component?

My goal is to access a user set in another component. I passed the state from the highest component (which is the app) by utilizing this function for state change. handleRegisterSubmit(e, username, password) { e.preventDefault(); axios.post('/au ...

Tips for retrieving multiple values or an array from an AJAX request?

Is there a correct way to pass multiple sets (strings) of data back after executing an ajax call in php? I understand that echo is typically used to send a single string of data back, but what if I need to send multiple strings? And how should I handle th ...