地图操作
切换地图
openlayers 中切换地图使用 setSource()
方法,它接受一个 source 源作为参数。
js
import { OSM, BingMaps } from "ol/source";
const osm = new OSM();
const bingmap = new BingMaps({
key: "AuTngMwN4lNgKFXy91uWt7eZjolIRsky9u2E3E9z6W7ru6b-zVvKtwz0n9ZSaD7i",
imagerySet: "Aerial"
});
const layers: any = new TileLayer({
source: osm
});
let map: any;
onMounted(() => {
map = new Map({
target: "map",
layers: [layers],
view: new View({
projection: "EPSG:4326",
center: [102.7362, 38.0249],
zoom: 5
})
});
});
function handleClick() {
if (layers.getSource() === osm) {
layers.setSource(bingmap);
} else {
layers.setSource(osm);
}
}
显示/隐藏图层
openlayers 中控制图层显示/隐藏的方式有两种:
属性 | 作用 |
---|---|
visible | true:显示图层;false:隐藏图层 |
方法 | 作用 |
---|---|
getVisible() | 获取图层是否隐藏 |
setVisible() | 设置图层是否隐藏 |
js
let map: any;
onMounted(() => {
map = new Map({
target: "map",
layers: [
new TileLayer({
source: new OSM(),
visible: true
})
],
view: new View({
projection: "EPSG:4326",
center: [102.7362, 38.0249],
zoom: 5
})
});
});
function handleClick() {
// 方式一
// const layers = map.getAllLayers();
// const layer = layers[0];
// 方式二
const layers = map.getLayers();
const layer = layers.item(0); // item(0) 是一个方法,用于获取指定索引的地图图层
const visible = layer.getVisible();
layer.setVisible(!visible);
}
图层透明度
openlayers 中控制图层透明度的方式有两种:
属性 | 作用 |
---|---|
opacity | 默认 1,取值范围 [0-1] |
方法 | 作用 |
---|---|
getOpacity() | 获取图层透明度 |
setOpacity() | 设置图层透明度 |
js
let map: any;
onMounted(() => {
map = new Map({
target: "map",
layers: [
new TileLayer({
source: new OSM(),
opacity: 0.7
})
],
view: new View({
projection: "EPSG:4326",
center: [102.7362, 38.0249],
zoom: 5
})
});
});
function handleClick() {
const layers = map.getLayers();
const layer = layers.item(0);
const opacity = layer.getOpacity();
layer.setOpacity(1);
}