turf.js OpenLayers3 Draw中自相交多边形的相交错误

turf.js Intersect Error for Self-intersecting Polygons from OpenLayers3 Draw

本文关键字:错误 多边形 自相交 js OpenLayers3 Draw turf      更新时间:2023-09-26

我使用OpenLayers3 ol.interaction.Draw让用户在地图上绘制一个形状,可以通过单击顶点,也可以通过Shift+Drag来绘制自由多边形(这对我的应用程序很重要)。一旦绘制了形状,我就使用turf.js将绘制的形状与客户端中的WFS层进行比较,运行intersect()查看WFS特征是否与绘制的形状相交。然而,如果手绘形状甚至有最轻微的自相交,则turf.js intersect()函数将失败,并出现以下错误(第326行是我调用intersect()的地方)。

trurt.min.js:9未捕获[object对象]
getResultGeometry@surfs.min.js:9
si.overlayOp@草皮.最小.js:9
交叉路口@草皮.min.js:15
e.exports@草皮.min.js:16
(匿名函数)@main.js:326

下面是我的代码草图。

var features = new ol.Collection();
var vs = new ol.source.Vector({
  format: new ol.format.GeoJSON(),
  url: function(extent) {
    return XXXXXX;
  },
  strategy: ol.loadingstrategy.bbox
});
features.on('add', function() {
  vs.forEachFeatureIntersectingExtent(extent, function(feature) {
    // use to turf.js to intersect each feature with drawn feature
    var bt = gjformat.writeFeatureObject(feature, {rightHanded: false});
    var dt = gjformat.writeFeatureObject(features.item(0), {rightHanded: false} );
    var intersection = turf.intersect(bt, dt);
  }
});

我试过同时使用turf.js simplify()ol.geom.Geometry.simplify(),但都没有用。有人对使用turf.js intersect()处理手绘自相交多边形有什么建议吗?或者在运行交叉口之前删除自交叉口的方法?

受使用JSTS缓冲区来识别自相交多边形的答案的启发(感谢lead@ahocevar),我将解决方案移植到了turf.js。将绘制的具有自相交的特征缓冲0将删除较小的自相交多边形,并为您提供一个运行intersect()的干净功能。

    features.on('add', function() {
      vs.forEachFeatureIntersectingExtent(extent, function(feature) {
        // create geojson of wfs features and drawn feature
        var bt = gjformat.writeFeatureObject(feature, {rightHanded: false});
        var dt = gjformat.writeFeatureObject(features.item(0), {rightHanded: false} );
        // check for kinks in the drawn feature
        var kinks = turf.kinks(dt);
        var dtf;
        if(kinks.features.length > 0) {
          // if there are self-intersections, buffer by 0 to get rid of them
          dtf = turf.buffer(dt, 0, 'meters');
        } else {
          // if there are no self-intersection, intersect by unbuffered features
          dtf = dt; 
        }
        var intersection = turf.intersect(bt, dtf);
      }
    });

您至少可以警告用户自交叉。这些可以通过JSTS检测到。请参见谷歌地图多边形自相交检测。删除自相交比较困难,但使用JSTS也应该可以:使用JSTS缓冲区来识别自相交多边形。