Just a cat
Just a cat

Reputation: 5

How to add circle programmatically with radius,long and lat in Openlayers?

I am trying to add circle with latitude,longitude and radius(in meter or kilometer) when a button clicked.

I can add a circle on button clicked but it takes radius as a number between 1-25. I need to give radius in meter

Note: when I draw a circles with finger gestures , I can get its radius in meter with this code

var radius = geometry.getRadius();

My drawing with finger gesture function:

function addInteraction() {
  draw = new ol.interaction.Draw({
    source: source,
    type: shapetype,
    freehand: true
  });
  map.addInteraction(draw);

Upvotes: 0

Views: 6846

Answers (2)

geocodezip
geocodezip

Reputation: 161334

To add a circle to the map:

var centerLongitudeLatitude = ol.proj.fromLonLat([longitude, latitude]);
var layer = new ol.layer.Vector({
  source: new ol.source.Vector({
    projection: 'EPSG:4326',
    features: [new ol.Feature(new ol.geom.Circle(centerLongitudeLatitude, 4000))]
  }),
  style: [
    new ol.style.Style({
      stroke: new ol.style.Stroke({
        color: 'blue',
        width: 3
      }),
      fill: new ol.style.Fill({
        color: 'rgba(0, 0, 255, 0.1)'
      })
    })
  ]
});
map.addLayer(layer);

proof of concept fiddle

screenshot of resulting map

code snippet:

var map = new ol.Map({
  target: 'map',
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    })
  ],
  view: new ol.View({
    center: ol.proj.fromLonLat([-117.1610838, 32.715738]),
    zoom: 12
  })
});
var centerLongitudeLatitude = ol.proj.fromLonLat([-117.1610838, 32.715738]);
var layer = new ol.layer.Vector({
  source: new ol.source.Vector({
    projection: 'EPSG:4326',
    // radius = 4000 meters
    features: [new ol.Feature(new ol.geom.Circle(centerLongitudeLatitude, 4000))]
  }),
  style: [
    new ol.style.Style({
      stroke: new ol.style.Stroke({
        color: 'blue',
        width: 3
      }),
      fill: new ol.style.Fill({
        color: 'rgba(0, 0, 255, 0.1)'
      })
    })
  ]
});
map.addLayer(layer);
html,
body {
  height: 100%;
  width: 100%;
  padding: 0px;
  margin: 0px;
}

.map {
  height: 100%;
  width: 100%;
}
<link href="https://openlayers.org/en/v4.6.5/css/ol.css" rel="stylesheet" />
<script src="https://openlayers.org/en/v4.6.5/build/ol.js"></script>
<div id="map" class="map"></div>

Upvotes: 5

Thomas Gratier
Thomas Gratier

Reputation: 2371

You just need to do the following

var coordsLongitudeLatitude = [1, 44]
# Convert to map coordinates (usually Spherical Mercator also named EPSG 3857)
var center = ol.proj.fromLonLat(coordsLongitudeLatitude)
# Create Circle geometry, 4000 = distance in meters
var circleGeometry = new ol.geom.Circle(center, 4000);
# If you want/need to transform it to a polygon
var polygonFromCircleGeometry = ol.geom.Polygon.fromCircle(circleGeometry);

Upvotes: 2

Related Questions