我有使用angular的离子应用程序。我正在尝试从JSon API URL获取对象,从服务器获取纬度和经度的内容。对象密钥上的数据json api内容和这些密钥一直在变化。我只想获取这些“对象”键内部的坐标,然后将其添加到Google地图标记中以在地图上显示。
我的代码
export class HomePage implements OnInit {
point:any
Data :any
map: GoogleMap;
constructor(private http : HTTP) {}
ngOnInit(){
this.getData()
}
//// Getting json response ////
getData(){
this.http.get("xxxxxxx", {}, {}).then(data =>{
this.Data = JSON.parse(data.data)
this.point= Object.keys(this.Data).map(key => this.Data[key].airport.position).map(({
latitude,
longitude
}) => ({
lat: latitude,
lng: longitude
}))
console.log(this.point)
}).then(()=>{
this.loadMap()
})
}
//// inject coordinates into google map ////
loadMap() {
this.map = GoogleMaps.create('map_canvas');
////// icon marker here ////
let marker: Marker = this.map.addMarkerSync({
title: 'Ionic',
icon: 'blue',
animation: 'DROP',
position: this.point
});
}
}
简杰森
{
"ABQ": {
"airport": {
"name": "Albuquerque International Airport",
"code": {
"iata": "ABQ",
"icao": "KABQ"
},
"position": {
"latitude": 35.040218,
"longitude": -106.609001,
"altitude": 5355
}
}
},
"ACE": {
"airport": {
"name": "Lanzarote Airport",
"code": {
"iata": "ACE",
"icao": "GCRR"
},
"position": {
"latitude": 28.945459,
"longitude": -13.6052,
"altitude": 47
}
}
}
}
当我运行我的应用程序时,我在地图上什么也没有,也没有标记,控制台也没有错误显示。
答案 0 :(得分:2)
点变量的问题是因为它是点详细信息的数组。您必须一个接一个地添加所有标记,在这里我指出出现问题的确切位置。
let marker: Marker = this.map.addMarkerSync({
title: 'Ionic',
icon: 'blue',
animation: 'DROP',
position: this.point // issue in here because trying to make the position by an array
});
解决方案是定义一个函数,通过遍历点数组中的每个点来添加标记,我将其重命名为解决方案的点,因为它很有意义。
// You can use forEach as well on points
for(var i = 0; this.points.length; i++){
addMarker(points[i]);
}
addMarker(point: any){
return this.map.addMarkerSync({
title: 'Ionic',
icon: 'blue',
animation: 'DROP',
position: point
});
}
完整代码更新如下,
import { HttpClient } from '@angular/common/http';
export class HomePage implements OnInit {
points: Array<any> = [];
Data: any;
map: GoogleMap;
constructor(private http: HttpClient) { }
ngOnInit() {
this.loadMap();
this.getData();
}
loadMap() {
this.map = GoogleMaps.create('map_canvas');
}
getData() {
this.http.get("<URL>").
subscribe((data) => {
this.Data = JSON.parse(data.data);
this.points = Object.keys(this.Data)
.map(key => this.Data[key].airport.position)
.map((position) => ({
lat: position.latitude,
lng: position.longitude
}));
this.points.forEach((point) => {
this.addMarker(point);
});
});
}
addMarker(point: any) {
return this.map.addMarkerSync({
title: 'Ionic',
icon: 'blue',
animation: 'DROP',
position: point
});
}
}