Search code examples
javascripthtmljsonfile-uploadleaflet

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)

Solution

  • 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);