我的Angular项目中的Geocoder
由于未定义而崩溃。我尝试了这个:
Getting 'Uncaught TypeError: Cannot read property 'geocode' of undefined ' error
但是如果我首先对其进行初始化或分配,它将不起作用。两者都不起作用。
我的代码,第一行出现错误:
private geoCoder = new google.maps.Geocoder();
@ViewChild('search', { static: false })
public searchElementRef: ElementRef;
constructor(private maps: MapsAPILoader, private ngZone: NgZone){ }
ngOnInit() {
// Load places autocomplete
this.maps.load().then(() => {
this.setCurrentLocation();
let autocomplete = new google.place.Autocomplete(this.searchElementRef.nativeElement, {
types: ["address"]
});
autocomplete.addListener("place_changed", () => {
this.ngZone.run(() => {
// Get the place result
let place: google.maps.places.PlaceResult = autocomplete.getPlace();
// Verify result
if (place.geometry === undefined || place.geometry === null) {
return;
}
// Set latitude, longitude & zoom
this.userLat = place.geometry.location.lat();
this.userLng = place.geometry.location.lng();
this.zoom = 12;
});
});
});
}
// Get Current Location Coordinates
private setCurrentLocation() {
if ('geolocation' in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
this.userLat = position.coords.latitude;
this.userLng = position.coords.longitude;
this.zoom = 15;
});
}
}
getaddress(latitude, longitude) {
this.geoCoder.geocode({ "location": { lat: latitude, lng: longitude } }, (results, status) => {
console.log(results);
console.log(status);
if (status === "Ok") {
if (results[0]) {
this.zoom = 12;
this.address = results[0].formatted_address;
} else {
window.alert("No results found.");
}
} else {
window.alert("Something went wrong, please try again.");
}
});
}
从(向下滚动到“添加位置/地点搜索”栏):
如何防止崩溃?谢谢!
答案 0 :(得分:0)
等待地图加载器,然后在Geocoder()
中分配ngOnInit()
:
this.mapsAPILoader.load().then(() => {
this.setCurrentLocation();
this.geoCoder = new google.maps.Geocoder;
.....
}
请确保安装:
npm install @types/googlemaps --save-dev
编辑:
正确导入module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AgmCoreModule } from '@agm/core';
import { AppComponent } from './app.component';
@NgModule({
imports: [
AgmCoreModule.forRoot({
apiKey: 'AIzaSyCnn-_D68N95BaSpYRYn1E3N_DHGs1vz0Y',
libraries: ["places"]
}),
BrowserModule,
FormsModule,
ReactiveFormsModule
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
答案 1 :(得分:0)
自Geocoder
初始化以来,尚未加载Google Maps API,因此发生了错误。在Angular Google Maps库MapsAPILoader
中,可以利用服务来确保Google Maps API已加载,然后初始化Geocoder
:
this.mapsAPILoader.load().then(() => {
this.geoCoder = new google.maps.Geocoder;
});
下面是一个示例(改编自official Geocoding Service example),该示例演示了如何将Goolge Maps地理编码服务与Angular Google Maps一起使用
export class AppComponent implements OnInit {
center = {lat: -34.397, lng: 150.644};
position= {lat: null, lng: null};
zoom: number = 8;
address: string;
private geoCoder;
constructor(
private mapsAPILoader: MapsAPILoader,
private ngZone: NgZone
) { }
ngOnInit() {
this.mapsAPILoader.load().then(() => {
this.geoCoder = new google.maps.Geocoder;
});
}
geocodeAddress(addressInput) {
const address = addressInput.value;
this.geoCoder.geocode({'address': address}, (results, status) => {
if (status === 'OK') {
this.position = {
"lat": results[0].geometry.location.lat(),
"lng": results[0].geometry.location.lng()
}
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
}
这是demo
答案 2 :(得分:0)
您需要确保您具有正确的import语句并使用正确的库。
由于Geocoder并未在@agm
中定义,而是在@types/googlemaps
中定义,如果没有npm install --save @types/googlemaps
,则需要下载。
使用以下导入语句:import { } from 'googlemaps';
制成此文件后,将index.d.ts
放在src
文件夹或根目录下,并在其中声明以下内容:
index.d.ts
declare module "googlemaps";
并确保将您的Geocoder放在括号中:Geocoder()
。
这应该可以解决问题,就像对我一样。