首页 > 解决方案 > 无法访问 geojson 特征集合的“坐标”成员

问题描述

我的 Angular 应用程序中有一个 GeoJSON 功能集合,它是一组功能,每个功能都包含一个几何对象和属性对象。结构如下所示:

import { FeatureCollection, Feature } from 'geojson';

staticBreadcrumbs: GeoJSON.FeatureCollection<GeoJSON.Geometry>;

this.staticBreadcrumbs = {
    type : 'FeatureCollection',
    features: [
    {
        type: 'Feature',
        properties: {
            property1:  'property1',
            property2:  'property2'
        },
        geometry: {
            type: 'Point',
            coordinates: [-117.14024305343628, 32.81294345855713]
        }
    },
    {
        type: 'Feature',
        properties: {
        ...

我正在尝试为集合中的每个功能创建一个 mapboxgl 标记,并且需要从每个 GeoJSON 对象获取坐标,编译器告诉我坐标不是功能的一部分。具体错误是:“几何”类型上不存在属性“坐标”。类型“GeometryCollection”上不存在属性“坐标”。

console.log('this.staticBreadcrumbs.features[0]', this.staticBreadcrumbs.features[0]);

var marker = new Marker(el)
    .setLngLat([
        this.staticBreadcrumbs.features[0].geometry.coordinates[0],
        this.staticBreadcrumbs.features[0].geometry.coordinates[1]
    ])
    .addTo(this.map);

我的 console.log 显示

 this.staticBreadcrumbs.features[0]
 {type: "Feature", properties: {…}, geometry: {…}}
 1.  geometry:
     1.  coordinates: Array(2)
         1.  0: -117.14024305343628
         2.  1: 32.81294345855713
         3.  length: 2
         4.  __proto__: Array(0)
     2.  type: "Point"
   2. __proto__: Object
2. properties: {deviceID: "CAP498", altitude: 401.6721913312, autonomous: 0, azimuth: 0, batteryStatusLabel: "Nominal", …}
3. type: "Feature"
4. __proto__: Object

坐标正是我期望的位置,但我无法找到它们。我尝试了各种不同的方式来声明 Feature 集合,但我找不到正确的组合。

我需要做什么才能访问坐标?

谢谢.....

标签: angulartypescriptgeojson

解决方案


我需要做什么才能访问坐标?

简答

在尝试访问其属性之前检查geometry它。Pointcoordinates

if (staticBreadcrumbs.features[0].geometry.type === 'Point') {

    var marker = new Marker(el)
        .setLngLat([
            this.staticBreadcrumbs.features[0].geometry.coordinates[0],
            this.staticBreadcrumbs.features[0].geometry.coordinates[1]
        ])
        .addTo(this.map);

}

解释

您遇到的问题是因为Geometry 是 union type

联合类型描述的值可以是多种类型之一。我们使用竖线 ( |) 来分隔每种类型...

这是Geometry联合类型定义:

export type Geometry = 
    Point |
    MultiPoint | 
    LineString | 
    MultiLineString | 
    Polygon | 
    MultiPolygon | 
    GeometryCollection;

如您所见,该Geometry类型是七种类型的并集。不幸的是,并非所有这些类型都包含该coordinates属性。

如果我们有一个联合类型的值,我们只能访问联合中所有类型共有的成员。

这就是为什么我们只能coordinates在缩小类型后才能访问该属性。

其他一些选项

如果您在 中仅使用Point类型FeatureCollection,则使用该Point类型作为泛型参数:

let staticBreadcrumbs: FeatureCollection<Point>;

如果您在 中使用多种类型,请FeatureCollection使用强制转换告诉类型检查器您确定您有Point

(staticBreadcrumbs.features[0].geometry as Point).coordinates[0]

简短答案中所示,您可以使用条件语句来缩小类型,而不是使用强制转换:

const geometry = staticBreadcrumbs.features[0].geometry;

if (geometry.type === 'Point') {
    const coordinates00 = geometry.coordinates[0];
    const coordinates01 = geometry.coordinates[1];
}

此处有最后一个示例的简短演示。


推荐阅读