View local GeoJSON
Download the example Average Wind Speeds GeoJSON. Instead of uploading the file to a server and reading it from there, the browser directly accesses the file locally, eliminating the need for any network transfer. If you wish to write to the file that has been opened, you can refer to the following example that utilizes the File System Access API: View local GeoJSON (experimental).
NPM module setup
npm install --save @maptiler/sdk
import { Map, MapStyle, config } from '@maptiler/sdk';
import '@maptiler/sdk/dist/maptiler-sdk.css';
config.apiKey = 'YOUR_MAPTILER_API_KEY_HERE';
const map = new Map({
container: 'map',
style: MapStyle.STREETS,
center: [-8.3226655, 53.7654751],
zoom: 8
});
function handleFileSelect(evt) {
const file = evt.target.files[0]; // Read first selected file
const reader = new FileReader();
reader.onload = function (theFile) {
// Parse as (geo)JSON
const geoJSONcontent = JSON.parse(theFile.target.result);
// Add as source to the map
map.addSource('uploaded-source', {
'type': 'geojson',
'data': geoJSONcontent
});
map.addLayer({
'id': 'uploaded-polygons',
'type': 'fill',
'source': 'uploaded-source',
'paint': {
'fill-color': '#888888',
'fill-outline-color': 'red',
'fill-opacity': 0.4
},
// filter for (multi)polygons; for also displaying linestrings
// or points add more layers with different filters
'filter': ['==', '$type', 'Polygon']
});
};
// Read the GeoJSON as text
reader.readAsText(file, 'UTF-8');
}
document
.getElementById('file')
.addEventListener('change', handleFileSelect, false);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex">
<title>View local GeoJSON | NPM example</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<style>
#file {
position: absolute;
top: 0;
left: 0;
}
</style>
<div id="map"></div>
<input
type="file"
id="file"
name="file"
accept="application/geo+json,application/vnd.geo+json,.geojson"
/>
<script type="module" src="./main.js"></script>
</body>
</html>
body {margin: 0; padding: 0;}
#map {position: absolute; top: 0; bottom: 0; width: 100%;}
Related examples
View local GeoJSON (experimental)
ExamplesView local GeoJSON with experimental File System Access API.