Reputation: 315
Good day,
I am using Mapbox in React to make a map with a polygon layer. The issue is that I have to use a local GeoJSON file for the polygon layer and I cannot use a URL. I have seen some solutions, but none in React.
Here is the code with the URL that works:
import React, { Component } from "react";
import ReactMapboxGL, { Source, Layer } from "react-map-gl";
class Mapbox extends Component {
state = {
viewport: {
width: "100vw",
height: "90vh",
latitude: 44.065256,
longitude: -125.075801,
zoom: 4,
},
};
render() {
return (
<div className="Mapbox">
<ReactMapboxGL
{...this.state.viewport}
onViewportChange={(viewport) => this.setState({ viewport })}
mapStyle="mapbox://styles/mapbox/outdoors-v11"
mapboxApiAccessToken="pk.eyJ1IjoiY2FybGF2ZGIiLCJhIjoiY2o0ZTM3d293MHRraTMydWZ5aGVtajdldSJ9.BMk1gf9OXguMOhEqcP43eg"
>
<Source
id="oregonjson"
type="geojson"
#Here is the URL:
data="https://raw.githubusercontent.com/glynnbird/usstatesgeojson/master/oregon.geojson"
/>
<Layer
id="anything"
type="fill"
source="oregonjson"
paint={{ "fill-color": "#228b22", "fill-opacity": 0.4 }}
/>
</ReactMapboxGL>
</div>
);
}
}
export default Mapbox;
The local file's name is "oregon_local.geojson" and is exactly the same as the URL.
Instead of the URL, I have tried:
<Source
id="oregonjson"
type="geojson"
data={require("../diagrams/oregon_local.geojson")}
/>
This gives an error:
Error {message: "Input data is not a valid GeoJSON object."}
I have also tried:
<Source
id="oregonjson"
type="geojson"
data={"file://D:/diagrams/oregon_local.geojson"}
/>
This gives the error:
Not allowed to load local resource
I also tried:
<Source
id="oregonjson"
type="geojson"
data={"http://../diagrams/oregon_local.geojson"}
/>
This gives the error:
Error {message: "Failed to fetch"}
How can I load a local GeoJSON as a polygon layer using Mapbox in React?
Upvotes: 2
Views: 3137
Reputation: 287
You can do it in couple ways.
Change geojson file extension to json
import oregon_local from './assets/oregon.json'
...
<Source id="oregonjson" type="geojson" data={oregon_local} >
...
This way is ok if your geojson file file is rather small, because it will be bundled into your javascript.
Place your geojson file in public/data folder
<Source type="geojson" data="/data/oregon.geojson" >
...
Upvotes: 3