[GIS] How to create a circle in openlayers 3

javascriptopenlayers

I have tried to create a circle of desired range using following code but not working. Please guide me.

function createBuffer(lat, lon, range) {

var style = new ol.style.Style({
    fill : new ol.style.Fill({
    color : 'yellow',
    opacity : 0.6,
    color : 'rgba(255,255,204,0.3)'
}),
stroke : new ol.style.Stroke({
    width : 2,
    // color: 'rgba(255, 100, 50, 0.8)'
    color : 'red',
    radius : 1
}),
image : new ol.style.Circle({
    fill : new ol.style.Fill({
    // color: 'rgba(55, 200, 150, 0.5)'
    color : 'rgba(51, 204, 255,0.3)'
}),
stroke : new ol.style.Stroke({
    width : 1,
    color : 'blue'
    // color:'rgb(230, 184, 0,0)'
}),
radius : 3
}),
  });
var  features = [];
var point = new ol.geom.Circle(ol.proj.transform([parseFloat(lat),parseFloat(lon)], 'EPSG:4326', 'EPSG:4326'),range*1210);
console.log(point.getCenter());
console.log(point);  

// Features
var pointFeature = new ol.Feature(point);
features.push(pointFeature);

// Source and vector layer
var vectorSource = new ol.source.Vector({
    projection: 'EPSG:4326',
    features: features
});

var vectorLayer = new ol.layer.Vector({
    source : vectorSource,
    style : style
});
map.renderSync();
map.addLayer(vectorLayer);
}

Best Answer

I've created a simple listener on double click that adds a circle to the map:

map.getViewport().addEventListener("dblclick", function(e) {
  var coordinate = map.getEventCoordinate(e);
  vectorSource.addFeature(new ol.Feature(new ol.geom.Circle(coordinate, dist)));
});

The distance dist can be defined elsewhere.

Check the following fiddle. It has a running example. When you double click on the map, a circle is created. If you want to change the circle radius, change the combobox.

If you want to create a buffer around an existing point, it is not much more complicated. I've created another fiddle, where you already have a layer with 4 cities. If you click on a city, the buffer is created.

Be aware that the web mercator maybe IS NOT THE BEST PROJECTION to create circles. Make sure you understand the web mercator fallacy.

Related Question