how to draw circle with radius in openlayers

Mayank Pandya picture Mayank Pandya · Apr 24, 2014 · Viewed 19.1k times · Source

I want to draw a circle in openlayers with specific radius in km. with the center of specific geo point? I follow same as http://demo.gwt-openlayers.org/gwt_ol_showcase/GwtOpenLayersShowcase.html?example=Draw%20Regular%20Polygon%20Example but I want to draw automatically with predefined values.

Answer

Alexandre Mélard picture Alexandre Mélard · Feb 3, 2015

The following code will give you a circle in light blue centered at the center of the current map with a radius defined in meters. If you want it in feet, just replace:

        var radius = (radius / ol.proj.METERS_PER_UNIT.m) * resolutionFactor;

with:

        var radius = (radius / ol.proj.METERS_PER_UNIT.ft) * resolutionFactor;

Code:

   var drawCircleInMeter = function(map, radius) {
        var view = map.getView();
        var projection = view.getProjection();
        var resolutionAtEquator = view.getResolution();
        var center = map.getView().getCenter();
        var pointResolution = projection.getPointResolution(resolutionAtEquator, center);
        var resolutionFactor = resolutionAtEquator/pointResolution;
        var radius = (radius / ol.proj.METERS_PER_UNIT.m) * resolutionFactor;


        var circle = new ol.geom.Circle(center, radius);
        var circleFeature = new ol.Feature(circle);

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

        map.addLayer(vectorLayer);
    }

NB. The OpenLayers circle created here is always a perfectly flat 2d circle. Whereas in reality you may want something that takes better account of the map projection (especially close to the poles).