如何操作 LatLng 对象?

How to manipulate LatLng objects?

我 运行 向数据库发出请求并获取(如控制台中的 JSON.Stringify() 所示:

sites : [{"siteName":"Site de Marseille",
"siteAdress1":"rue du string",
"siteAddress2":"string",
"siteCodPost":"13010","siteTown":"Marseille",
"id":"5d0ce7c4a06b07213a87a753",
"companyId":"5cd430745304a21b9464a219",
"customerId":"5cd430c65304a21b9464a21a",
"points":
[
 {"lat":44.841225,"lng":-0.580036},
 {"lat":44.842236,"lng":-0.64696},    
 {"lat":44.805615,"lng":-0.63084}]}
]

这是一条有一些属性的记录,一条属性是一个Lat/Lng的数组。 要获取此记录,我有以下代码:

 this.customerApi.getSites(this.currentUser.id)
.subscribe(response => {
  this.sites = response;
  console.log('sites : ' + JSON.stringify(this.sites));
});
  }

我正在控制台中显示一个 Observable()。

我想获取 Point 属性 并将其推送到一个数组数组中,因为它可能存在后端发回的许多记录。 目标是拥有可以在 Google Map 上绘制多边形的嵌套坐标 Angular Google Map angular component

为此,我声明:

rectangles: Array<Array<LatLngLiteral>> = [];

并在 "subscribe" 下执行:

.subscribe(response => {
  this.sites = response;
  this.rectangles.push(this.sites.points); 

矩形是空的。

有什么可以帮助我的想法吗?

在此先感谢您的帮助。

我在你的数据结构中看到 sites 是一个数组。所以如果你做 this.sites.points 它将是 undefined.

你要的是:this.rectangles.push(this.sites.map(s => s.points))

不同之处在于您尝试访问数组上的 属性 sites。 数组没有 属性,因此它是未定义的。数组构建在数据结构中,具有一组已定义的函数和属性,例如 lengthmap

例如:

const exampleObject = {propertyA: "value", propertyB: "another value" }

//access properties on object

//"value"
exampleObject.propertyA

//"another value"
exampleObject.propertyB

const exampleArray = ["one", "two", "three"]

//propertyA does not exists = undefined
exampleArray.propertyA

//lenght property exists on all arrays = 3
exampleArray.length

数组确实有一个名为 map 的函数,这意味着对每个元素调用一个函数,并 return 一个新数组。它通常用于转换数据结构或获得更深的嵌套元素。

这只是 shorthand:

this.sites.map(s => s.points)

其实是这个意思:

const pointsArray = this.sites.map(s => {
       //s is a single element in sites array
       // s has property points which is an array
       return s.points
    })


// now we have an array of points, we can add it to rectangles

this.reactangles.push(pointsArray)

希望现在更清楚了。