openlayer学习总结


  1. 最好的学习素材(http://openlayers.org/en/latest/examples/
  2. 学习的主要点Map(View,Layer(Source(Feature(ol.geom.Point…))))
  3. 地图中主要的存在是图层Layer,这个Layer需要依赖于某个创建好的Map,图层中可以展示各种各样的点线面,对于这些点线面可以使用东西进行装饰他们,无论是点线还是面,都通通称呼为要素Feature,对于这个要素,可以动态的添加删除到Layer中。
  4. View主要是控制格式,坐标的格式,放大缩小,地图的中心等等,设置到Map中可以查看相应的ol.Map中去查看如何设置view,到ol.View中查看种种重要的东西。查看api和事例的Demo是个好东西。

Map的创建

   var map = new ol.Map({
        //目标div
        // target: "mapView",
        target: this.mapDiv,
        //渲染方式
        renderer: 'canvas',
        //控件,比如放大缩小
        controls: ol.control.defaults({
            attribution: false
        }),
        view: new ol.View({
          zoom: 6
        }),
        //layers: [roads, imagery]
        //layers 代表主要显示的几个图层,我们一般通过函数添加
        //这个也是Map的属性
    });

创建Layer

Layer有好几种类型的tile(瓦片地图),Image(图像),Vector(画点线等等需要的图层)
Layer中的资源就是图层中信息,图片,或者我们添加的点线面等等数据
Image图层(来至于静态图片)

 var baseLayer= new ol.layer.Image({
        source:new ol.source.ImageStatic({
            url:"test.jpg"
        })
    })

Vector:
这里的style是设置整个图层中所有添加的要素的样式,你也可以单独的在要素中添加样式,这个style有三种形式 ol.style.Style | Array.< ol.style.Style> | ol.StyleFunction(A function that takes an ol.Feature and a {number} representing the view’s resolution. The function should return a ol.style.Style or an array of them. This way e.g. a vector layer can be styled.)
你可以返回一个数组的style或者一个函数当添加要素的时候通过判断逻辑进行处理。
这里的source:是我们接触的最多的部分,在向矢量图层中添加要素的时候都需要getSource()然后在进行添加要素。

 var areaLayer = new ol.layer.Vector({
        source: new ol.source.Vector(),
        style:new ol.style.Style({
                  image: new ol.style.Circle({
                        radius: 7,
                        fill: new ol.style.Fill({
                          color: '#ffcc33'
                        })
                      })
                   }),
        zIndex:1
     });

Layer添加要素

添加要素一般都是在ol.geom.Point/ol.geom.LineString()等等,你可以去修饰这些要素添加style。
要素一般称为ol.Feature,Feature中你可以通过类似Map的属性设置你要保持的ID等交互需要的信息,点击Feature的时候可以获取得到相关的数据信息。
var jobId = feathure.get(“jobId”);这样的类似。
然后添加到图层中去,这里也可以单独设置要素的样式,如果之前设置图层style的时候使用function的形式可以接受到当前添加的要素feature的形式,根据属性进行特别的绘制。

    var  point = new ol.geom.Point([x,y]);
    var feature = new ol.Feature({
        geometry :point,
        jobId :"关键的属性"
    });
    this.areaLayer.getSource().addFeature(feature);

划线(将点的数据一个个的添加,具体的其他的方案可以参考api,比如wkt或者gjson等等,我没有用过哈哈),然后添加到图层中去就好了。

    var lineString = new ol.geom.LineString();
    for(var i=0;i < param.length;i++){
        var point = [param[i].x,param[i].y];
        lineString.appendCoordinate(point);
    }
    var feature = new ol.Feature({
        geometry : lineString
    })

事件

事件的监听都是放置在Map上面的,我们可以通过监听,判断是否要处理,还可以自定义事件,分发下去。
监听点击或者渲染事件(时刻都在,可以在里面做些定时器做的事情)

(自定义事件)
http://www.zhangxinxu.com/wordpress/2012/04/js-dom%E8%87%AA%E5%AE%9A%E4%B9%89%E4%BA%8B%E4%BB%B6/

map.on('click', function(evt) {
        var pixel = evt.pixel;
        var coordinate = map.getCoordinateFromPixel(pixel); //获取像素界别的坐标
        var feature = map.forEachFeatureAtPixel(pixel, function(feature) {
                return feature;
            }) 
            //遍历地图上的所有的要素,判断当前点击的点在哪个要素上,如果存在返回,否则为空
        if (feature && feature instanceof ol.Feature) {
            //这里做相应的处理,弹出对话框,或者其他的自己处理
            //也可以分发成自定义的事件,触发自定义的事件
             document.dispatchEvent(new MapClick('map-click',feature));

        }

    });

map.on("map-click",function(events){
    //可以在外面做些事情,方便封装
})

//让他继承Map的事件体系,这样在Map中就可以监听这个事件了
var MapClick = function(type,param){
    ol.events.Event.call(this,type);
    this.param = param;
}
ol.inherits(MapClick, ol.events.Event);

拖动要素

官方上的例子很好直接可以使用,在放开的一瞬间处理自己的事件就好了。

下面是处理业务的时候的用的东西

/**
 * descrption: 使用openLayer处理
 * authohr: wangji
 * date: 2017-07-24 20:00
 */
var radius = 0;
var MapConfig = function (opt) {
    ol.Object.call(this);
    this.setting = opt.setting||false;
    this.mapDiv = opt.mapDiv || undefined;
    this.imagePath =opt.imagePath || undefined;
    this.extent = [-0.5, -1156.5, 1636.5, 0.5];
    this.zoom = opt.zoom || 2
    this.maxZoom  = opt.maxZoom ||17;
    this.situation = opt.situation ||0;
}
ol.inherits(MapConfig, ol.Object);
MapConfig.prototype.initMap = function () {
    if(!this.imagePath){
        return;
    }
    if(!this.mapDiv){
        return;
    }
    var __that = this;
    this.projection =new ol.proj.Projection({
        code: 'xkcd-image',
        units: 'pixels',
        extent: __that.extent
    });
    this.map = new ol.Map({
        target: this.mapDiv,
        render: 'canvas',
        view: new ol.View({
            projection: __that.projection,
            center: ol.extent.getCenter(__that.extent),
            zoom: this.zoom,
            maxZoom: this.maxZoom
        })
    });

   var baseLayer= new ol.layer.Image({//地图底图
        source:new ol.source.ImageStatic({
            url:__that.imagePath,
            projection: __that.projection,
            imageExtent: __that.extent
        })
    })
    this.baseLayer=baseLayer;

    this.map.addLayer(baseLayer);
    if(__that.situation ==0){//某种情况可以拖动
        __that.map.addInteraction(new app.Drag());
    }
    function createStyle(src,orgname) {
        return new ol.style.Style({
            image: new ol.style.Icon(({
                anchor: [0.5, 0.5],
                crossOrigin: 'anonymous',
                anchorOrigin:'bottom-right',
                src: src,
            })),
            text: new ol.style.Text({
                font:"14px serif",
                text:orgname,
                offsetX:0,
                offsetY:30,
                stroke: new ol.style.Stroke({color: 'black', width: 1})
            }),
            stroke: new ol.style.Stroke({
                width: 3,
                color: [255, 0, 0, 1]
            }),
            fill: new ol.style.Fill({
                color: [0, 0, 255, 0.6]
            })
        });
    }

    this.ruuningJobFeature = [];//存储某个点可以让其闪烁

    var areaLayer = new ol.layer.Vector({
        source: new ol.source.Vector(),
        style:function (feathure) {
            var orgName = feathure.get("orgName");
            if(__that.situation == 1){

                var globalStatus = feathure.get("globalStatus");
                if(globalStatus == 1){
                    __that.ruuningJobFeature.push(feathure);
                    return createStyle("test.jpg",orgName);//某种状态

                }else if(globalStatus == 2){
                    return createStyle("test1.jpg",orgName);
                }else{
                    return createStyle("test2.jpg",orgName);
                }
            }

        },
        zIndex:1
    });//区域layer


    this.areaLayer =areaLayer;
    this.map.addLayer(areaLayer);
    this.map.on('click',__that.mapListener,__that);
    /**
     *处理闪烁的流程
     * 1.将需要处理的要素保存起来到一个数组中
     * 2.地图渲染时都会触发postcompose事件进行监听
     * 3.将保存的要素切换其Style
     * 4.可以根据自增数据控制其切换的速度
     */
    this.map.on('postcompose', function () {
        if (__that.ruuningJobFeature.length > 0) {
            radius++;
            radius = radius % 100;
            var style;
            for (var i = 0; i < __that.ruuningJobFeature.length; i++) {
                var orgName = __that.ruuningJobFeature[i].get("orgName");
                if (radius < 60) {
                    src = "test.jpg";
                    style = createStyle(src,orgName)
                } else {

                    style = new ol.style.Style({
                        text: new ol.style.Text({
                            font:"14px serif",
                            text:orgName,
                            offsetX:0,
                            offsetY:30,
                            stroke: new ol.style.Stroke({color: 'black', width: 1})
                        }),
                        stroke: new ol.style.Stroke({
                            width: 3,
                            color: [255, 0, 0, 1]
                        }),
                        fill: new ol.style.Fill({
                            color: [0, 0, 255, 0.6]
                        })
                    });
                }
                __that.ruuningJobFeature[i].setStyle(style);
            }
        }
    })
}
MapConfig.prototype.mapListener = function(evt){
    var __that = this;
    var pixel = evt.pixel;
    var coordinate = __that.map.getCoordinateFromPixel(pixel);
    var feature = __that.map.forEachFeatureAtPixel(pixel,function(feature){//获取到点击的feathure
        return feature;
    })
    if(feature && feature instanceof ol.Feature){
        __that.dispatchEvent(new MapClick('map-click',feature));

    }
}

MapConfig.prototype.addFeature = function (feature) {
   if(feature && feature  instanceof ol.Feature){
       this.areaLayer.getSource().addFeature(feature);
   }
}
MapConfig.prototype.removeFeature = function (feature) {
    if(feature && feature  instanceof ol.Feature ){
        this.areaLayer.getSource().removeFeature(feature);
    }
}

MapConfig.prototype.getPointFeatureFromXY = function (param) {
   // debugger
    var  point = new ol.geom.Point([param.xCoord,param.yCoord]);
    var feature = new ol.Feature({
        geometry :point,
        orgName:param.orgName,//自己设置的值
        globalStatus:param.globalStatus
    });
    this.areaLayer.getSource().addFeature(feature);
}

/**
 * @desction: 创建线
 * @author: wangji
 * @date: 2017/7/25
 * @param:
 * @return:
 */
MapConfig.prototype.generateLine = function(param){
    if(param == null || param.length <=0  ){
        return;
    }
    var lineString = new ol.geom.LineString();
    for(var i=0;i< param.length;i++){
        var point = [param[i].x,param[i].y];
        lineString.appendCoordinate(point);
    }
    var feature = new ol.Feature({
        geometry : lineString
    })
    var lineLayer = new ol.layer.Vector({
        source : new ol.source.Vector(),
        style : function (feature) {
            var geometry = feature.getGeometry();
            var styles = [
                // linestring
                new ol.style.Style({
                    stroke: new ol.style.Stroke({
                        color: '#49B4FF',
                        width: 2
                    })
                })
            ];
            return styles;
        }
    })
    lineLayer.getSource().addFeature(feature);
    this.map.addLayer(lineLayer);
}
//改变底层的图片
MapConfig.prototype.changeBaseLayerImage = function (ImpagePath) {
    if(ImpagePath == undefined ||ImpagePath == ''){
        return;
    }
    var __that =this;
    var baseLayer= new ol.layer.Image({//地图底图
        source:new ol.source.ImageStatic({
            url:path+ImpagePath,
            projection: __that.projection,
            imageExtent: __that.extent
        })
    })
    __that.map.removeLayer( __that.baseLayer);
    __that.baseLayer = baseLayer;
    __that.map.addLayer(baseLayer);

}

var MapClick = function(type,param){
    ol.events.Event.call(this,type);
    this.param = param;
}
ol.inherits(MapClick, ol.events.Event);


var  app ={};//拖拽事件的处理,官方网站
app.Drag = function() {
    ol.interaction.Pointer.call(this, {
        handleDownEvent: app.Drag.prototype.handleDownEvent,
        handleDragEvent: app.Drag.prototype.handleDragEvent,
        handleMoveEvent: app.Drag.prototype.handleMoveEvent,
        handleUpEvent: app.Drag.prototype.handleUpEvent
    });
    //坐标
    this.coordinate_ = null;
    //鼠标
    this.cursor_ = 'pointer';
    //要素
    this.feature_ = null;
    this.previousCursor_ = undefined;
};
ol.inherits(app.Drag, ol.interaction.Pointer);

/**
 * 当鼠标向下的时候,判断当前是不是要素,是的话返回true开始拖拽
 */
app.Drag.prototype.handleDownEvent = function(evt) {
    var map = evt.map;

    var feature = map.forEachFeatureAtPixel(evt.pixel,
        function(feature) {
            return feature;
        });
     //记录当前的点和当前的要素的值
    if (feature && feature  instanceof ol.Feature) {
        this.coordinate_ = evt.coordinate;
        this.feature_ = feature;
    }
    return !!feature;
};


/**
 * 拖动时候的事件,不用管它
 */
app.Drag.prototype.handleDragEvent = function(evt) {
    var deltaX = evt.coordinate[0] - this.coordinate_[0];
    var deltaY = evt.coordinate[1] - this.coordinate_[1];
    var geometry = (this.feature_.getGeometry());
    geometry.translate(deltaX, deltaY);
    this.coordinate_[0] = evt.coordinate[0];
    this.coordinate_[1] = evt.coordinate[1];
};
/**
 * 拖动过程中的事件,不用管它
 */
app.Drag.prototype.handleMoveEvent = function(evt) {
    if (this.cursor_) {
        var map = evt.map;
        var feature = map.forEachFeatureAtPixel(evt.pixel,
            function(feature) {
                return feature;
            });
        var element = evt.map.getTargetElement();
        if (feature) {
            if (element.style.cursor != this.cursor_) {
                this.previousCursor_ = element.style.cursor;
                element.style.cursor = this.cursor_;
            }
        } else if (this.previousCursor_ !== undefined) {
            element.style.cursor = this.previousCursor_;
            this.previousCursor_ = undefined;
        }
    }
};

app.Drag.prototype.handleUpEvent = function() {
    //拖动结束了,我们在这里做一些自己的处理
    var objectId = this.feature_.get("orgId");
    var coordinate = this.coordinate_;
    //处理事件或者ajax请求等等

    this.coordinate_ = null;
    this.feature_ = null;
    return false;
};

转载自:https://blog.csdn.net/u012881904/article/details/76269172

You may also like...