javascript - 如何将坐标的 JSON 数据提供给 turf.polygon?

标签 javascript json turfjs

如何将坐标的JSON数据传给turf.polygon?

示例: turf.polygon();

var polygon = turf.polygon([[
 [-2.275543, 53.464547],
 [-2.275543, 53.489271],
 [-2.215118, 53.489271],
 [-2.215118, 53.464547],
 [-2.275543, 53.464547]
]], { name: 'poly1', population: 400});

示例: JSON 格式

var json = 
{
    "type": "geojson",
    "data": 
        {
         "type": "FeatureCollection",
         "features": [{
               "type": "Feature",
               "geometry": {
                   "type": "Polygon",
                   "coordinates": [[
                         [1.275543, 54.464547], // I want to feed these coordinates
                         [1.275543, 54.489271],
                         [1.215118, 54.489271],
                         [1.215118, 54.464547],
                         [1.275543, 54.464547]  
                    ]]
                }
            }]
       }
 }

我的伪代码: 不起作用并返回错误消息 “LinearRing of a Polygon must have 4 or more Positions.”

var polygon = turf.polygon([[ json.data.features[0].geometry.coordinates ]], { name: 'poly1', population: 400});

谢谢。

最佳答案

coordinates 属性已经是一个深度嵌套的数组:

"coordinates": [[
  [1.275543, 54.464547], // I want to feed these coordinates
  [1.275543, 54.489271],
  [1.215118, 54.489271],
  [1.215118, 54.464547],
  [1.275543, 54.464547]  
]]

当你这样做时:

var polygon = turf.polygon([[
  json.data.features[0].geometry.coordinates
]], ...

它将解析为:

var polygon = turf.polygon([[
  [[
    [1.275543, 54.464547], // I want to feed these coordinates
    [1.275543, 54.489271],
    [1.215118, 54.489271],
    [1.215118, 54.464547],
    [1.275543, 54.464547]  
  ]]
]], ...

您想提取并使用原始嵌套数组本身,而不进行修改。试试这个:

var polygon = turf.polygon(json.data.features[0].geometry.coordinates, { name: 'poly1', population: 400});

关于javascript - 如何将坐标的 JSON 数据提供给 turf.polygon?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50054010/

相关文章:

json - 如何从 Web 应用程序访问仅限身份验证的 Twitter API 方法

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

javascript - 当我刷新并投票时,投票从我的本地存储重新开始。

javascript - 当我不希望它打开时 fancybox 打开

javascript - Anchor Cycler/Dropdown 定期导入学校类(class)数据

php - 从表中获取全部内容

javascript - 从 featureCollection turf.js 中删除功能

javascript - 连接两个边界框 bbox

javascript - 无法读取未定义的属性 'setState' - 转换为箭头函数

javascript - Date() 将某些日期字符串转换为本地时间