【发布时间】:2021-12-13 05:48:21
【问题描述】:
这是我的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>
这是javascript文件
// 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: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map_init);
L.geoJSON(json).addTo(map)
我想在它的函数之外的第二个函数中使用 json 变量。我正在尝试创建一个文件上传输入,可以轻松地将 json 文件读入传单地图
L.geoJSON(json).addTo(map)
【问题讨论】:
-
请澄清您的具体问题或提供更多详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。
-
我正在尝试在函数外使用函数的变量
标签: javascript html json file-upload leaflet