I'm really new to angular and TypeScript, I am working on application which uses google maps to find address and I can't store address from geocoder.geocode().
I tried solution from here: How do I return a variable from Google Maps JavaScript geocoder callback?
and it is ok, the alert() is working but what I want to do is to pass address from GeocoderService to a parent component and store it there. I tried to store it in service itself but I can't!
GeocoderService:
initialize() {
this.geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.730885,-73.997383);
this.codeLatLng(function(addr){
this.loc = addr; // <= here i can't store address it is undefined
alert(addr);
return this.loc;
});
}
codeLatLng(callback) {
var latlng = new google.maps.LatLng(40.730885,-73.997383);
if (this.geocoder) {
this.geocoder.geocode({'location': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
callback(results[1].formatted_address);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
}
app.component:
constructor( private geolocationService: GeolocationService,
private geocoderService: GeocoderService){
this.position = {latitude: 0, longitude: 0}
this.LatLng = new google.maps.LatLng( this.position.latitude, this.position.longitude);
}
findMe(){
this.geolocationService.getPosition().then((position: any) => {
this.position = {latitude:position.coords.latitude,longitude: position.coords.longitude}
this.LatLng = new google.maps.LatLng( this.position.latitude, this.position.longitude);
this.map.setCenter(this.LatLng);
this.loc = this.geocoderService.initialize(); //<= here i need this address to be returned and stored
console.log(this.loc) // <= undefined
})
}
app.component.html:
<div #map style= "width:100%;height:400px"></div>
<button (click) = "findMe()">Find me</button>
Please help and sorry if question is dumb