import React, { useRef, useState, useEffect } from 'react';
import { Map, View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import { defaults } from 'ol/control';
import { fromLonLat } from 'ol/proj';
import { OSM, Stamen, BingMaps } from 'ol/source';
import { Radio } from 'antd';
import 'ol/ol.css';
import styles from './index.less';
export default function Index() {
// 地图
const map = useRef<any>();
// 当前图层
const [currentLayer, setCurrentLayer] = useState('osm');
useEffect(() => {
// 初始化地图
initMap();
}, [])
/**
* 初始化地图
*/
const initMap = () => {
// 创建一个使用OpenStreetMap地图源的瓦片图层
let osmLayer = new TileLayer({ source: new OSM() });
osmLayer.set('layerId', 'osm');
// 创建一个使用Stamen Map地图源的瓦片图层
let stamenMapLayer = new TileLayer({
source: new Stamen({
layer: 'watercolor'
})
});
stamenMapLayer.set('layerId', 'stamenMap');
// 创建一个使用Bing Map地图源的瓦片图层
let bingMapLayer = new TileLayer({
source: new BingMaps({
key: 'Bing Map的key,可以去官网申请',
imagerySet: 'AerialWithLabels'
})
});
bingMapLayer.set('layerId', 'bingMap');
// 加载地图
map.current = new Map({
// 挂载到id为map的div容器上
target: 'map',
// 设置地图图层
layers: [osmLayer, stamenMapLayer, bingMapLayer],
// 设置地图视图
view: new View({
// 设置空间参考系统为'EPSG:3857'
projection: 'EPSG:3857',
// 地图的显示中心
center: fromLonLat([0, 0]),
// 地图的显示层级
zoom: 3
}),
controls: defaults({
// 移除归属控件
attribution: false,
// 移除缩放控件
zoom: false,
// 移除旋转控件
rotate: false
})
})
}
useEffect(() => {
const layerCollection = map.current.getLayers().getArray();
layerCollection.forEach((v: any) => {
if (v.get('layerId') === currentLayer) {
v.setVisible(true);
} else {
v.setVisible(false);
}
});
}, [currentLayer])
return (<div className={styles.mapCon}>
<div id='map' className={styles.map}></div>
<div className={styles.switchLayer}>
<Radio.Group onChange={(e) => { setCurrentLayer(e.target.value) }} value={currentLayer}>
<Radio value={'osm'}>OpenStreetMap</Radio>
<Radio value={'stamenMap'}>Stamen Map</Radio>
<Radio value={'bingMap'}>Bing Map</Radio>
</Radio.Group>
</div>
</div>)
}
参考文章
OpenLayers教程七:地图控件之自己实现图层切换控件
OpenLayers教程十一:多源数据加载之用最简单的方式加载瓦片地图
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。