首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我正在尝试使用react-map-gl地理位置示例,但.geojson数据不愿意加载

我正在尝试使用react-map-gl地理位置示例,但.geojson数据不愿意加载
EN

Stack Overflow用户
提问于 2019-03-28 23:07:16
回答 1查看 1K关注 0票数 0

我正在尝试使用https://github.com/uber/react-map-gl/tree/4.1-release/examples/geojson的react-map-gl地理位置示例,但是'data/us-income.geojson‘拒绝在'app.js’中加载(404)。

代码语言:javascript
复制
import {json as requestJson} from 'd3-request';  

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

'd3-request‘模块似乎被弃用了,但我无法让它与'd3-fetch’一起工作,正如所建议的那样。如何在react-map-gl中加载.geojson数据?

EN

回答 1

Stack Overflow用户

发布于 2019-04-04 04:51:49

要通过d3-fetch库加载GeoJSON文件:

1)导入json函数:import { json } from 'd3-fetch'

2)现在可以像这样下载文件内容:

代码语言:javascript
复制
json("data/us-income.geojson")
.then((data) => {
    //...
});

这是一个适用于react-map-gl libraryofficial example

代码语言:javascript
复制
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"]
    });
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55400941

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档