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

182
Views
i want to access a variable from function

this is my html

    <form id="upload">
        <label for="file">File to upload</label>
        <input type="file" id="file" accept=".json">

        <button>Upload</button>
    </form>
    <div id="map"></div>

this is the javascript file

    // Get the form and file field
    let form = document.querySelector('#upload');
    let file = document.querySelector('#file');
    // Listen for submit events
    form.addEventListener('submit', handleSubmit);
    /**
     * Handle submit events
     * @param  {Event} event The event object
     */
    function handleSubmit(event) {

        // Stop the form from reloading the page
        event.preventDefault();
        // If there's no file, do nothing
        if (!file.value.length) return;
        // Create a new FileReader() object
        let reader = new FileReader();
        // Setup the callback event to run when the file is read
        reader.onload = logFile;
        // Read the file
        reader.readAsText(file.files[0]);

    }

    function logFile(event) {
        let str = event.target.result;
        let json = JSON.parse(str);
        console.log('string', str);
        console.log('json', json);
    }
    var map_init = L.map('map', {
        center: [9.0820, 8.6753],
        zoom: 8
    });
    var osm = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map_init);
    L.geoJSON(json).addTo(map)

I want to use the json variable in the second function outside it's function. I am trying to create a file upload input that can easily read json file into leaflet map

L.geoJSON(json).addTo(map)
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You need to save it on the outside of the function first, let jsonFile = null;

then inside logFile function you can reassign: jsonFile = JSON.parse(str);

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