openlayers 2实现vector图层文字标注

图层绑定要素属性实现文字标注,注意是openlayers2不是3
大概的思路是,继承OpenLayers.Layer.Vector,监听图层添加要素的事件,创建dom节点,添加到map的容器之中,同时地图放大缩小,文字标注跟随移动(根据分辨路重新计算位置),图层移除要素,移除标注;
初始化

/**
     * Constructor: OpenLayers.Layer.E_Vector
     */
    initialize : function(layerName,options) {
        OpenLayers.Layer.Vector.prototype.initialize.apply(this,arguments);
        this.annotations = [];  
    },

创建标注

/**
     * 创建标注
     * @param data
     */
    createAnnotation :function(data){
        if(!this.annotationsVisible && data.feature.layer != this)return;
        if(data.feature.attributes != null
            && data.feature.attributes.annotationDisplay != null
            && data.feature.attributes.annotationDisplay==false)
            return;
        if(data.feature.attributes.hasOwnProperty(this.bindFiled)==false)return;
        for (var i = 0, len = this.annotations.length; i < len; i++) {
            if (this.annotations[i].feature == data.feature) {
                return;
            }
        }
        var lglt = null;
        if (data.feature.geometry instanceof OpenLayers.Geometry.Point) {
            lglt = data.feature.geometry.getBounds().getCenterLonLat();
        } else if (data.feature.geometry instanceof OpenLayers.Geometry.LineString) {  //取线图形的中部作为展示标注的位置
            var lineGeos = data.feature.geometry.getVertices();
            lglt = lineGeos[parseInt(lineGeos.length / 2)].getBounds().getCenterLonLat();
        } else if (data.feature.geometry instanceof OpenLayers.Geometry.Polygon) {    //取面图形的中心作为展示标注的位置
            var point = data.feature.geometry.getCentroid();
            lglt = point.getBounds().getCenterLonLat();
        }
        var px = this.map.getLayerPxFromLonLat(lglt).add(this.annotationOffset.x,this.annotationOffset.y);
        //size 可以根据自己需要写到外部
        var size = new OpenLayers.Size(120,30);
        var divId = OpenLayers.Util.createUniqueID("E_Annotation"+"_");
        var anDiv = OpenLayers.Util.createDiv(divId, px, size,null, null, null, "hidden");
        this.map.layerContainerDiv.appendChild(anDiv);
        anDiv.innerHTML = data.feature.attributes[this.bindFiled];
        anDiv.style.zIndex = 250;
        this.annotations.push({feature:data.feature,div:anDiv});
    },

初始化标注的时候监听

        this.events.on({"featureadded": this.createAnnotation});//监听featureadded事件
        this.events.on({"featureremoved": this.deleteAnnotation});//监听featureremoved事件

大概的思路就这样,最后贴代码:
https://git.oschina.net/leez/OpenLayers2_EXT.git

你可能感兴趣的:(gis,javascript)