6

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

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

4

3 回答 3

6

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

脚步:

1.安装mapbox-gl-leaflet

npm i mapbox-gl-leaflet 

2.添加mapbox-gl js和cssindex.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.添加这个组件。

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.使用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

于 2018-11-15T10:34:22.747 回答
3

在这个react-leaflet 问题中有一些非常好的矢量图块示例(下面复制了 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以避免mapboxgl未定义的问题。

于 2017-06-01T16:07:16.523 回答
2

您可以通过扩展 MapLayer 组件来创建自定义组件。您可以在我参与的项目中看到如何在 react-leaflet 1.0 中完成此操作的示例

于 2017-03-13T21:28:39.007 回答