openlayers 2實現vector圖層文字標註
阿新 • • 發佈:2019-02-03
圖層繫結要素屬性實現文字標註,注意是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事件