gpt4 book ai didi

google-maps - Angular2 找不到命名空间 'google'

转载 作者:太空狗 更新时间:2023-10-29 16:50:20 25 4
gpt4 key购买 nike

我正在使用 angular2-google-maps和最新版本的 Angular2。我正在尝试将一些本地 map 组件功能转换为它们自己文件中的服务 maps.service.ts .例如:

map .component.ts

getGeoLocation(lat: number, lng: number) {
if (navigator.geolocation) {
let geocoder = new google.maps.Geocoder();
let latlng = new google.maps.LatLng(lat, lng);
let request = { latLng: latlng };
geocoder.geocode(request, (results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
let result = results[0];
if (result != null) {
this.fillInputs(result.formatted_address);
} else {
alert("No address available!");
}
}
});
}
}

变成这样的东西:maps.service.ts

getGeoLocation(lat: number, lng: number): Observable<google.maps.GeocoderResult[]> {
let geocoder = new google.maps.Geocoder();
let latlng = new google.maps.LatLng(lat, lng);
let request = { latLng: latlng };
return new Observable((observer: Observer<google.maps.GeocoderResult[]>) => {
geocoder.geocode({ request }, (
(results: google.maps.GeocoderResult[], status: google.maps.GeocoderStatus) => {
if (status == google.maps.GeocoderStatus.OK) {
observer.next(results);
observer.complete();
} else {
console.log('Geocoding service failed due to: ' +status);
observer.error(status);
}
}
));
});
}

我遇到的问题是 google当我尝试使用 Observer<google.maps.GeocoderResult[]> 时无法识别变量.我有declare var google: any;也在服务类之外。

google变量在我的 map.componenet.ts 中有效但在 maps.service.ts 中未被识别.

最佳答案

Angular 6 和 7 步骤(也应该适用于所有其他 Angular 版本):

  1. npm install @types/googlemaps --save-dev
  2. 分别在 tsconfig.spec.json 中将 googlemaps 添加到两个文件 tsconfig.app.json 的类型数组中(保存两个文件)
  3. 在 controller.ts 的顶部
/// <reference types="@types/googlemaps" />
  1. 重启 npm 服务器

types 数组在两个文件中应该看起来像这样

{ 
"compilerOptions": {
"types": ["googlemaps","othertype",...]
}
}

You can delete both declaration types from the components: import {} from '@types/googlemaps'; declare var google: any; You don't have to include any of them.

PS:如果您正在使用 agm-s GoogleMapsAPIWrapper.getNativeMap(),您必须在使用之前转换 map 对象。例如开启交通层:

this.apiWrapper.getNativeMap().then(map => {
this.trafficLayer = new google.maps.TrafficLayer();
const gMap: any = map;
this.trafficLayer.setMap(gMap as google.maps.Map);
});

关于google-maps - Angular2 找不到命名空间 'google',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42394697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com