问题描述
我正在使用Google的API Geocode,该功能可以正常使用,直到需要使用this.singleGeocode和this.resultsMarker。这是我的组件代码:
interface Location {
lat: number;
lng: number;
}
singleGeocode: Location;
resultsMarkers: Location[];
addresstoCoordinates(addresstoSearch: string) {
this.geoCoder.geocode({ address: addresstoSearch },function ( results,status) {
debugger;
if (status == google.maps.GeocoderStatus.OK) {
let p = results[0].geometry.location;
debugger;
this.singleGeocode.lat = p.lat();
this.singleGeocode.lng = p.lng();
this.resultsMarkers.push(this.singleGeocode);
}
});
}
那是我的HTML代码:
<agm-map [latitude]="startingLat" [longitude]="startingLng" [zoom]="startingZoom" (zoomChange)="onZoomChange($event)">
<div *ngIf="selectedZoom > 4">
<agm-marker-cluster imagePath="https://raw.githubusercontent.com/googlemaps/v3-utility-library/master/markerclustererplus/images/m" [minimumClusterSize]="2">
<agm-marker *ngFor="let m of resultsMarkers; let i = index"
(markerClick)="clickedMarker(m.label,i)"
[latitude]="m.lat"
[longitude]="m.lng"
[label]="test"
[markerDraggable]="false">
</agm-marker>
</agm-marker-cluster>
</agm-map>
如何使函数读取我的此参数,以便我的HTML会使用它?或者如何更改代码以使其正常工作?
编辑: 我尝试放置绑定,但是这些参数仍未定义。
this.geoCoder.geocode({ address: addresstoSearch },function (results,status) {
debugger;
if (status == google.maps.GeocoderStatus.OK) {
let p = results[0].geometry.location;
debugger;
this.singleGeocode.lat = p.lat();
this.singleGeocode.lng = p.lng();
this.resultsMarkers.push(this.singleGeocode);
}
}.bind(this));
}
此外,我尝试了=>,但仍未定义:
this.geoCoder.geocode({ address: addresstoSearch },(results,status) => {
debugger;
if (status == google.maps.GeocoderStatus.OK) {
let p = results[0].geometry.location;
debugger;
this.singleGeocode.lat = p.lat();
this.singleGeocode.lng = p.lng();
this.resultsMarkers.push(this.singleGeocode);
}
});
}
我想念什么?
解决方法
您要在为singleGeocode
和resultsMarkers
赋值之前初始化它们吗?如果不是这样,则可能是问题所在。查看它是否有助于如下修改代码:
interface Location {
lat: number;
lng: number;
}
// class starts here
singleGeocode: Location;
resultsMarkers: Location[] = []; // new
addressToCoordinates(addressToSearch: string) {
this.geoCoder.geocode({ address: addressToSearch },function(
results,status
) {
if (status == google.maps.GeocoderStatus.OK) {
let p = results[0].geometry.location;
// new
this.singleGeocode = {
lat: p.lat(),lng: p.lng()
};
this.resultsMarkers.push(this.singleGeocode);
}
});
}