1. 程式人生 > >OpenLayers官方示例詳解十四之可重用地圖源(Reusable Source)

OpenLayers官方示例詳解十四之可重用地圖源(Reusable Source)

目錄

一、示例簡介

二、程式碼詳解


一、示例簡介

    這個示例展示如何更新地圖中的瓦片。

    可以呼叫source.setUrl()來更新瓦片地圖源的URL,請注意,當更改瓦片地圖源的URL時,在載入完新的瓦片之前,將不會替換現有的瓦片。

    如果想要清除當前呈現的瓦片,則可以呼叫source.refresh()方法。

二、程式碼詳解

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Reusable Source</title>
    <link href="ol_v5.0.0/css/ol.css" rel="stylesheet" type="text/css" />
    <script src="ol_v5.0.0/build/ol.js" type="text/javascript"></script>
</head>
<body>
    <div id="map"></div>
    <button class="switcher" value="0">January</button>
    <button class="switcher" value="1">January (with bathymetry)</button>
    <button class="switcher" value="2">July</button>
    <button class="switcher" value="3">July (With bathymetry)</button>

    <script>
        // 有mapbox瓦片地圖url組成的陣列
        var urls = [
            'https://{a-c}.tiles.mapbox.com/v3/mapbox.blue-marble-topo-jan/{z}/{x}/{y}.png',
            'https://{a-c}.tiles.mapbox.com/v3/mapbox.blue-marble-topo-bathy-jan/{z}/{x}/{y}.png',
            'https://{a-c}.tiles.mapbox.com/v3/mapbox.blue-marble-topo-jul/{z}/{x}/{y}.png',
            'https://{a-c}.tiles.mapbox.com/v3/mapbox.blue-marble-topo-bathy-jul/{z}/{x}/{y}.png'
        ];

        // 瓦片地圖源
        var source = new ol.source.XYZ();

        var map = new ol.Map({
            target: 'map',
            layers: [
                new ol.layer.Tile({
                    source: source
                })
            ],
            view: new ol.View({
                center: [0, 0],
                zoom: 2
            })
        });

        function updateUrl(index){
            source.setUrl(urls[index]);     // 改變瓦片地圖源的url
        }

        var buttons = document.getElementsByClassName('switcher');  
        for(var i = 0, len = buttons.length; i < len; i++){
            var button = buttons[i];
            // 讓瓦片地圖的url隨使用者點選按鈕而變化
            button.addEventListener('click', updateUrl.bind(null, Number(button.value)));
        }

        updateUrl(0);       // 先預設定瓦片地圖
    </script>
</body>
</html>