概述
写一篇水文,讲讲如果在openlayers中实现不同的区域加载不同的底图。
效果
实现
通过tileUrlFunction
实现不同切片地址的请求。
<!DOCTYPE html>
<html><head><title>XYZ</title><link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css"><!-- The line below is only needed for old environments like Internet Explorer and Android 4.x --><script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script><script src="https://openlayers.org/en/v4.6.5/build/ol.js"></script><style>html, body, #map {height: 100%;margin: 0;padding: 0;overflow: hidden;}</style></head><body><div id="map" class="map"></div><script>function isTileInExtent(z, x, y) {const [xmin, ymin, xmax, ymax] = ol.proj.transformExtent([73.502355,3.397162,135.09567,53.563269], 'EPSG:4326', 'EPSG:3857')const val = 20037508.34const res = (val * 2 / Math.pow(2, z))const [_xTileMin, _xTileMax, _yTileMin, _yTileMax] = [-val + x * res, -val + (x + 1) * res,val - (y + 1) * res, val - y * res]return _xTileMin >= xmin && _xTileMin <= xmax && _yTileMin >= ymin && _yTileMin <= ymax|| _xTileMax >= xmin && _xTileMax <= xmax && _yTileMin >= ymin && _yTileMin <= ymax|| _xTileMin >= xmin && _xTileMin <= xmax && _yTileMax >= ymin && _yTileMax <= ymax|| _xTileMax >= xmin && _xTileMax <= xmax && _yTileMax >= ymin && _yTileMax <= ymax}var map = new ol.Map({target: 'map',layers: [new ol.layer.Tile({source: new ol.source.XYZ({tileUrlFunction([z, x, y]) {const isIn = isTileInExtent(z, x, -y)return isIn ?`https://webrd02.is.autonavi.com/appmaptile?style=8&x=${x}&y=${-y}&z=${z}&lang=zh_cn&size=1&scale=1` :`https://gac-geo.googlecnapps.cn/maps/vt?lyrs=m&x=${x}&y=${-y}&z=${z}`}})})],view: new ol.View({center: [12793318.711518219, 5336814.9902110305],zoom: 4,minZoom: 3})});</script></body>
</html>