Optimize the performance of filtering large GeoJSON files using Ajax in leaflet for the

I am managing four 2MB geoJson files with four different Layers that need to be loaded. Each layer is loaded using the following code:

LayerBoon = L.geoJSON.ajax(URL, {pointToLayer:returnBoonMarker, filter:filtertext}); 

There is also a button click function that triggers the refresh of all layers:

$("#btnFindText").click(function(){
    SeachTXT = $("#txtFind").val();
    LayerSt.refresh();
    LayerPr.refresh();
    LayerHL.refresh();
    LayerBoon.refresh();
})

Every time the button is clicked, all layers need to be re-filtered. Is there a way to keep the files in cache and just filter them again without reloading?

Answer №1

If you're looking for a simple solution, consider using the fetch method:

const api = 'json_boon.json';

async function fetchData(url) {
  try {
    const response = await fetch(url, { cache: "force-cache" });
    const data = await response.json();
    return data;
  } catch (err) {
    console.error(err);
  }
};

fetchData(api)
  .then(data => {
    L.geoJson(data).addTo(map);
  });

I included an extra parameter to ensure that the browser caches files cache: "force-cache"

The initial download occurs as usual, but subsequent downloads are fetched from the disk cache. You can verify this using devtools.

Update:

const geojsonOpts = {
  pointToLayer: function (feature, latlng) {
    return ...
  },
  filter: function(feature, layer) {
    return ...
  }
};

["one", "two", "three", "four"].map((json) => {
  fetchData(`./${json}.json`).then((data) => {
    L.geoJSON(data, geojsonOpts).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

Preventing line breaks (endline) from PHP variable when passing to JavaScript

Check out my code snippet below: <td onclick="openFile('<?php echo htmlentities ($row['name'])?>',' <?php echo htmlentities ($row['content'])?>')"> <a href="#nf" dat ...

Encountered a runtime error while trying to insert a list item <li> into a paragraph <p> element

Take a look at this code snippet: <%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication18._Default" %> <!DOCTYPE html> <html> <body> <p id="someId"></p& ...

Basic Django button for triggering view function

After attempting tutorials for a few days, I've decided to throw in the towel. Any assistance would be greatly appreciated. I'm struggling to make this work - it seems straightforward, but it's actually quite complex. All I'm trying to ...

Tips for implementing and utilizing onclick functions in EJS

My goal is to develop a trivia game with interactive features. I aim to enable users to click on an answer, which will trigger a border effect and increase the points variable. Below is the layout of the entire page: <% include ../partials/boilerp ...

Immersive Visual Symphony through Dynamic Multi-Layered

My goal is to create captivating animations for my multiple background images. Here's the CSS code I've come up with: .header { background-image: url('/img/cloud2.png'), url('/img/cloud3.png'), url('/img/cloud1.png&apos ...

Jquery problem: dealing with empty spaces

I am working on a project where I need to use jQuery to disable specific input fields, like the following: $("input[value=" + resultId[i].name + "]" ).prop('disabled', true); $("input[value=" + resultId[i].name + "]" ).css({ 'background-col ...

Restricting the scope of ngClick in multiple instances with AngularJS

I'm working on developing a directive that can toggle an element open or closed when a specific link is clicked. The issue I'm facing is that, upon clicking one trigger, all instances are being toggled open instead of just the intended one. If y ...

The HTML document is unable to locate the Angular framework

I'm encountering an issue with the code below on my HTML page - every time I run it, I receive an error message saying "angular is not defined". I've already included angular in the head section of the page so I'm puzzled as to why it's ...

Using Javascript to display or conceal a specific child element within a loop, based on which parent element has been clicked

I need assistance with creating a grid of projects where clicking on a specific 'project' in the loop will display the corresponding 'project_expanded' div, while hiding all other 'project_expanded' divs. My initial plan was ...

React JS Issue: Real-time Clock not updating in React component

I have a react application designed for attendance tracking. The issue at hand is that the time displayed does not update in real-time. Once the app is initially rendered, the time remains static. (It only updates when the app is reloaded) The code snipp ...

Switching React Icons when Clicked

I'm struggling to understand this. I want the React icons below to be filled and remain filled when clicked, changing back to outlined when another is clicked. Here's the code: import { useState } from "react"; import { Link } from "react-router- ...

Leverage JSON data using props in React JS

Currently, my data is formatted in JSON and successfully populated into props known as foxFooterData. Upon inspecting the console.log result of foxFooterData.data, the following information is visible: https://i.sstatic.net/8htNG.png I am attempting to r ...

How to Eliminate the Border on the Final Item within a React List

Hi everyone, I need help with removing the border of the last item in an unordered list when the list reaches a certain size. I initially tried this: document.querySelector('.employee-list-item:last-child').style.border = "none"; However, I enc ...

Watching a video play within a slider and transitioning seamlessly to an image once the video ends

I am currently facing an issue with a video playing inside a HeroCarousel slider. Before the slider, there is an image and after the slider, there is another image. This is my code: <div data-time="8000" data-prev-src="/media/splash/slider-left.png" ...

What is the best approach to building this using Angular?

Greetings, this marks the beginning of my inquiry and I must admit that articulating it correctly might be a challenge. Nevertheless, here's my attempt: Within the following code snippet, there lies an element that effectively fills up my designated ...

inserting a dynamic variable into a JSON string

My goal is to create a javascript object, var systemName = {"system" : varA}; However, I want the object to be structured like `{"system" :"varA"} where varA contains the variable value but is enclosed in double quotes. I attempted {"system" : "'+ ...

Switching from module.exports in Javascript to Typescript format

My Node-express code currently uses module.exports to export functions. As I am converting the code to TypeScript, I need to find out how to replace module.exports in typescript. Can you help me with this? ...

Is it possible to remove or delete a module in AngularJS?

Is there a way to clear the memory of a previous module in my app that I won't be using after routing to a different location? For instance, let's say my main Angular module is "WebApp" which has dependencies on modules like "catalogApp", "Payme ...

"Preventing Cross-Origin Requests" error encountered while trying to load a JSON document

I've been working on an online experiment using JavaScript, and I need to load parameters for the task from a JSON file. I managed to do this successfully when running the task through a live server. However, if I try to run it locally by opening the ...

Unexpected token encountered when testing Ajax call with JSON response

Currently, I have a Vue application with the following code snippet... var vm = new Vue({ el: '#Workbooks', components: { 'workbook-list': workbooklist }, data: { workbooks: [], message: '', loading: true, ...