Is it possible to add a icon symbol to a polygon

本小妞迷上赌 提交于 2019-12-24 05:28:09

问题


I am currently working on a openlayers 3 project and for better visulaizing i need to show both. The Polygon shape(attribute based color) which works great and an icon on the polygon position. I know that the polygon contains multiple coordinates and so its not so easy to define a position for the icon. Now i have some kind of workaround that creates an seperate overlay with the interior Points of the polygon to mark the position of the icons. To make the project more simple i want to combine these two styling. Does anyone know if its possible?

Kind Regards


回答1:


I presumes that you use a ol.source.serversource for your data. The trick is to test all your features for being a polygon. If it is, you create a point feature you add to your source.

First create the source and the layer:

var avlVectorSource = new ol.source.ServerVector({
  format: new ol.format.GeoJSON(),
  loader: function(extent, resolution, projection) {
    myLoader(resolution);
  }
});

var myLayer = new ol.layer.Vector({
   source: myVectorSource,
   style: myStyleFunction      
});

The layer has a style function to set the right icon.

The main thing is the loader:

var myLoader = function(resolution){
    $.ajax({
        url: "http://myJsonSource.com",
        timeout: 1000,
        success: function(response) {
            var layerJSONString = $.parseJSON(response);
            var newFeatures = [];
            j= 0;
            var size=layerJSONString.features.length;
            for (i = 0; i < size; i++){
                var feat = layerJSONString.features[i];
                var geom = feat.geometry;
                var type = geom.type;
                if(type == "Polygon")
                {
                    var poly = new ol.geom.Polygon(geom.coordinates);
                    var extent = poly.getExtent();
                    var coord = [];
                    coord[0] = (extent[2]-extent[0])/2 + extent[0];
                    coord[1] = (extent[3]-extent[1])/2 + extent[1];
                    var point = new ol.geom.Point(coord);
                    newFeatures[j++] = new ol.Feature({
                        geometry : point,
                        StyleName : feat.properties.StyleName
                    });
                } 
            }           
            avlVectorSource.addFeatures(myVectorSource.readFeatures(response));
            avlVectorSource.addFeatures(newFeatures);
        },
        error: myLoadError
    });
}
};

The documentation says that ol.geom.Polygon has a method called getInteriorPoint(). It has but I can get it to work. So I calculate the center point of the extent of the polygon.

I use "StyleName" to set the right icon in my style function.



来源:https://stackoverflow.com/questions/27093482/is-it-possible-to-add-a-icon-symbol-to-a-polygon

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!