有没有办法使用react-leaflet中的矢量切片?
我知道Leaflet.VectorGrid,但它不是为react-leaflet写的?
答案 0 :(得分:4)
对于react-leaflet v2
,导出用HOC MapBoxGLLayer
包装的withLeaflet()
组件以使其起作用。
步骤:
1。安装mapbox-gl-leaflet
。
npm i mapbox-gl-leaflet
2。将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。添加此组件。
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
答案 1 :(得分:3)
这个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
,以避免mapboxgl
未定义的问题。< / p>
答案 2 :(得分:2)
您可以通过扩展MapLayer组件来创建custom component。您可以在我为here贡献的项目中看到如何在react-leaflet 1.0中完成此操作的示例。