---
title: "Openlayer 加载Echarts省市轮廓，XYZ方式加载TMS瓦片底图"
author: "bnmnba"
date: "2018-08-23T18:10:24Z"
tags: []
categories: ["开源软件"]
slug: "openlayer-echarts-xyz-tms"
draft: false
lastmod: "2018-08-23T18:11:50Z"
id: 2429248
url: "https://bnmnba.iteye.com/blog/2429248"
---

首先说明几个概念。

GIS：地理信息系统（Geographic Information System)、Geo、地图、地理系统。

坐标系：XY、坐标参考系、crs（coordinate reference system）、坐标参考系、把地球放到坐标系里才能做成数字地图，通常分为球形和投影平面；

常见坐标系：WGS84地理坐标系（地理学和谷歌地球）、WGS84 web 墨卡托投影坐标系（国外地图常用）、GCJ02（国内地图常用）、BD09（百度自定义坐标系）、CGCS2000（基于高斯2000坐标系）

坐标：通常有两个数值组成的数值、coordinate、\[116, 38]、只知道坐标不知道坐标系无法使用。

投影：projection、把球形坐标系按照一个算法，把每一个点投射到二维平面XY坐标系的方法叫做投影算法。EPSG：Coordinate Systems Worldwide、世界地理坐标系标准组织。

wgs84：球形坐标系、地理坐标系、经纬度坐标、World Geodetic System 1984 、单位是度、EPSG:4326、

lonlat（lon经度、lat维度）

wgs84 墨卡托投影坐标系：Mercator Projection 、把wgs84经纬度坐标按照墨卡托投影得到的平面投影坐标系、EPSG:3857、EPSG:900913、Google Maps Projection, OpenStreetMap, Bing都是用这个投影、https://epsg.io/3857、单位是米

GCJ02：中国国测局制定的坐标系、火星坐标。

CGCS2000：国家大地2000坐标系、EPSG:1024。

瓦片：Tile、包括TMS瓦片、MBTitles、使用很多小图片来表示地图的层级；瓦片使用的是墨卡托投影坐标系（EPSG:3857）

层级：瓦片分为22个层级，每深入一层，图片数量增加四倍。

图层：layer、一个地图分为很多图层，包括矢量图层和影像图层（通常称为底图），两个图层叠加可以表示丰富的信息，两个影像图层叠加前需要确认是互相覆盖还是背景透明。

特征：矢量图层里有很多特征Feature，每个特征是一个形状（点Point、线Line、多边形Polygon），特征的根据坐标决定的。

样式：每个特征有对应的绘制样式Style，例如边框Stroke、填充Fill、圈Circle等等。

GeoJSON ：使用JSON格式带说明一个特征集合FeatureCollection，使用的的是WGS84地理坐标系。

TopoJSON：是扩展的GeoJSON。

坐标统一：所有数据包括矢量、影像、特征、GEOJSON都要自动或手动转换为同一个坐标系才能显示无偏移。

偏移：包括水平偏移、旋转偏移、缩放偏移。

openlay:一个把切片加载到web项目里的前端工具包，功能强大。

leaflet：比openlayer更小巧。

 

 

openlayer v4.6.5 + echarts 河南地图json的展示示例：

 

```
<!doctype html>
<html lang="cn">
  <head>
    <link rel="stylesheet" href="js/openlayer/v4.6.5/css/ol.css" type="text/css">
    <style>
      .map {
        height: 400px;
        width: 100%;
      }
    </style>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<script type="text/javascript" src="js/jQuery1.3.1.js"></script>
    <script type="text/javascript" src="js/openlayer/v4.6.5/build/ol.js"></script>
	<script type="text/javascript" src="js/coordtransform.js"></script>
	<script type="text/javascript" src="js/cm.js"></script>
  </head>
  <body>
    <div id="map" class="map"></div>
    <script type="text/javascript">

    
      var image = new ol.style.Circle({
        radius: 5,
        fill: null,
        stroke: new ol.style.Stroke({color: 'red', width: 1})
      });


      var styles = {
 		'station_1': new ol.style.Style({
 	          image: new ol.style.Circle({
 	            radius: 3,
 	            fill: null,
 	            stroke: new ol.style.Stroke({color: '#bada55', width: 1})
 	          })
 	        }),
 	    'station_2': new ol.style.Style({
 	          image: new ol.style.Circle({
 	            radius: 6,
 	            fill: null,
 	            stroke: new ol.style.Stroke({color: '#bada55', width: 1})
 	          })
 	        }),
 	 	    'station_3': new ol.style.Style({
 	 	          image: new ol.style.Circle({
 	 	            radius: 9,
 	 	            fill: null,
 	 	            stroke: new ol.style.Stroke({color: '#bada55', width: 1})
 	 	          })
 	 	        }),
	 	 	    'station_4': new ol.style.Style({
	  	          image: new ol.style.Circle({
	  	            radius: 12,
	  	            fill: null,
	  	            stroke: new ol.style.Stroke({color: '#bada55', width: 1})
	  	          })
	  	        }),
	  	 	    'station_5': new ol.style.Style({
	   	          image: new ol.style.Circle({
	   	            radius: 15,
	   	            fill: null,
	   	            stroke: new ol.style.Stroke({color: '#bada55', width: 1})
	   	          })
	   	        }),
        'Point': new ol.style.Style({
          image: image
        }),
        'LineString': new ol.style.Style({
          stroke: new ol.style.Stroke({
            color: 'green',
            width: 1
          })
        }),
        'MultiLineString': new ol.style.Style({
          stroke: new ol.style.Stroke({
            color: 'green',
            width: 1
          })
        }),
        'MultiPoint': new ol.style.Style({
          image: image
        }),
        'MultiPolygon': new ol.style.Style({
          stroke: new ol.style.Stroke({
            color: 'yellow',
            width: 1
          }),
          fill: new ol.style.Fill({
            color: 'rgba(255, 255, 0, 0.1)'
          })
        }),
        'Polygon': new ol.style.Style({
          stroke: new ol.style.Stroke({
            color: 'blue',
            lineDash: [4],
            width: 3
          }),
          fill: new ol.style.Fill({
            color: 'rgba(0, 0, 255, 0.1)'
          })
        }),
        'GeometryCollection': new ol.style.Style({
          stroke: new ol.style.Stroke({
            color: 'magenta',
            width: 2
          }),
          fill: new ol.style.Fill({
            color: 'magenta'
          }),
          image: new ol.style.Circle({
            radius: 10,
            fill: null,
            stroke: new ol.style.Stroke({
              color: 'magenta'
            })
          })
        }),
        'Circle': new ol.style.Style({
          stroke: new ol.style.Stroke({
            color: 'red',
            width: 2
          }),
          fill: new ol.style.Fill({
            color: 'rgba(255,0,0,0.2)'
          })
        })
      };

      var styleFunction = function(feature) {
          	return styles[feature.getGeometry().getType()];
          	
        };
		//fs.concat(new SGGTool(211,false,[{lon:12645670.400179092,lat:4137598.634327903}]).getFeatures())
        var geojsonObject = {
          'type': 'FeatureCollection',
          'crs': {
            'type': 'name',
            'properties': {
              'name': 'EPSG:900913'
            }
          },
          'features': 
           [{
            'type': 'Feature',
            'geometry': {
              'type': 'Point',
              'coordinates': [0, 0]
            }
          }, {
            'type': 'Feature',
            'geometry': {
              'type': 'LineString',
              'coordinates': [[4e6, -2e6], [8e6, 2e6]]
            }
          }, {
            'type': 'Feature',
            'geometry': {
              'type': 'LineString',
              'coordinates': [[4e6, 2e6], [8e6, -2e6]]
            }
          }, {
            'type': 'Feature',
            'geometry': {
              'type': 'Polygon',
              'coordinates': [[[-5e6, -1e6], [-4e6, 1e6], [-3e6, -1e6]]]
            }
          }, {
            'type': 'Feature',
            'geometry': {
              'type': 'MultiLineString',
              'coordinates': [
                [[-1e6, -7.5e5], [-1e6, 7.5e5]],
                [[1e6, -7.5e5], [1e6, 7.5e5]],
                [[-7.5e5, -1e6], [7.5e5, -1e6]],
                [[-7.5e5, 1e6], [7.5e5, 1e6]]
              ]
            }
          }, {
            'type': 'Feature',
            'geometry': {
              'type': 'MultiPolygon',
              'coordinates': [
                [[[-5e6, 6e6], [-5e6, 8e6], [-3e6, 8e6], [-3e6, 6e6]]],
                [[[-2e6, 6e6], [-2e6, 8e6], [0, 8e6], [0, 6e6]]],
                [[[1e6, 6e6], [1e6, 8e6], [3e6, 8e6], [3e6, 6e6]]]
              ]
            }
          },  {
            'type': 'Feature',
            'geometry': {
              'type': 'GeometryCollection',
              'geometries': [{
                'type': 'LineString',
                'coordinates': [[-5e6, -5e6], [0, -5e6]]
              }, {
                'type': 'Point',
                'coordinates': [4e6, -5e6]
              }, {
                'type': 'Polygon',
                'coordinates': [[[1e6, -6e6], [2e6, -4e6], [3e6, -6e6]]]
              }]
            }
          }]
          
          
          
        };

        //var sgt=new SGGTool(202,false,[{lon:12645670.400179092,lat:4137598.634327903}]).getFeature();
        
        var vectorSource = new ol.source.Vector({
          features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
          //features: new SGGTool(202,false,[{lon:12645670.400179092,lat:4137598.634327903}]).getFeatures()
        });

        //vectorSource.addFeature(new ol.Feature(new ol.geom.Circle([5e6, 7e6], 1e6)));
        
        var vectorLayer = new ol.layer.Vector({
            source: vectorSource,
            style: styleFunction
          });

    var map = new ol.Map({
       target: 'map',
       layers: [
         new ol.layer.Tile({
           source: new ol.source.XYZ({
             url: 'henanArcgisTitle/{z}/{x}/{-y}.png'
           })
         })
         
       ],
       view: new ol.View({
          center: [12284632, 3682763],
          zoom: 3
       }),
       projection: ol.proj.get('EPSG:900913'),
       
    });
    
    map.addControl(new ol.control.MousePosition());
    

    map.addLayer(vectorLayer);
    /* var styleFunction = function(feature) {
      return styles[feature.getGeometry().getType()];
    }; */

    //$.getJSON('mapJson/henan.json', function (json) {
    $.getJSON('mapJson/henan.json', function (json) {   
        var vectorSource = new ol.source.Vector();
        vectorSource.addFeatures(new ol.format.GeoJSON().readFeatures(decode(json), {featureProjection: ol.proj.get('EPSG:900913')}));
        // vectorSource.addFeature(new ol.Feature(new ol.geom.Circle([5e6, 7e6], 1e6)));

        var vectorLayer = new ol.layer.Vector({
          source: vectorSource
          //,style: styleFunction
        });
        
        map.addLayer(vectorLayer);
    });
    
    
    
    </script>
  </body>
</html>
```

 

 

参考：

https://openlayers.org