通过d3-fetch
库加载 GeoJSON 文件:
1)导入json
功能:import { json } from 'd3-fetch'
2)现在可以像这样下载文件内容:
json("data/us-income.geojson")
.then((data) => {
//...
});
这是一个适用于library的官方示例:react-map-gl
const MAPBOX_TOKEN =
"--YOUR_KEY-GOES-HERE--"; //
const SOURCE_ID = "national-park";
class Map extends Component {
constructor(props) {
super(props);
this.state = {
viewport: {
latitude: 40.492392,
longitude: -121.403732,
zoom: 11
}
};
this.mapRef = React.createRef();
this.handleMapLoaded = this.handleMapLoaded.bind(this);
this.handleViewportChange = this.handleViewportChange.bind(this);
}
handleViewportChange(viewport) {
this.setState({ viewport });
}
handleMapLoaded() {
const map = this.mapRef.current.getMap();
json("data/national-park.json")
.then((data) => {
this.initMapData(map, data);
});
}
render() {
const { viewport } = this.state;
return (
<div style={{ height: "100%" }}>
<MapGL
ref={this.mapRef}
onLoad={this.handleMapLoaded}
mapStyle="mapbox://styles/mapbox/outdoors-v11"
width="100%"
height="480px"
{...viewport}
onViewportChange={this.handleViewportChange}
mapboxApiAccessToken={MAPBOX_TOKEN}
/>
</div>
);
}
initMapData(map, data) {
map.addSource(SOURCE_ID, data);
map.addLayer({
id: "park-boundary",
type: "fill",
source: "national-park",
paint: {
"fill-color": "#888888",
"fill-opacity": 0.4
},
filter: ["==", "$type", "Polygon"]
});
map.addLayer({
id: "park-volcanoes",
type: "circle",
source: "national-park",
paint: {
"circle-radius": 6,
"circle-color": "#B42222"
},
filter: ["==", "$type", "Point"]
});
}
}