angular - 无法访问 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 集合,但我找不到正确的组合。
我需要做什么才能访问坐标?
谢谢.....
解决方案
我需要做什么才能访问坐标?
简答
在尝试访问其属性之前检查geometry
它。Point
coordinates
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];
}
此处有最后一个示例的简短演示。
推荐阅读
- neo4j - 分布式模式下的 Neo4j - 有可能吗?
- angular - 动态更改角度材料 mat-grid-list 中的列值
- php - 在laravel上的每个循环中附加字符串
- azure-devops - 用于将发布管道中的 vsts 构建工件混淆为 VSTS 任务的容器
- android - 更新 Firebase 依赖项时出现 Gradle 构建错误
- swift - 无法将“Promise<[NSDictionary]>”类型的值转换为预期的参数类型“保证”
' - elasticsearch - 如何组合 multi_match 和两个布尔过滤器
- node.js - 如何使用 Google API 服务库 (Node.js) 运行 Google App 脚本
- r - R ggplot,geom_text 在标签命令中舍入标签?
- php - 从 laravel 在 mysql 中插入 DOB