You can create a downloadable file from a GeoJSON object by converting it to a JSON string, creating a Blob from that string, and then triggering a download using a temporary anchor element. Here’s an example of how to do that:
function downloadGeoJSON(geojsonObject, filename = 'data.geojson') {
// Convert the GeoJSON object to a string
const geojsonStr = JSON.stringify(geojsonObject, null, 2);
// Create a Blob with the GeoJSON string and set its MIME type
const blob = new Blob([geojsonStr], { type: 'application/geo+json' });
// Create a link element
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
// Append the link to the document
document.body.appendChild(a);
// Trigger a click on the link to download the file
a.click();
// Cleanup: remove the link and revoke the object URL
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
// Example usage:
const myGeoJSONObject = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-74.5, 40]
},
"properties": {
"name": "Sample Point"
}
}
]
};
// Call the function to trigger the download
downloadGeoJSON(myGeoJSONObject, 'myData.geojson');
Explanation
-
Convert the geojson object to a string:
Use JSON.stringify() to convert your GeoJSON object into a JSON string. The optional parameters (null and 2) make the output pretty-printed.
-
Create a Blob:
The Blob allows you to store data in raw form. Here, we set the MIME type to application/geo+json, which is appropriate for GeoJSON files.
-
Generate an Object URL:
Use URL.createObjectURL(blob) to generate a temporary URL that represents the Blob’s data.
-
Create an Anchor Element:
Create a temporary <a> element and set its href attribute to the Blob URL and the download attribute to specify the filename.
-
Trigger the Download:
Append the element to the document, call click() on it, and then remove it from the document after the download initiates.
-
Cleanup:
Use URL.revokeObjectURL(url) to release the memory once done.
This approach works in modern browsers and provides a simple way to enable users to download GeoJSON content from your web app.