openlayers常用方法封装

import 'ol/ol.css';
import { isPlainObject } from '@/utils/assist';
import { Map, View, Tile, Feature, Overlay } from 'ol';
import { XYZ, Vector as VectorSource, ImageStatic, ImageCanvas as ImageCanvasSource, Cluster } from 'ol/source';
import { Tile as TileLayer, Vector as VectorLayer, Image as ImageLayer, Graticule as GraticuleLayer,  } from 'ol/layer';
import { GeoJSON, WKT } from 'ol/format';
import { defaults, MousePosition } from 'ol/control';
import { createStringXY } from 'ol/coordinate';
import { LinearRing, LineString, Point, Polygon, MultiLineString, MultiPolygon, Circle as CircleShape } from 'ol/geom';
import { fromExtent, fromCircle } from 'ol/geom/Polygon';
import { Style, Stroke, Text, Fill, Circle, Icon, IconImage, RegularShape } from 'ol/style';
import { transform, fromLonLat } from "ol/proj";
import Collection from 'ol/Collection';

export const baseURL = process.env.BASE_URL;

export const EPSG4326 = 'EPSG:4326';
export const EPSG3857 = 'EPSG:3857';

//创建地图
export function createMap(opts) {
    let { id, layers, controls, view } = opts || {};
    let map = new Map({
        target: id,
        layers,
        view: new View({
            projection: EPSG4326,
            ...view,
        }),
        controls: defaults({// 设置地图控件,默认的三个控件都不显示
            attribution: false,
            rotate: false,
            zoom: false,
            ...controls,
        }).extend(id === 'lvg-map' ? [mousePositionControl('mouse-position',"right-bottom")] : ''),
    });
    // map.addControl( mousePositionControl('mouse-position',"right-bottom") );
    return map;
}
//实例化鼠标位置经纬度控件
export function mousePositionControl(id,cN) {
    return new MousePosition({
        coordinateFormat: createStringXY(4), //坐标格式
        projection: EPSG4326, //地图投影坐标系
        className: `custom-mouse-position ${cN}`, //坐标信息显示样式,cN:自定义类名
        target: document.getElementById(id), // 显示鼠标位置信息的目标容器
        undefinedHTML: '不在范围内', //未定义坐标的标记
    });
}
//设置图层是否显示,opts: { layerId: true/false }
export function setVisibleLayer(map, opts) {
    Object.keys(opts).forEach(layerId => {
        const layer = findLayerById(map, layerId);
        if (layer) {
            layer.setVisible(opts[layerId]);
        }
    });
}
//根据 layerId 来查找 layer
export function findLayerById(map, layerId) {
    const layers = map.getLayers().getArray();
    for (let i = 0; i < layers.length; i++) {
        const prop = layers[i].getProperties();
        if (prop['layerId'] === layerId) {
            return layers[i];
        }
    }
}
//创建图层
export function createLayer(opts) { 
    const { style, source, ...layerOpts } = opts || {};
    return new VectorLayer({
        source: new VectorSource({
            format: new GeoJSON(),
            ...source,
        }),
        style: typeof style === 'function' ? style : createStyle(style),
        ...layerOpts,
    });
}
//样式
export function createStyle(opts = {}) {
    return new Style(stampStyle(opts));
}
//整合样式参数
export function stampStyle(opts = {}) {
    const type = {
        stroke: Stroke,
        text: Text,
        fill: Fill,
        circle: Circle,
        icon: Icon,
        iconImage: IconImage,
        image: null,
        regularShape: RegularShape,
        backgroundFill: Fill,
        backgroundStroke: Stroke,
    };
    function stamp(opts) {
        const style = {};
        Object.entries(opts).forEach(([key, val]) => {
            if (key in type && isPlainObject(val)) {
                if (key == 'image') {
                    const [[k, v]] = Object.entries(val);
                    style[key] = new type[k](stamp(v));
                } else {
                    style[key] = new type[key](stamp(val));
                }
            } else {
                style[key] = val;
            }
        });
        return style;
    }
    return stamp(opts);
}
//绑定图层
export function blankLayer(opts) {
    return new VectorLayer({
        zIndex: opts.zIndex || 1000,
        ...opts,
        source: new VectorSource(),
    });
}
//给指定图层添加点要素
export function addFeaturesPoint(layer, data, isClearSource, style, x = 'lon', y = 'lat') {
    const source = layer.getSource();
    if (isClearSource) {//isClearSource用于循环创建点,isClearSource为true是不可循环创建点,false是可以循环创建点
        source.clear(); //先移除之前的点
    }
    if (!data || !data.length) {
        return;
    }
    const feature = data.map(item => {
        const point = createFeature({
            layerId: layer.get('layerId'),
            geometry: createPoint([+item[x], +item[y]]),
            data: item,
        });
        point.setStyle(typeof style == 'function' ? style(item) : style);
        return point;
    });
    source.addFeatures(feature);
}
//给指定图层添加线要素
export function addFeaturesLine(layer, data, isClearSource, style, x = 'lon', y = 'lat') {
    const source = layer.getSource();
    if (isClearSource) {//isClearSource用于循环创建线,isClearSource为true是不可循环创建线,false是可以循环创建线
        source.clear(); //先移除之前的点
    }
    if (!data || !data.length) {
        return;
    }
    const feature = [];
    data.sort((a, b) => {
        const line = createFeature({
            layerId: layer.get('layerId'),
            geometry: createLineString([
                [+b[x], +b[y]],
                [+a[x], +a[y]],
            ]),
            data: [b, a],
        });
        line.setStyle(typeof style == 'function' ? style(b, a) : style);
        feature.push(line);
    });
    source.addFeatures(feature);
}
//给指定图层添加面要素
export function addFeaturesPolygon(layer, data, isClearSource, style, x = 'lon', y = 'lat') {
    const source = layer.getSource();
    if (isClearSource) {//isClearSource用于循环创建面,isClearSource为true是不可循环创建面,false是可以循环创建面
        source.clear(); //先移除之前的点
    }
    if (!data || !data.length) {
        return;
    }
    const feature = [];
    data.sort((a, b) => {
        const line = createFeature({
            layerId: layer.get('layerId'),
            geometry: createPolygon([
                [+b[x], +b[y]],
                [+a[x], +a[y]],
            ]),
            data: [b, a],
        });
        line.setStyle(typeof style == 'function' ? style(b, a) : style);
        feature.push(line);
    });
    source.addFeatures(feature);
}
//十六进制颜色值转成rgba
export function colorRgb(str,opacity){
    let sColor = str.toLowerCase();
    if(sColor){
        if(sColor.length === 4){
            let sColorNew = "#";
            for(let i=1; i<4; i+=1){
                sColorNew += sColor.slice(i,i+1).concat(sColor.slice(i,i+1));
            }
            sColor = sColorNew;
        }
        //处理六位的颜色值
        let sColorChange = [];
        for(let i = 1; i < 7; i += 2){
            sColorChange.push(parseInt("0x"+sColor.slice(i,i+2)));
        }
        return "rgba(" + sColorChange.join(",")+","+opacity + ")";
    }else{
        return sColor;
    }
};
//导出api
export function createFeature(opts = {}) {
    return new Feature(opts);
}
export function createCollection() {
    return new Collection();
}
export function createCircleShape(center, radius) {
    return new CircleShape(center, radius);
}
export function createVectorLayer(opts = {}) {
    return new VectorLayer(opts);
}
export function createVectorSource(opts = {}) {
    return new VectorSource(opts);
}
export function createOverlay(opts = {}) {
    return new Overlay(opts);
}
export function createFromLonLat(arr) {
    return new fromLonLat(arr);
}
export function createPoint(opts = []) {
    return new Point(opts);
}
export function createLineString(opts = []) {
    return new LineString(opts);
}
export function createPolygon(opts = {}) {
    return new Polygon(opts);
}
export function createMultiLineString(opts = {}) {  
    return new MultiLineString(opts);
}
export function createMultiPolygon(opts = {}) {
    return new MultiPolygon(opts);
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是 OpenLayers常用的一些地图方法: 1. 创建地图对象 ``` var map = new ol.Map({ target: 'map', // 地图容器元素的 id layers: [...], // 地图图层 view: new ol.View({ center: [0, 0], // 地图中心点坐标 zoom: 2 // 地图缩放级别 }) }); ``` 2. 添加图层 ``` var layer = new ol.layer.Tile({ source: new ol.source.OSM() }); map.addLayer(layer); ``` 3. 设置地图中心点和缩放级别 ``` map.getView().setCenter([lon, lat]); map.getView().setZoom(zoom); ``` 4. 添加标注 ``` var marker = new ol.Feature({ geometry: new ol.geom.Point([lon, lat]), name: 'Marker' }); var markerLayer = new ol.layer.Vector({ source: new ol.source.Vector({ features: [marker] }) }); map.addLayer(markerLayer); ``` 5. 添加矢量图层 ``` var vectorLayer = new ol.layer.Vector({ source: new ol.source.Vector({ features: [...] }), style: new ol.style.Style({ stroke: new ol.style.Stroke({ color: 'blue', width: 3 }), fill: new ol.style.Fill({ color: 'rgba(0, 0, 255, 0.1)' }) }) }); map.addLayer(vectorLayer); ``` 6. 监听地图事件 ``` map.on('click', function(evt) { console.log('Map clicked at ' + evt.coordinate); }); ``` 7. 缩放地图 ``` map.getView().setZoom(map.getView().getZoom() + 1); // 放大地图 map.getView().setZoom(map.getView().getZoom() - 1); // 缩小地图 ``` 8. 平移地图 ``` map.getView().setCenter([lon, lat]); // 移动地图中心点 ``` 9. 获取地图当前范围 ``` var extent = map.getView().calculateExtent(map.getSize()); // 获取地图当前范围 ``` 10. 图层切换 ``` layer.setVisible(true); // 显示图层 layer.setVisible(false); // 隐藏图层 ``` 这些方法只是 OpenLayers 中的一部分,还有很多其他的方法可以根据不同的需求进行调用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值