Search code examples
javascriptopenlayers

why does drawing a circle in the northern hemisphere result in an oval?


I know there is probably some geographical/mathematical/Projection reason, but why does my circle result in a oval polygon? i am trying to draw a circle from a point.

code

https://jsfiddle.net/mdecker84/1embLyhj/9/

When my Point has coordinates: [0, 0] or in the southern hemisphere i get a perfect circle. I don't know what is going on.

enter image description here

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([-71.076056, 42.388399], 'EPSG:3857'),
    zoom: 9
  })
});
var layer = new ol.layer.Vector({
  source: new ol.source.Vector({
    projection: 'EPSG:4326',
    features: []
  }),
});
map.addLayer(layer);
var vectorSource = layer.getSource();

function createCircle(circleCenterX, circleCenterY, circleRadius, pointsToEnd) {
  let angleToAdd = 360 / pointsToEnd;
  let coords = [];
  let angle = 0;
  for (let i = 0; i < pointsToEnd; i++) {
    angle += angleToAdd;
    let coordX = circleCenterX + circleRadius * Math.cos(angle * Math.PI / 180);
    let coordY = circleCenterY + circleRadius * Math.sin(angle * Math.PI / 180);
    coords.push([coordX, coordY]);
  }
  return coords;
}

function addMarker(coordinates) {
  console.log(coordinates);
  var marker = new ol.Feature(new ol.geom.Point(coordinates));
  marker.setStyle(new ol.style.Style({
    image: new ol.style.Circle({
      radius: 5,
      fill: new ol.style.Fill({
        color: 'red'
      })
    })
  }));
  vectorSource.addFeature(marker);
}

function addCircle(coords) {
  // var lonlat1 = ol.proj.transform([0, 0], 'EPSG:4326','EPSG:3857');
  // console.log('var lonlat1',lonlat1)
  var circleCoords = createCircle(coords[0], coords[1], 0.2, 180);
  console.log(circleCoords);
  var polygon = new ol.geom.Polygon([circleCoords]);
  polygon.transform('EPSG:4326', 'EPSG:3857');
  polygon = new ol.Feature(polygon);
  vectorSource.addFeature(polygon);
}

addCircle(ol.proj.toLonLat([-7912507.055205271, 5196764.057392394]));
addMarker([-7912507.055205271, 5196764.057392394]);
html,
body {
  height: 100%;
  width: 100%;
  padding: 0px;
  margin: 0px;
}

.map {
  height: 100%;
  width: 100%;
}
<html>

<head>
  <link href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.4.3/css/ol.css" rel="stylesheet" />
  <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.4.3/build/ol.js"></script>
</head>

<body>
  <div id="map" class="map"></div>
</body>
</html>


Solution

  • This is due to the earth being a globe. That's really it. It is still a circle but bended on the z-axis