首页 > 解决方案 > 如何动态创建多多边形数组?

问题描述

我的目标是构建一个turf.js多多边形。这种硬编码工作正常:

const searchWithin = turf.multiPolygon(
[
    [[
        [-0.607051, 44.840753], 
        [-0.543708, 44.832962], 
        [-0.52225, 44.820544], 
        [-0.566367, 44.808853], 
        [-0.586367, 44.788853], 
        [-0.607051, 44.840753]
    ]],
    [[
        [5.39014, 43.279295], 
        [5.393069, 43.279249], 
        [5.391814, 43.278421], 
        [5.390709, 43.278749], 
        [5.3909, 43.2785], 
        [5.39014, 43.279295]
    ]]
]);

如您所见,在获取坐标数组之前有 3 级括号。来自数据库,我得到:

[
    [
        [-0.607051, 44.840753], 
        [-0.543708, 44.832962], 
        [-0.52225, 44.820544], 
        [-0.566367, 44.808853], 
        [-0.586367, 44.788853], 
        [-0.607051, 44.840753]
    ],
    [
        [5.39014, 43.279295], 
        [5.393069, 43.279249], 
        [5.391814, 43.278421], 
        [5.390709, 43.278749], 
        [5.3909, 43.2785], 
        [5.39014, 43.279295]
    ]
]

从数据库中获取数据:

.subscribe((response) => {
      this.locations = response;
      this.polygonsArray.push(this.locations);
      this.locations.forEach(element => {          
this.polygons.push(element.geoDefinition.features['0'].geometry.coordinates);

多边形声明为:

polygons: number[][][] = [];

我试过了:

this.polygons.push('['+element.geoDefinition.features['0'].geometry.coordinates)+']';

但坐标是数字,所以我无法连接。

请问这个结构有3个方括号,我该怎么做?任何帮助都会非常有帮助。

我提前感谢您的帮助。

标签: angulartypescriptgeojsonturfjs

解决方案


目前尚不清楚预期的结构。但首先值得注意的是:

  1. 如果多边形是 3 维数组polygons: number[][][] = [];,则不能直接向其推送数字,例如polygons.push(5),您必须考虑结构:

polygons[0][0].push(5)polygons.push([[5]])

  1. 另一件事是this.polygonsArray.push(this.locations);- 它至少应该this.polygonsArray.push(...this.locations);像 push 一样将整个this.locations数组添加为this.polygonsArray.

  2. 最后一个。如果你推送类似的东西this.polygons.push('['+something+']');- 你只需将一个字符串推送到简单数组。取而代之的是,您可以使用

    this.polygons[0].push(something);

希望它可以为您提供一些如何组织 3 维结构的想法。


推荐阅读