1.加载在线WFS服务

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
<template>
<view>
    <view id="map" ref="rootmap"></view>
    <view style="display: flex;">
        <button @click="moveView">moveView</button>
        <button @click="fitToChengdu">fitToChengdu</button>
    </view>
</view>
</template>
<script module="ol" lang="renderjs">
	import 'ol/ol.css';
	import Map from 'ol/Map';
	import View from 'ol/View';
	import {Vector as VectorLayer,Tile as TileLayer} from 'ol/layer';
	import {Vector as VectorSource,OSM,XYZ} from 'ol/source';
	import {GeoJSON} from 'ol/format';
	import {bbox} from 'ol/loadingstrategy'
	import {Style,Stroke,Circle,Fill} from 'ol/style';
	import {fromLonLat} from 'ol/proj'

	var map = null

	export default {
		name: 'OlWFS',
		data() {
			return {
				
			};
		},
		
		onReady() { 
			
			this.loadMap()

		},
		
		methods:{
			
			loadMap(){
				
				//创建wfs资源
				let wfsVectorSource = new VectorSource({
					format: new GeoJSON(),
					projection: 'EPSG:4326',
					url: '/api/maptest/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=maptest%3Aqunaer_data_final&maxFeatures=500&outputFormat=application%2Fjson',
					strategy: bbox
				});
				let wfsVectorSourcePolygon = new VectorSource({
					format: new GeoJSON(),
					projection: 'EPSG:4326',
					url: '/api/maptest/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=maptest%3Achina_province&maxFeatures=50&outputFormat=application%2Fjson',
					strategy: bbox
				});
				//创建wfs图层,注意需要设置好描边样式,否则不展示效果出来
				let wfsVectorLayer = new VectorLayer({
					source: wfsVectorSource,
					style: new Style({
						image: new Circle({
							radius: 5,
							fill: new Fill({
								color: "#3885ff",
								opacity: 0.5
							})
						}),
						stroke: new Stroke({
							color: 'blue',
							width: 5
						})
					}),
					visible: true
				});
				
				//view设置
				let view = new View({
					// center: fromLonLat([105, 34],'EPSG:3857'),
					center: [105, 34],
					zoom: 5,
					maxZoom: 18,
					minZoom: 5,
					projection: 'EPSG:4326'
				});	
				
				//创建一个map
				map = new Map({
					layers: [
						new TileLayer({
							// source: new OSM() //这个会出现底图
							source: new XYZ({
								url: 'http://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png'
							})
						}),
						wfsVectorLayer
					],
					target: "map",
					view: view
				});
				
				map.on('click', function(evt) {
					console.log("evt:",evt.pixel)
					// displayFeatureInfo(evt.pixel);
					var feature = map.forEachFeatureAtPixel(evt.pixel, function(feature) {
						return feature;
					});
					console.log("feature:",feature)
					if(feature != null){
						console.log("feature getId:",feature.getId())
						console.log("feature getKeys:",feature.getKeys())
						console.log("feature getProperties:",feature.getProperties())
					}
				});
			},
			
			// 向左移动地图
			moveView(){
				var view = map.getView();
				var mapCenter = view.getCenter();
				// 让地图中心的x值增加,即可使得地图向左移动,增加的值根据效果可自由设定
				console.log("mapCenter:",mapCenter)
				mapCenter[0] += 50000;
				view.setCenter(mapCenter);
				map.render();
			},
			
			fitToChengdu() {
				// 让地图最大化完全地显示区域[104, 30.6, 104.12, 30.74]
				map.getView().fit([104, 30.6, 104.12, 30.74], map.getSize());
			},
			
			
		}
	};
</script>

<style>
	#map{
		width: 100%;
		height: 90vh;
	}

	/*隐藏ol的一些自带元素*/
	.ol-attribution,
	.ol-zoom {
		display: none;
	}
</style>

2.点击wfs要素展示数据

==使用map.forEachFeatureAtPixel==

html

1
2
3
4
<div id="popup" class="ol-popup">
    <a href="#" id="popup-closer" class="ol-popup-closer"></a>
    <div id="popup-content"></div>
</div>

js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// 获取到popup的节点
var container = document.getElementById('popup');
var content = document.getElementById('popup-content');
var closer = document.getElementById('popup-closer');

/**
 * Add a click handler to hide the popup.
 * @return {boolean} Don't follow the href.
 */
closer.onclick = function () {
    overlay.setPosition(undefined);
    closer.blur();
    return false;
};

// 创建一个overlay, 绑定html元素container
var overlay = new Overlay(/** @type {olx.OverlayOptions} */ ({
    element: container,
    autoPan: true,
    autoPanAnimation: {
      duration: 250
    }
}));

map.addOverlay(overlay)

//点击要素获得信息
map.on('singleclick', function(evt) {
	// console.log("evt:",evt)
	// displayFeatureInfo(evt.pixel);
	var feature = map.forEachFeatureAtPixel(evt.pixel, function(feature) {
        return feature;
	});
	console.log("feature:",feature)
	if(feature != null){
        // console.log("feature getId:",feature.getId())
        // console.log("feature getKeys:",feature.getKeys())
        // console.log("feature getProperties:",feature.getProperties())
        var prop = feature.getProperties();
        
        if(feature.getId().indexOf("qunaer") != -1){
            content.innerHTML =
            '<h3>' + prop.F_name + '</h3>' + 
            '<p style="margin:10px 0">地址:' + prop.address + '</p>' + 
            '<img src="' + prop.picurl + '" height="150px" />';
        }
        else if(feature.getId().indexOf("province") != -1){
            content.innerHTML =
            '<h2>' + prop.NL_NAME_1 + '</h2>'
        }
        
        // 设置overlay的位置,从而显示在鼠标点击处
        overlay.setPosition(evt.coordinate);
	}
});

css

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
.ol-popup {
    position: absolute;
    background-color: white;
    box-shadow: 0 1px 4px rgba(0,0,0,0.2);
    padding: 15px;
    border-radius: 10px;
    border: 1px solid #cccccc;
    bottom: 12px;
    left: -50px;
    min-width: 250px;
}
.ol-popup:after, .ol-popup:before {
    top: 100%;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
}
.ol-popup:after {
    border-top-color: white;
    border-width: 10px;
    left: 48px;
    margin-left: -10px;
}
.ol-popup:before {
    border-top-color: #cccccc;
    border-width: 11px;
    left: 48px;
    margin-left: -11px;
}
.ol-popup-closer {
    text-decoration: none;
    position: absolute;
    top: 2px;
    right: 8px;
}
.ol-popup-closer:after {
    content: "✖";
}

3.通过wfs修改数据

加载wfs的时候要指定geometryName

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
wfsVectorLayer = new VectorLayer({
    source: new VectorSource({
    format: new GeoJSON({
        // 因为数据源里面字段the_geom存储的是geometry,所以需要指定
        geometryName: 'the_geom' 
    }),
    url: '/api/wfs?service=WFS&version=1.0.0&request=GetFeature&typeName=maptest%3Anyc_roads&outputFormat=application%2Fjson&srsname=EPSG:4326'
	}),
    style: function(feature, resolution) {
        return new Style({
            stroke: new Stroke({
                color: 'red',
                width: 2
            })
        });
	}
});
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// 保存已经编辑的要素
onSave() {
    if (modifiedFeatures && modifiedFeatures.getLength() > 0) {
    	console.log("modifiedFeatures:",modifiedFeatures)
    	// 转换坐标
    	var modifiedFeature = modifiedFeatures.item(0).clone();
    	// 注意ID是必须,通过ID才能找到对应修改的feature
    	modifiedFeature.setId(modifiedFeatures.item(0).getId());
    	// 调换经纬度坐标,以符合wfs协议中经纬度的位置
    	modifiedFeature.getGeometry().applyTransform(function(flatCoordinates, flatCoordinates2, stride) {
            for (var j = 0; j < flatCoordinates.length; j += stride) {
                var y = flatCoordinates[j];
                var x = flatCoordinates[j + 1];
                flatCoordinates[j] = x;
                flatCoordinates[j + 1] = y;
            }
    	});
    	console.log("modifyWfs:",modifiedFeature)
    	this.modifyWfs([modifiedFeature]);
    }
},

// 把修改提交到服务器端
modifyWfs(features) {
    var WFSTSerializer = new WFS();
    var featObject = WFSTSerializer.writeTransaction(null,
    	features, null, {
                featureType: 'nyc_roads', 
                // 注意这个值必须为创建工作区时的命名空间URI   
                featureNS: 'http://maptest/test1',  
                srsName: 'EPSG:4326'
    	});
    // 转换为xml内容发送到服务器端
    var serializer = new XMLSerializer();
    var featString = serializer.serializeToString(featObject);
    console.log("featString:",featString)
    uni.request({
        url: '/api/wfs?service=WFS', 
        method: 'POST',
        data:featString,
        header: {
            // 指定内容为xml类型
            'Content-Type': 'text/xml'
        },
        success: (res) => {
            console.log("success res:",res.data);
        }
    });
}

4.加载WMS 点击wms获得信息

使用**==getFeatureInfoUrl==**

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//加载WMS
var wmsLayer = new TileLayer({
    source: new TileWMS({
        url: "/api/maptest/wms",
        params:{
            'LAYERS': this.wmsSource,
            'TILED': true
        },
        transition: 0  //渲染时不透明度过渡的持续时间。要禁用不透明度转换 transition: 0
    })
});


var view = new View({
	projection: "EPSG:4326",
	// center: [105, 34],
	center: [118.006954,25.101685],
	zoom: 10,
	maxZoom: 18,
	minZoom: 4,

})
var map = new Map({
	// layers: [tileOSM, tileLayer],
	layers: [tileOSM, wmsLayer, wfsVectorLayer],
	view: view,
	target: 'map',
});

//点击wms获得信息
map.on('singleclick', function(evt) {
	// document.getElementById('nodelist').innerHTML = "Loading... please wait...";
	var view = map.getView();
	var viewResolution = view.getResolution();
	var source = wmsLayer.getSource();
	var url = source.getFeatureInfoUrl(
        evt.coordinate, viewResolution, view.getProjection(), {
        'INFO_FORMAT': 'application/json',
        'FEATURE_COUNT': 50
        });
	if (url) {
        // document.getElementById('nodelist').innerHTML = '<iframe seamless src="' + url + '"></iframe>';
        console.log("url:",url)
	}
});