0

I am trying to use the react-map-gl geolocation example at https://github.com/uber/react-map-gl/tree/4.1-release/examples/geojson but 'data/us-income.geojson' refuses to load (404) in 'app.js'.

import {json as requestJson} from 'd3-request';  

componentDidMount() {
    requestJson('data/us-income.geojson', (error, response) => {
      if (!error) {
    this._loadData(response);
  }
});
}

The 'd3-request' module seems to be deprecated, but I can't get it working with 'd3-fetch' instead, as suggested. How do I load .geojson data in react-map-gl?

riastrad
  • 1,624
  • 10
  • 22

1 Answers1

1

To load GeoJSON file via d3-fetch library:

1) import json function: import { json } from 'd3-fetch'

2) now file content could be downloaded like this:

json("data/us-income.geojson")
.then((data) => {
    //...
});

Here is an official example adapted for react-map-gl library:

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"]
    });
  }
}
Vadim Gremyachev
  • 57,952
  • 20
  • 129
  • 193
  • 1
    Thanks, I did have to change the format of the addSource object slightly as per below: `map.addSource(SOURCE_ID, { type: 'geojson', data: data });` – craigvl Jan 18 '22 at 05:53