Reputation: 551
I'm working with API Geocode of Google, and the function works fine until I need to use this.singleGeocode and this.resultsMarker. This is my component code:
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);
}
});
}
That's my HTML code:
<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>
How can make the function read my this parameters, so my HTML will use it? Or how I can change my code to make it work?
EDIT: I tried to put the bind, but those parameters are still undefined.
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));
}
Also, I tried with => but still undefined:
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);
}
});
}
What am I missing?
Upvotes: 1
Views: 67
Reputation: 5691
Are you initializing singleGeocode
and resultsMarkers
before you assign them values? If not then this is likely the problem. See if it helps modifying your code as below:
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);
}
});
}
Upvotes: 1