.map { width: 1000px; height: 600px;}
.mapcontainer { position: relative;}
/* 地图缩放组件样式, 可使用top left两个属性定位 */.map .ol-zoom { top: 178px; left: 158px;}
/* 地图旋转组件样式, 可使用top right两个属性定位 */.map .ol-rotate { top: 178px; right: 58px;}
/* 版权信息样式, 可使用display: none; 来隐藏 */.map .ol-attribution,.map .ol-attribution.ol-uncollapsible { bottom: 30px; right: 50px;}
.padding-top { position: absolute; top: 0; left: 0px; width: 1000px; height: 170px; background: rgba(255, 255, 255, 0.5);}
.padding-left { position: absolute; top: 170px; left: 0; width: 150px; height: 400px; background: rgba(255, 255, 255, 0.5);}
.padding-right { position: absolute; top: 170px; left: 950px; width: 50px; height: 400px; background: rgba(255, 255, 255, 0.5);}
.padding-bottom { position: absolute; top: 570px; left: 0px; width: 1000px; height: 30px; background: rgba(255, 255, 255, 0.5);}
.center { position: absolute; border: solid 1px black; top: 490px; left: 560px; width: 20px; height: 20px;}
button { font-size: 18px; margin: 10px 5px; padding: 10px;}Advanced View Positioning 高级视图定位
以最佳比例缩放到瑞士 以最小分辨率缩放到洛桑 将洛桑放置到中心// 加载geojson文件,创建资源对象const source = new ol.source.Vector({ url: 'https://openlayers.org/en/latest/examples/data/geojson/switzerland.geojson', format: new ol.format.GeoJSON(),});// 创建样式对象const style = new ol.style.Style({ // 填充样式 fill: new ol.style.Fill({color: 'rgba(255, 255, 255, 0.6)', }), // 边框样式 stroke: new ol.style.Stroke({color: '#319FD3',width: 1, }), // 图片样式,此处代表点的样式,以圆Circle呈现 image: new ol.style.Circle({radius: 5,fill: new ol.style.Fill({ color: 'rgba(255, 255, 255, 0.6)',}),stroke: new ol.style.Stroke({ color: '#319FD3', width: 1,}), }),});// 创建矢量图层const vectorLayer = new ol.layer.Vector({ source: source, style: style,});// 创建视图const view = new ol.View({ center: [0, 0], zoom: 1,});// 地图初始化const map = new ol.Map({ // 设置图层 layers: [// OSM底图new ol.layer.Tile({ source: new ol.source.OSM(),}),// 刚创建的矢量图层vectorLayer, ], // 绑定页面元素 target: 'map', // 设置视图 view: view,});
// 绑定按钮点击事件// 以最佳比例缩放到瑞士const zoomtoswitzerland = document.getElementById('zoomtoswitzerland');zoomtoswitzerland.addEventListener( 'click', function () {// 获取瑞士多边形polygon对象const feature = source.getFeatures()[0];const polygon = feature.getGeometry();// 最佳比例缩放到瑞士view.fit(polygon, { padding: [170, 50, 30, 150] }); }, false);
// 以最小分辨率缩放到洛桑const zoomtolausanne = document.getElementById('zoomtolausanne');zoomtolausanne.addEventListener( 'click', function () {// 获取洛桑点位point对象const feature = source.getFeatures()[1];const point = feature.getGeometry();// 以50分辨率缩放到洛桑view.fit(point, { padding: [170, 50, 30, 150], minResolution: 50 }); }, false);
// 将洛桑放置到中心const centerlausanne = document.getElementById('centerlausanne');centerlausanne.addEventListener( 'click', function () {// 获取洛桑点位point对象const feature = source.getFeatures()[1];const point = feature.getGeometry();// 获取地图尺寸const size = map.getSize();// 将洛桑点位放置到地图[570, 500]位置view.centerOn(point.getCoordinates(), size, [570, 500]); }, false);