Openlayer加载GeoServer发布的WTMS

CDN

1
2
<link rel="stylesheet" href="https://openlayers.org/en/v3.20.1/css/ol.css" type="text/css">
<script src="https://openlayers.org/en/v3.20.1/build/ol.js" type="text/javascript"></script>
1. 点击Logo -》版本号 -》查看自己的wms地址


2. 查看WTMS,右键查看源码

3. 将所有script标签中的代码复制下来,删除红框,添加绿框

4.修改baseUrl
1
var baseUrl = 'http://localhost:8089/geoserver/gwc/service/wmts';

完整代码 注意:script要放在html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="https://openlayers.org/en/v3.20.1/css/ol.css" type="text/css">
<script src="https://openlayers.org/en/v3.20.1/build/ol.js" type="text/javascript"></script>

</head>

<body>
<h2>WTMS</h2>
<div id="map"></div>
</body>
<script src="js/test.js"></script>

</html>

test.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
function init() {
var gridsetName = 'landsat_zdy';
var gridNames = ['landsat_zdy:0', 'landsat_zdy:1', 'landsat_zdy:2', 'landsat_zdy:3', 'landsat_zdy:4', 'landsat_zdy:5'];
var baseUrl = 'http://localhost:8089/geoserver/gwc/service/wmts';
var style = '';
var format = 'image/png';
var infoFormat = 'text/html';
var layerName = 'webgis_test:LC08_L1TP_123033_20170523_20170526_01_T1_B1';
var projection = new ol.proj.Projection({
code: 'EPSG:32650',
units: 'm',
axisOrientation: 'neu'
});
var resolutions = [2609.2074758118906, 1304.6037379059453, 652.3018689529727, 326.1509344764863, 163.07546723824316, 81.53773361912158];
baseParams = ['VERSION', 'LAYER', 'STYLE', 'TILEMATRIX', 'TILEMATRIXSET', 'SERVICE', 'FORMAT'];

params = {
'VERSION': '1.0.0',
'LAYER': layerName,
'STYLE': style,
'TILEMATRIX': gridNames,
'TILEMATRIXSET': gridsetName,
'SERVICE': 'WMTS',
'FORMAT': format
};
// 构建layer的source
function constructSource() {
var url = baseUrl + '?'
for (var param in params) {
if (baseParams.indexOf(param.toUpperCase()) < 0) {
url = url + param + '=' + params[param] + '&';
}
}
url = url.slice(0, -1);

var source = new ol.source.WMTS({
url: url,
layer: params['LAYER'],
matrixSet: params['TILEMATRIXSET'],
format: params['FORMAT'],
projection: projection,
tileGrid: new ol.tilegrid.WMTS({
tileSize: [256, 256],
extent: [166021.44309607794, 0.0, 833978.556903922, 9351399.593309816],
origin: [166021.44309607794, 9351399.593309816],
resolutions: resolutions,
matrixIds: params['TILEMATRIX']
}),
style: params['STYLE'],
wrapX: true
});
return source;
}

var layer = new ol.layer.Tile({
source: constructSource()
});

var view = new ol.View({
center: [0, 0],
zoom: 2,
projection: projection,
extent: [166021.44309607794, 0.0, 833978.556903922, 9351399.593309816]
});

var map = new ol.Map({
layers: [layer],
target: 'map',
view: view
});
map.getView().fit([320685.0, 4187385.0, 553515.0, 4424415.0], map.getSize());
}
init();

结果