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

Posted 牛老师讲GIS

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了OL中通过tileUrlFunction实现多底图加载相关的知识,希望对你有一定的参考价值。

概述

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

效果

实现代码

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
    
  )
);

完整代码如下:

<!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>

以上是关于OL中通过tileUrlFunction实现多底图加载的主要内容,如果未能解决你的问题,请参考以下文章

ol 6中新的内部瓦片坐标和自定义瓦片网格的WMS层

openlayers6 mapserver加载地图底图

React中通过地图函数传递道具

笔记:openlayers调用天地图做底图并叠加geoserver发布的图层

在 ol 6.4 中使用 WFS 层

Geoserver2.11矢量切片与OL3中的调用展示