加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:39:53 所属栏目:安全 来源:网络整理
导读:我使用Angular 2进行反向地理编码,它工作正常,但我无法使用服务(setter和getter)设置值(即城市名称) import { ShareService } from './services/ShareService';class ConferenceApp { constructor(public shareService: ShareService){ this.getGeoLocation(
我使用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(市);
我收到错误说,

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

服务:

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

解决方法

我觉得一切都很好.但是,我建议你使用arrowfunction()=>如下所示,

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读