View local GeoJSON (experimental)
Download the example Average Wind Speeds GeoJSON. This particular example showcases the usage of the File System Access API in newer versions of Chrome and Edge browsers (see the article The File System Access API: simplifying access to local files and the file system access explanation). Instead of uploading the file to a server and then retrieving it, the browser directly accesses the file locally, eliminating the need for any network transfer. Unlike the File API, this example also allows writing to the file, although that functionality is not implemented here. It’s important to note that this example is experimental as the window.showOpenFilePicker is not supported by all major browsers. For details on browser compatibility, please refer to the browser compatibility page.
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
});
const viewbutton = document.getElementById('viewbutton');
async function buttonClickHandler() {
let fileHandle;
[fileHandle] = await window.showOpenFilePicker({
// allow only single file
multiple: false,
// apply filter for GeoJSON files
types: [
{
description: 'GeoJSON',
accept: { 'application/geo+json': ['.geojson'] }
}
],
// start in download directory
startIn: 'downloads'
});
// get file handle and read content
const file = await fileHandle.getFile();
const contents = await file.text();
// parse file as json and add as source to the map
map.addSource('uploaded-source', {
'type': 'geojson',
'data': JSON.parse(contents)
});
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']
});
}
if ('showOpenFilePicker' in window) {
viewbutton.addEventListener('click', buttonClickHandler);
} else {
viewbutton.innerText =
'Your browser does not support File System Access API';
// If you want a fallback, try <input type="file">; but this uses classical file upload
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex">
<title>View local GeoJSON (experimental)</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<style>
#viewbutton {
position: absolute;
top: 0;
left: 0;
}
</style>
<div id="map"></div>
<button id="viewbutton">View local GeoJSON file</button>
<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
Add a third party vector tile source
ExamplesAdd and render third-party vector data sources on maps.