1. 程式人生 > >openlayer呼叫GeoServer的WMTS切片快取服務

openlayer呼叫GeoServer的WMTS切片快取服務

openlayer3中提供了呼叫WMTS服務的介面。其主要思想是先構建切片資訊,再傳入服務資訊即可。切片資訊包括切片名、切片大小、切片範圍等。這些切片資訊都可以在GeoServer中Gridsets中找到,按照其中的切片資訊構建相應的請求方法即可。

具體程式碼如下:

完整程式碼如下: 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WMTS</title>
    <link rel="stylesheet" href="https://openlayers.org/en/v4.6.4/css/ol.css" type="text/css">
    <script src="https://openlayers.org/en/v4.6.4/build/ol.js"></script>
</head>
<body>
<div id="map" class="map"></div>
<script>
    //切片名
    var gridNames = ['EPSG:4326:0', 'EPSG:4326:1', 'EPSG:4326:2', 'EPSG:4326:3', 'EPSG:4326:4', 'EPSG:4326:5', 'EPSG:4326:6', 'EPSG:4326:7', 'EPSG:4326:8', 'EPSG:4326:9', 'EPSG:4326:10', 'EPSG:4326:11', 'EPSG:4326:12'];
    //切片大小
    var resolutions = [0.703125, 0.3515625, 0.17578125, 0.087890625, 0.0439453125, 0.02197265625, 0.010986328125, 0.0054931640625, 0.00274658203125, 0.001373291015625, 6.866455078125E-4, 3.4332275390625E-4, 1.71661376953125E-4];
    //設定地圖投影
    var projection = new ol.proj.Projection({
        code: 'EPSG:4326',//投影編碼
        units: 'degrees',
        axisOrientation: 'neu'
    });
    var bounds = [103.62470665055986, 24.648642295015023, 109.58868159389407, 29.215053346774152];

    //地圖
    var map = new ol.Map({
        layers: [
            // osmMap,
            new ol.layer.Tile({
                source: new ol.source.WMTS({
                    //服務地址
                    url: 'http://localhost:8080/geoserver/gwc/service/wmts',
                    layer: 'local:LX_C',
                    //切片集
                    matrixSet: 'My_EPSG:4326',
                    format: 'image/png',
                    projection: projection,
                    //切片資訊
                    tileGrid: new ol.tilegrid.WMTS({
                        tileSize: [256, 256],
                        extent: [-180.0, -90.0, 180.0, 90.0],//範圍
                        origin: [-180.0, 90.0],
                        resolutions: resolutions,
                        matrixIds: gridNames
                    }),
                    //
                    style: 'local:cundaoStyle',
                    wrapX: true
                })
            })
        ],
        target: 'map',
        controls: ol.control.defaults({
            attributionOptions: ({
                collapsible: false
            })
        }),
        view: new ol.View({
            projection: projection
        })
    });
    map.getView().fit(bounds, map.getSize());
</script>
</body>
</html>

從中我們可以看到首先設定了切片名,切片大小等,之後新建一個ol.tilegrid.WMTS,將切片資訊傳入,即可呼叫WMTS地圖服務

效果如下:

如果提前做好切片快取,載入本地切片,如果沒有提前做切片,則在瀏覽過程中生成切片快取,很明顯可以感覺到,做好切片快取載入速度較快