Geojson
Step-by-Step Guide: Adding GeoJSON Data Using MlGeoJsonLayer
Step 1: Import the MlGeoJsonLayer Component
Start by importing the MlGeoJsonLayer
component in a new react component:
import { MlGeoJsonLayer } from "@mapcomponents/react-map-components-maplibre";
Step 2: Prepare Your GeoJSON Data
Create a GeoJSON file with sample data. Here's an example GeoJSON object representing a single point feature located at coordinates [0, 0].
// public/geojson/sample-data.geojson
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [0, 0]
},
"properties": {
"name": "Null Island"
}
}
]
}
Place this file inside a geojson folder within the public
directory of the React app.
Step 3: Load GeoJSON Data Dynamically
Use the fetch API to load the GeoJSON data at runtime. This method avoids bundling the data with the application, which can significantly increase the build size and negatively impact performance. Instead, the data is loaded when the component mounts, resulting in faster initial load times.
Here’s how the GeoJSON data can be fetched and written to state using the useState and useEffect React hooks:
import React, { useState, useEffect } from "react";
const MyMapComponent = () => {
const [geoJsonData, setGeoJsonData] = useState(null);
useEffect(() => {
fetch("/geojson/sample-data.geojson")
.then((response) => response.json())
.then((data) => setGeoJsonData(data))
.catch((error) => console.error("Error loading GeoJSON:", error));
}, []);
// ... Rest of the component in step 4
};