openlayers加载本地离线地图瓦片 (五)

1. 准备工作

准备好openlayers的js、css文件和上篇文章下载的上海地图瓦片(格式为谷歌XYZ)。新建一个html文件,我的目录是这样的:
在这里插入图片描述

2. 引用文件

<link rel="stylesheet" href="./static/ol.css">
<script src="./static/ol.js"></script>

3. 添加容器

<div id="map"></div>

4. 创建地图

var map = new ol.Map({
 view: new ol.View({
    center: [121.5025,31.237015], // 中心点, 填的是经纬度
    projection: 'EPSG:4326',  // EPSG:4326格式的经纬度
    zoom: 14, // 地图默认缩放级别
    maxZoom: 15,  // 地图最大缩放级别
    minZoom: 11,  // 地图最小缩放级别
  }),
  target: 'map', // 地图容器id
})

5. 创建一个使用离线地图瓦片的层

var offlineMapLayer = new ol.layer.Tile({
  source: new ol.source.XYZ({
   url: './tiles/{z}/{x}/{y}.png',
  })
});

6. 将层添加进地图

map.addLayer(offlineMapLayer);

7. 地图就展示出来啦~

在这里插入图片描述

8. 完整代码

<!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>demo</title>
  <link rel="stylesheet" href="./static/ol.css">
  <script src="./static/ol.js"></script>
</head>
<body>
  <div id="map"></div>
  <script type="text/javascript">

    // 创建地图
    var map = new ol.Map({
      view: new ol.View({
        center: [121.5025,31.237015], // 中心点, 填的是经纬度
        projection: 'EPSG:4326',  // EPSG:4326格式的经纬度
        zoom: 14, // 地图默认缩放级别
        maxZoom: 15,  // 地图最大缩放级别
        minZoom: 11,  // 地图最小缩放级别
      }),
      target: 'map', // 地图容器id
    })

    // 创建一个使用离线地图瓦片的层
	var offlineMapLayer = new ol.layer.Tile({
		source: new ol.source.XYZ({
        	url: './tiles/{z}/{x}/{y}.png',
		})
    });
    
    // 将层添加进地图
    map.addLayer(offlineMapLayer);
  </script>
</body>
</html>

如果地图瓦片是TMS格式,创建一个使用离线地图瓦片的层里面代码需要改一下,如下

var offlineMapLayer = new ol.layer.Tile({
	source: new ol.source.XYZ({
		tileUrlFunction: function(tileCoord) {
			var z = tileCoord[0];
			var x = tileCoord[1];
			var y = Math.pow(2, z) + tileCoord[2];
			return './tiles/' + z + '/' + x + '/' + y + '.png'
		},
	})
});

9. 补充

这里补充一下,demo中new View的时候我使用了projection: ‘EPSG:4326’
在我不断的体验之后,不推荐这样使用,因为后面会面临各种莫名其妙的问题,建议还是使用EPSG:3857。
牢记一句话,经纬度存储计算用EPSG:4326也就是WGS84,数据展示用EPSG:3857。
2个格式的数据怎么互转呢?

  1. 可以通过ol/proj/transform这个方法
    例: transform([121.501842, 31.239204], ‘EPSG:4326’, ‘EPSG:3857’),
  2. 使用gcoord这个库
    npm install gcoord --save
    
    import gcoord from 'gcoord'
    const xy = gcoord.transform(
       [经度, 纬度],
       gcoord.EPSG4326,
       gcoord.EPSG3857
     )
    

猜你喜欢

转载自blog.csdn.net/m0_37797410/article/details/105414258