openlayers3地图搭建

最近搭建内网地图用到前端openlayer框架,以杭州萧山经纬度作为示例:

openlayers地图搭建步骤:

1. 开地图服务(这里用的是arcgis做的地图服务)

2. 确定瓦片地图的坐标系,瓦片地图名称(需要和地图服务里的对应),服务位置,比例尺,代码如下

//坐标系
var gridsetName = 'EPSG:4326'
// 瓦片地图的名称,需要和地图服务里的相同
var gridNames = [ 'EPSG:4326:11', 'EPSG:4326:12', 'EPSG:4326:13','EPSG:4326:14', 'EPSG:4326:15', 'EPSG:4326:16', 'EPSG:4326:17' ]
// 地图服务url,当初用的是wms,这次改用了wmts,写法不太一样,导致开始搭建不起来
var baseUrl = 'http://127.0.0.1:8090/geoserver/gwc/service/wmts'
var style = ''
var format = 'image/png'
var layerName = 'hz_xs:hz_xs'
var projection = new ol.proj.Projection({
	code : 'EPSG:4326',
	units : 'degrees',
	axisOrientation : 'neu'
})
// 比例尺数组,这个跟arcgis切图出来的比例尺要匹配
var resolutions=
[0.0003433227539062,0.0001716613769531,0.0000858306884766,0.0000429153442383,0.0000214576721191,0.0000107288360596, 0.0000053644180298 ]
var baseParams = [ 'VERSION', 'LAYER', 'STYLE', 'TILEMATRIX','TILEMATRIXSET', 'SERVICE', 'FORMAT' ]
var params = {
	'VERSION' : '1.0.0',
	'LAYER' : layerName,
	'STYLE' : style,
	'TILEMATRIX' : gridNames,
	'TILEMATRIXSET' : gridsetName,
	'SERVICE' : 'WMTS',
	'FORMAT' : format
}
var url = baseUrl + '?'
for ( var param in params) {
	if (baseParams.indexOf(param.toUpperCase()) < 0) {
		url = url + param + '=' + params[param] + '&'
	}
}
url = url.slice(0, -1)
var source = new ol.source.WMTS({
	url : url,
	layer : params['LAYER'],
	matrixSet : params['TILEMATRIXSET'],
	format : params['FORMAT'],
	projection : projection,
	tileGrid : new ol.tilegrid.WMTS({
		tileSize : [ 256, 256 ],
		extent : [ -180.0, -90.0, 180, 90 ],
		origin : [ -180, 90 ],
		resolutions : resolutions,
		matrixIds : params['TILEMATRIX']
	}),
	style : params['STYLE'],
	wrapX : true
})
var layer = new ol.layer.Tile({
	source : source
})

3. 添加地图视图、图层、控件等,代码如下

var view = new ol.View({
	center : [120.32245,30.32021 ],
	projection : projection,
	zoom : 10,
	minZoom : 10,
	maxZoom : 16
})
// 动态矢量层,点、线都绘制到该图层
var vectorSource = new ol.source.Vector({
	projection : 'EPSG:4326',
	format : new ol.format.GeoJSON({
		extractStyles : false
	})
})
var styleFunction = function(feature) {
	return styles[feature.getGeometry().getType()]
}
var vectorLayer = new ol.layer.Vector({
	source : vectorSource,
	style : styleFunction
})
// 加一个Logo
var logoElement = document.createElement('a')
var logoImage = document.createElement('img')
logoImage.src = './openlayers/images/logo.png'
logoElement.appendChild(logoImage)
var map = new ol.Map({
	controls : ol.control.defaults({attribution : false}).extend([ 
                new ol.control.ScaleLine({units : 'metric'}), 
		new ol.control.Attribution({collapsible : true}), 
		new ol.control.ZoomSlider()
	]),
	layers : [ layer, vectorLayer ],
	target : 'map',
	view : view,
	logo : logoElement
})
// 地图初始时显示比例,包含左上和右下的点
map.getView().fit([120.0608254790039,30.35848617553711,120.40140151977539,30.17343521118164], map.getSize())

转载自:https://blog.csdn.net/z874889608/article/details/79420247

You may also like...