我正在OpenLayers(6)中使用Angular(4.6.5)编制地图。我还使用法国政府提供的法语API来创建请求并返回GeoJSON文件。
我已经用这样的静态GeoJSON文件编写了一个地图:
this.parkingLayer = new VectorSource({
url: '.../file.geojson',
format: new GeoJSON()
});
this.vectorLayer_parking = new VectorLayer({
source: this.parkingLayer
});
现在我想使用这个API并动态创建请求! 我创建了一个StackBlitz来说明我的问题。
我的问题是我在ngOnInit()之外创建了一个getLocation()函数(这是强制性的),现在我想使用const url = 'https://api-adresse.data.gouv.fr/reverse/?lon=${Longitude}&lat=${Latitude}'
中的this.locationLayer
!我怎样才能做到这一点 ?目标是将点放在地图上(根据生成的GeoJSON文件)
答案 0 :(得分:0)
您可以使用Angular HttpClient处理http请求。
首先在app.module中导入HttpClientModule
import { HttpClientModule} from '@angular/common/http';
@NgModule({
imports: [
...,
HttpClientModule
],
...
})
在您的app.component中,从服务器
中获取信息import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient) {this.getLocation();}
getLocation(): void{
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position)=>{
const longitude = position.coords.longitude;
const latitude = position.coords.latitude;
this.callApi(longitude, latitude).subscribe(n => {
console.log(n);
//here you can add the geometry to a vector source
});
});
} else {
console.log("No support for geolocation")
}
}
callApi(Longitude: number, Latitude: number): Observable<any> {
const url = `https://api-adresse.data.gouv.fr/reverse/?lon=${Longitude}&lat=${Latitude}`;
return this.http.get(url)
}
使用openlayers创建VectorSource后,获取服务器信息后,在源上添加几何