Thursday, 22 October 2015

How to add a buffer on a point in OpenLayers 3


I am trying to add a buffer around some points shown on a map. I have tried to do something similar back in the days of OL2 and I remember it was not straight forward.



Is there a simple way to do this in OL3? I have found this:


ol.extent.buffer(extent, value, opt_extent)

but I am not able to find an example.



Answer



As long as you want to buffer points or extents, the function you mentioned should be enough. But If you want to buffer polygons or linestring JSTS topology suite would give you the solution. Now back to your question. Do something like the following:


//create the point feature you want to buffer
var pointFeature = new ol.Feature(
new ol.geom.Point([0,0])
);

//create a [point layer and a source and pass the fetaure to the source
var vectorPoint= new ol.layer.Vector({
source: new ol.source.Vector({
features: [pointFeature]
})
});
//create a polyon layer to hold your buffers
var vectorBuffers= new ol.layer.Vector({
source: new ol.source.Vector({})
});

//initilise your map and add the layers
var map = new ol.Map({
layers: [raster,vectorPoint,vectorBuffers],
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
});


//and finally build a function to do the buffering
var radius= 1000000;
function bufferit(radius){
var poitnExtent = pointFeature.getGeometry().getExtent();
var bufferedExtent = new ol.extent.buffer(poitnExtent,radius);
console.log(bufferedExtent);
var bufferPolygon = new ol.geom.Polygon(
[
[[bufferedExtent[0],bufferedExtent[1]],
[bufferedExtent[0],bufferedExtent[3]],

[bufferedExtent[2],bufferedExtent[3]],
[bufferedExtent[2],bufferedExtent[1]],
[bufferedExtent[0],bufferedExtent[1]]]
]
);
console.log("bufferPolygon",bufferPolygon);
var bufferedFeature = new ol.Feature(bufferPolygon);
vectorBuffers.getSource().addFeature(bufferedFeature);
}


here is a fiddle to make your life easier


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...