Javascript - 如何计算线串的中点?

标签 javascript geojson

使用给定的 GeoJSON 线串:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "LineString",
        "coordinates": [
          [
            2.6806640625,
            46.437856895024204
          ],
          [
            4.7021484375,
            50.20503326494332
          ],
          [
            13.271484375,
            47.010225655683485
          ],
          [
            17.2265625,
            52.855864177853974
          ]
        ]
      }
    }
  ]
}

我想找到准确的中间点。我不是指给定数组的中间元素,而是计算一个恰好位于线中间的中点。因此,如果一条线的总长度为 30 公里,则中点将位于 15 公里处。

我尝试在 npm 中搜索类似的东西,但找不到。唯一接近的图书馆能够将 n 个点放在线上,然后我可以获得中间的一个。但这对我来说很糟糕,因为精度不是那么好。

完美的选择是实现这个 http://postgis.net/docs/manual-1.5/ST_Line_Interpolate_Point.html在 JavaScript 中。

我怎样才能实现它?

最佳答案

Here's a working CodePen

以下代码将返回特定距离处的点。

对于这种特定情况,中点距离是总长度/2

像这样调用主函数,假设我们的线串数组存储在points

var totalLength = totalLen(points);
var midDistance = totalLength / 2;
var midPoint = getPointByDistance(points, midDistance)

Javascript

myData = {
  "type": "FeatureCollection",
  "features": [{
    "type": "Feature",
    "properties": {},
    "geometry": {
      "type": "LineString",
      "coordinates": [
        [
           2.6806640625,
          46.437856895024204
        ],
        [
          4.7021484375,
          50.20503326494332
        ],
        [
          13.271484375,
          47.010225655683485
        ],
        [
          17.2265625,
          52.855864177853974
        ]
      ]
    }
  }]
}
var points = myData.features[0].geometry.coordinates
var totalLength = totalLen(points);
var midDistance = totalLength / 2;
var midPoint = getPointByDistance(points, midDistance)
alert ("midPoint = " + midPoint[0] + ", " + midPoint[1])
// main function
function getPointByDistance(pnts, distance) {
  var tl = totalLen(pnts);
  var cl = 0;
  var ol;
  var result;
  pnts.forEach(function(point, i, points) {
    ol = cl;
    cl += i ? lineLen([points[i-1], point]) : 0;
    if (distance <= cl && distance > ol){
      var dd = distance - ol;
      result = pntOnLine([points[i-1], point], dd);
    }
  });
  return result
};
// returns a point on a single line (two points) using distance // line=[[x0,y0],[x1,y1]]
function pntOnLine(line, distance) {
  t = distance / lineLen(line)
  xt = (1 - t) * line[0][0] + (t * line[1][0])
  yt = (1 - t) * line[0][1] + (t * line[1][1])
  return [xt, yt]
};
// returns the total length of a linestring (multiple points) // pnts=[[x0,y0],[x1,y1],[x2,y2],...]
function totalLen(pnts) {
  var tl = 0;
  pnts.forEach(function(point, i, points) {
    tl += i ? lineLen([points[i - 1], point]) : 0;
  });
  return tl;
};
// returns the length of a line (two points) // line=[[x0,y0],[x1,y1]]
function lineLen(line) {
  var xd = line[0][0] - line[1][0];
  var yd = line[0][1] - line[1][1];
  return Math.sqrt(xd * xd + yd * yd);
};

解释

<强>1。我们找到线串的总长度:

  • 函数 lineLen() 计算单行的长度。
  • 函数 totalLen() 遍历所有行并计算总长度。 enter image description here

*来源和学分here (Igor Šarčević)

<强>2。中点距离为全长/2:

  • 现在我们有了想要的距离,我们遍历线并检查这条线起点这条线终点的距离,看看中点距离 在他们之间。
  • 一旦我们知道我们的中点所在的单线,我们就会计算它与这条线起点的距离(总长度 - 线起点距离)

    <
  • 现在我们使用 this formula (函数 pntOnLine())找到 xt,yt(想要的中点)

enter image description here

*感谢 Sen Jacob


可视化

我包含了一个 HTML5 canvas 来绘制(可视化)线串和中点,您不必包含它们。但如果您想测试代码并实时查看结果,它们会很有用

// Just for visualizing on canvas (not needed)
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext('2d');
drawLine(points);
//
ctx.beginPath();
ctx.arc(midPoint[0], midPoint[1], 2, 0, 2 * Math.PI);
ctx.closePath();
ctx.fillStyle = "red";
ctx.fill();
//
function drawLine(pnts) {
  pnts.forEach(function(point, i, points) {
    if (i === 0) {
      ctx.beginPath();
      ctx.moveTo(point[0], point[1]);
    } else {
      ctx.lineTo(point[0], point[1]);
    }
    if (i === points.length - 1) {
      ctx.stroke();
    }
  });
}

关于Javascript - 如何计算线串的中点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42371991/

相关文章:

javascript - 使用appendchild在已加载的表数据中动态填充文本列

javascript - 如何编写 AJAX 调用来获取 XML 文件?

javascript - 在 Titanium 中分离平台特定代码的最佳方法

javascript - jquery 迷你图 : box plots and one value

python - 在 GeoDjango 中添加属性

javascript - 如何 sinon spy 模块导出实用函数

google-maps-api-3 - 缩放到Google Maps API v3中的geojson多边形边界

c# - 如何在 C# 中序列化和反序列化 geojson

mapbox - Choropleth 图层 mapbox geojson 不起作用

d3.js - Shapefile 到 TopoJSON 转换问题