无法在 Openlayers 3 中将绘制的圆的特征保存到 JSON

Can't save features of drawn Circle to JSON in Openlayers 3

所以,事情是这样的:我想在 OL3 中的地图上画一个圆,然后将其保存到 JSON 文件中。据我了解,您不能将圆形几何体写入 JSON (https://github.com/openlayers/ol3/issues/3552)。我使用 OL3 示例绘制形状并将其更改为使用 ol.geom.Polygon.circular 方法以避免使用圆形几何。当我尝试保存它时,我得到 "TypeError: cyclic object value".

if (value) {
var geometryFunction, maxPoints;
    if (value === 'Circle') {
        value='Circle';
        maxPoints=2;
        geometryFunction = function (coordinates, geometry) {
        if (!geometry) {
        geometry = new ol.geom.Polygon(null);
                    }
      var center = coordinates[0];
      var last = coordinates[1];
      var dx = center[0] - last[0];
      var dy = center[1] - last[1];
      var radius = Math.sqrt(dx * dx + dy * dy);
      geometry = ol.geom.Polygon.circular(wgs84Sphere, center, radius);
      return geometry;
                }; 
            draw = new ol.interaction.Draw({
                features:features,
                type: value,
                geometryFunction: geometryFunction,
                maxPoints: maxPoints
            });
            map.addInteraction(draw);

我就是这样省钱的JSON:

var writer = new ol.format.GeoJSON();
var geojsonStr = writer.writeFeatures(source.getFeatures());
alert(geojsonStr);

我很确定一定有一种方法可以使用 ol.geom.Polygon.fromCircle 或 ol.geom.Polygon.circular 绘制圆并将其保存到 JSON。有什么想法吗?

使用自定义 geometryFunction 时,您必须使用作为第二个参数传递给几何函数的现有 geometry(如果可用)。我更新了你的 fiddle:http://jsfiddle.net/px6ks0am/1/.

成功的关键是以下 geometryFunction,它还负责正确地重新投影圆形多边形:

var wgs84Sphere = new ol.Sphere(6378137);
function geometryFunction(coordinates, geometry) {
  if (!geometry) {
    geometry = new ol.geom.Polygon(null);
  }
  var center = coordinates[0];
  var last = coordinates[1];
  var dx = center[0] - last[0];
  var dy = center[1] - last[1];
  var radius = Math.sqrt(dx * dx + dy * dy);
  var circle = ol.geom.Polygon.circular(wgs84Sphere, ol.proj.toLonLat(center), radius);
  circle.transform('EPSG:4326', 'EPSG:3857');
  geometry.setCoordinates(circle.getCoordinates());
  return geometry;
}