使用Angular 2进行反向地理编码

5

我正在使用Angular 2进行反向地理编码,它工作正常,但是我无法使用服务(setter和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);
          }
        }
}

如果我尝试使用服务进行设置, this.shareService.setLocationDetails(city); 我会收到错误提示,

app.ts:303 Uncaught TypeError: Cannot read property 'shareService' of undefined

这项服务:

locationObj: any;
setLocationDetails(locationObj){
      this.locationObj = locationObj;
    }
    getLocationDetails(){
      return this.locationObj;
    }

请在此处提及您使用的包和导入。 - Vijender Kumar
3个回答

6

我认为一切都很好。但是,我建议您使用如下所示的箭头函数()=>

// 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");
    }
  }
});

谢谢你告诉我们使用箭头函数。但是为什么普通函数不起作用? - Usman Iqbal

0

geocoder.geocode(request, (results, status) => {....} 在 'results' 上出现了一个错误,提示{'latLng' : latlng}与结果类型不对应。

解决方案:

  var geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(this.eventLat, this.eventLng);
  let request = {
    location: latlng
  };
  geocoder.geocode(request, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {
            console.log(results[1].formatted_address);

        } else {
            console.log('Location not found');
        }
    } else {
        console.log('Geocoder failed due to: ' + status);
    }
});

0

我没有足够的声望来评论 :-(,所以我将Usman Iqbal的问题作为答案回答。也许一些管理员可以将其转换为评论。

隐式回调函数创建一个名为闭包的结构:一个包含实际函数及其创建上下文的对象。该上下文包含所有“环绕”回调的变量及其在创建函数时的值。闭包不包含上下文的this值,因为它本身就是一个对象,并且在执行回调时具有自己的this

为了使创建上下文的this直接可用,箭头函数根据定义处理this,使其不是闭包的this,而是创建上下文的this。如果没有箭头函数,您可以通过显式地将周围的this复制到闭包的上下文中来实现相同的效果:

let self = this; // this of the creation context

geocoder.geocode(request, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        if (results[0] != null) {
            ...
            // access the surrounding this via self
            self.shareService.setLocationDetails(city);
        } 
        ...
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接