Skip to content

Reusable 数据源 ​

Reusable 数据源示例。

你可以调用 source.setUrl() 来更新瓦片数据源的 URL。注意,更改瓦片数据源的 URL 时,已有的瓦片会保留,直到新瓦片加载完成才会被替换。如果你想直接清除当前已渲染的瓦片,可以调用 source.refresh() 方法。另外,如果你想移除已渲染的瓦片并重新加载新瓦片,也可以使用两个独立的数据源。

main.js
js
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import TileLayer from 'ol/layer/WebGLTile.js';
import ImageTile from 'ol/source/ImageTile.js';

const key = 'Your Mapbox access token from https://mapbox.com/ here';
const baseUrl = 'https://{a-c}.tiles.mapbox.com/v4';
const urls = [
  baseUrl + '/mapbox.blue-marble-topo-jan/{z}/{x}/{y}.png?access_token=' + key,
  baseUrl +
    '/mapbox.blue-marble-topo-bathy-jan/{z}/{x}/{y}.png?access_token=' +
    key,
  baseUrl + '/mapbox.blue-marble-topo-jul/{z}/{x}/{y}.png?access_token=' + key,
  baseUrl +
    '/mapbox.blue-marble-topo-bathy-jul/{z}/{x}/{y}.png?access_token=' +
    key,
];

const source = new ImageTile();

const map = new Map({
  target: 'map',
  layers: [
    new TileLayer({
      source: source,
    }),
  ],
  view: new View({
    center: [0, 0],
    zoom: 2,
  }),
});

function updateUrl(index) {
  source.setUrl(urls[index]);
}

const buttons = document.getElementsByClassName('switcher');
for (let i = 0, ii = buttons.length; i < ii; ++i) {
  const button = buttons[i];
  button.addEventListener('click', updateUrl.bind(null, Number(button.value)));
}

updateUrl(0);
index.html
html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>可复用数据源</title>
    <link rel="stylesheet" href="node_modules/ol/ol.css">
    <style>
      .map {
        width: 100%;
        height: 400px;
      }
    </style>
  </head>
  <body>
    <div id="map" class="map"></div>
    <button class="switcher" value="0">一月</button>
    <button class="switcher" value="1">一月(含测深数据)</button>
    <button class="switcher" value="2">七月</button>
    <button class="switcher" value="3">七月(含测深数据)</button>

    <script type="module" src="main.js"></script>
  </body>
</html>
package.json
json
{
  "name": "reusable-source",
  "dependencies": {
    "ol": "10.11.0"
  },
  "devDependencies": {
    "vite": "^8.1.5"
  },
  "scripts": {
    "start": "vite",
    "build": "vite build"
  }
}