Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse geocoding using Angular 2

Tags:

angular

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;
    }
like image 365
vishnu Avatar asked Oct 08 '16 03:10

vishnu


1 Answers

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");
    }
  }
});
like image 130
Nikhil Shah Avatar answered Oct 08 '22 01:10

Nikhil Shah