在 react-leaflet 中渲染 mapbox 矢量瓦片?

Render mapbox vector tiles inside react-leaflet?

有没有办法使用 react-leaflet 中的矢量图块?

我知道 Leaflet.VectorGrid,但它不是为 react-leaflet 编写的?

您可以创建 custom component by extending the MapLayer component. You can see an example of how this is done in react-leaflet 1.0 in a project I contributed to here

react-leaflet issue 中有一些非常好的矢量切片示例(下面转载了 mapbox-gl 示例)。

// @flow

import L from 'leaflet'
import {} from 'mapbox-gl-leaflet'
import {PropTypes} from 'react'
import { GridLayer } from 'react-leaflet'

export default class MapBoxGLLayer extends GridLayer {
  static propTypes = {
    opacity: PropTypes.number,
    accessToken: PropTypes.string.isRequired,
    style: PropTypes.string,
    zIndex: PropTypes.number,
  }

  createLeafletElement(props: Object): Object {
    return L.mapboxGL(props)
  }
}

以及上述组件的用法:

<Map>
  <MapBoxGLLayer
    url={url}
    accessToken={MAPBOX_ACCESS_TOKEN}
    style='https://style.example.com/style.json'
  />
</Map>

注意:您可能还需要 npm install mapbox-gl 并导入该库并分配给全局 window.mapboxgl = mapboxgl 以避免 [=14= 出现问题] 未定义。

对于 react-leaflet v2,导出用 HOC withLeaflet() 包装的 MapBoxGLLayer 组件以使其工作。

步数:

1.Installmapbox-gl-leaflet

npm i mapbox-gl-leaflet 

2.Add mapbox-gl js 和 css 到 index.html

<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.51.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.51.0/mapbox-gl.css' rel='stylesheet' />  

3.Add 这个组件。

import L from "leaflet";
import {} from "mapbox-gl-leaflet";
import PropTypes from "prop-types";
import { GridLayer, withLeaflet } from "react-leaflet";

class MapBoxGLLayer extends GridLayer {
  createLeafletElement(props) {
    return L.mapboxGL(props);
  }
}

/*
* Props are the options supported by Mapbox Map object
* Find options here:https://www.mapbox.com/mapbox-gl-js/api/#new-mapboxgl-map-options-
*/
MapBoxGLLayer.propTypes = {
  accessToken: PropTypes.string.isRequired,
  style: PropTypes.string
};

MapBoxGLLayer.defaultProps = {
  style: "mapbox://styles/mapbox/streets-v9"
};

export default withLeaflet(MapBoxGLLayer);   

4.Use MapBoxGLLayer 组件。

class App extends Component {
  state = {
    center: [51.505, -0.091],
    zoom: 13
  };

  render() {
    return (
      <div>
        <Map center={this.state.center} zoom={this.state.zoom}>
          <MapBoxGLLayer
            accessToken={MAPBOX_ACCESS_TOKEN}
            style="mapbox://styles/mapbox/streets-v9"
          />
        </Map>
      </div>
    );
  }
}

在此处找到工作代码(添加您自己的 mapbox 标记):https://codesandbox.io/s/ooypokn26y