我正在与angular2-google-maps
以及最新版本的 Angular2。我正在尝试将一些本地地图组件功能转换为自己文件中的服务maps.service.ts
。例如:
地图组件.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;
服务类别之外也是如此。
The google
变量在我的工作map.componenet.ts
但没有得到认可maps.service.ts
.
Angular 6 和 7 步骤(也应该适用于所有其他 Angular 版本):
npm install @types/googlemaps --save-dev
- Add
googlemaps
到两个文件中的类型数组tsconfig.app.json
分别在tsconfig.spec.json
(保存两个文件)
- 在controller.ts的顶部
/// <reference types="@types/googlemaps" />
- 重新启动 npm 服务器
The types
两个文件中的数组应该类似于这些
{
"compilerOptions": {
"types": ["googlemaps","othertype",...]
}
}
您可以从组件中删除这两种声明类型:import {} from '@types/googlemaps';
declare var google: any;
您不必包含其中任何一个。
PS:如果您使用 agm-s GoogleMapsAPIWrapper.getNativeMap(),则必须在使用之前转换地图对象。例如开启流量层:
this.apiWrapper.getNativeMap().then(map => {
this.trafficLayer = new google.maps.TrafficLayer();
const gMap: any = map;
this.trafficLayer.setMap(gMap as google.maps.Map);
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)