提示:openlayers仅在h5端有效,在app端无效
一、设置地图div
<div id="map" class="map" tabindex="0"></div>
注意:map需要设置高度
二、使用步骤
需要在官网下载openlayers
npm install ol
1.引入库
代码如下(示例):
import Map from 'ol/Map';
import OSM from 'ol/source/OSM';
import TileLayer from 'ol/layer/Tile';
import View from 'ol/View';
import TileWMS from 'ol/source/TileWMS';
//地图初始化
initMap() {
helper.map = new Map({
layers: [
new TileLayer({
source: new OSM(),
}),
],
target: 'map',
view: new View({
center: [111.47, 27.24], //定义地图的经度和纬度
projection: 'EPSG:4326',
zoom: 12, //定义地图显示的层级
maxZoom: 30 //最大缩放
}),
});
helper.map.once('postrender', function(event) { //地图加载完成
});
},
//地图加上图层
initdataLayers() {
this.dataLayers = [{
url: "http://192.168.1.246:8080/geoserver/psxt/wms?service=WMS",
layer: "psxt:ps_pumpstation"
},
{
url: "http://192.168.1.246:8080/geoserver/psxt/wms?service=WMS",
layer: "psxt:ps_pipe"
}
];
},
//添加图层
addDataLayers: function() {
for (var i = 0; i < this.dataLayers.length; i++) {
var layerObj = this.dataLayers[i];
var vectorLayer = new TileLayer({
//extent: extent,
source: new TileWMS({
url: layerObj.url,
matrixSet: 'EPSG:4326',
params: {
'LAYERS': layerObj.layer,
'TILED': true
},
serverType: 'geoserver',
transition: 0,
}),
});
// mapApp.dataVectorLayers.push(vectorLayer);
helper.map.addLayer(vectorLayer);
}
},
2.点击定位
引入:
import GeoJSON from 'ol/format/GeoJSON';
import Proj from "ol/proj";
import {OSM, Vector as VectorSource} from 'ol/source';
import {transform} from 'ol/proj';
import helper from '../common/helper.js';
import {register} from 'ol/proj/proj4';
import proj4 from '../common/proj4.js'
data中定义变量
data() {
return {
dataProj:'EPSG:2382',
mapProj:'EPSG:4326',//地图坐标
typeStr:/^\s*(\w+)\s*\(\s*(.*)\s*\)\s*$/,
};
}
location(shape,index){
console.log(shape);//POINT(546985.0814819336 3011908.335510254)
this.initProj4();
let coods = transform(this.read(shape),'EPSG:2382','EPSG:4326');
helper.map.getView().setCenter(coods)
helper.map.getView().setZoom(15);
},
read: function(wkt) {
var features, type, str;
wkt = wkt.replace(/[\n\r]/g, " ");
var matches = this.typeStr.exec(wkt);
if(matches) {
str = matches[2].split(' ');
features = str.map((item,index)=>{ return parseFloat(item)})
}
return features;
},
initProj4:function (){
proj4.defs("EPSG:2382","+proj=tmerc +lat_0=0 +lon_0=111 +k=1 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs");
register(proj4);
},
parse: function(str) {
var coords = this.trim(str).split(/\s+/);
return coords;//new esri.geometry.Point(coords[0], coords[1]);
},
trim(str){
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}