OL中通过tileUrlFunction实现多底图加载

2021-12-06 10:35:38 浏览数 (3)

概述

业务发展好了,肯定会有一些国际业务,会用到全球底图,但是又想国内的又想用国内的,本文就结合openlayers中的tileUrlFunction加以简单实现。

效果

实现代码

代码语言:javascript复制
const tile = new ol.layer.Tile({
  visible: true,
  source: new ol.source.XYZ({
    tileUrlFunction(zxy, pixelRatio, proj) {
      const [z, x, y] = zxy
      let url  = isInChina(zxy) ? TILEURL.NAV : TILEURL.OSM
      url = url.split('{z}').join(z)
      url = url.split('{x}').join(x)
      url = url.split('{y}').join(y)
      return url
    }
  })
});

完整代码如下:

代码语言:javascript复制
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>OpenLayers map preview</title>
  <link rel="stylesheet" href="lib/ol/ol.css" type="text/css">
  <script src="lib/ol/ol.js" type="text/javascript"></script>
<style>
html,
body,
.map {
  height: 100%;
  margin: 0; }
</style>
</head>
<body>
<div id="map" class="map"></div>
<script>
const options = {
  tileUrl: TILEURL.NAV,
  center: [105.943468, 38.08155],
  zoom: 4.5,
  minZoom: 0,
  maxZoom: 18
}
const TILEURL = {
  'NAV': 'http://webrd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=8',
  'OSM': 'https://tile.openstreetmap.org/{z}/{x}/{y}.png'
}

function isInChina(zxy) {
  const [z, x, y] = zxy
  const tileExtent = getExtentFromZxy(z,x,y)
  const chinaExtent = [72.69154385120196, 2.1456019648604325, 136.8205912282765, 54.22089456253397]
  return ol.extent.intersects(tileExtent, chinaExtent)
}

const base = new ol.layer.Tile({
  visible: true,
  source: new ol.source.XYZ({
    tileUrlFunction(zxy, pixelRatio, proj) {
      const [z, x, y] = zxy
      let url  = isInChina(zxy) ? TILEURL.NAV : TILEURL.OSM
      url = url.split('{z}').join(z)
      url = url.split('{x}').join(x)
      url = url.split('{y}').join(y)
      return url
    }
  })
});

window.map = new ol.Map({
  controls: ol.control.defaults({
    attribution: false
  }).extend([]),
  target: 'map',
  layers: [base],
  view: new ol.View({
    center: ol.proj.fromLonLat(options.center),
    zoom: options.zoom,
    minZoom: options.minZoom,
    maxZoom: options.maxZoom
  })
});
</script>
</body>
</html>

0 人点赞