I am using reverse geocoding using Angular 2, it is working fine but i am not able to set the values(i.e, city name) using service(setter and getter)
import { ShareService } from './services/ShareService';
class ConferenceApp {
constructor(public shareService: ShareService){
this.getGeoLocation();
}
public getGeoLocation(){
if (navigator.geolocation) {
var options = {
enableHighAccuracy: true
};
navigator.geolocation.getCurrentPosition(position=> {
this.lat = position.coords.latitude;
this.long = position.coords.longitude;
let geocoder = new google.maps.Geocoder();
let latlng = new google.maps.LatLng(this.lat, this.long);
let request = {
latLng: latlng
};
geocoder.geocode(request, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0] != null) {
let city = results[0].address_components[results[0].address_components.length-4].short_name;
this.shareService.setLocationDetails(city);
} else {
alert("No address available");
}
}
});
}, error => {
console.log(error);
}, options);
}
}
}
if i try to set using service, this.shareService.setLocationDetails(city); I am getting error saying,
app.ts:303 Uncaught TypeError: Cannot read property 'shareService' of undefined
The service:
locationObj: any;
setLocationDetails(locationObj){
this.locationObj = locationObj;
}
getLocationDetails(){
return this.locationObj;
}
I think everything is fine. But, I'd suggest you to use arrowfunction()=>
as shown below,
// Removed function keyword and added arrow function
geocoder.geocode(request, (results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0] != null) {
let city = results[0].address_components[results[0]
.address_components.length-4].short_name;
this.shareService.setLocationDetails(city);
} else {
alert("No address available");
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With