【问题标题】:Geolocation value retuned from service is undefined从服务返回的地理位置值未定义
【发布时间】:2021-05-10 04:50:34
【问题描述】:

我已将地理定位调用置于我想在应用程序的不同区域使用的服务中。但是,未定义正在被返回。如何正确返回值以便检索?

服务代码

   getUserPosition() {
     this.geolocation.getCurrentPosition().then((position) => {
    this.latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    this.currentLat = position.coords.latitude;
    this.currentLng = position.coords.longitude;
    return this.latLng;

    }, (err) => {
      console.log('There was an error');
    });
  }

从服务调用这个函数

  async ngOnInit() {
    // Since ngOnInit() is executed before `deviceready` event,
    // you have to wait the event.
    await this.platform.ready();
    await this.loadMap();

   this.val =  await this.location.getUserPosition(); 
   console.log("I should be here val "+ this.val);
  }

【问题讨论】:

  • 你能发布完整的 SSCCE 吗?

标签: angular google-maps service ionic3 google-geolocation


【解决方案1】:

从函数返回详细信息

async getUserPosition() {
    await this.geolocation.getCurrentPosition().then((position) => {
      this.latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
      this.currentLat = position.coords.latitude;
      this.currentLng = position.coords.longitude;
      this.locationData = [this.latLng, this.currentLat, this.currentLng];
    }, (err) => {
      console.log('There was an error' + err.message);
    });
    // return all the details returned from the location
    return this.locationData;
  }

使用返回的详细信息

   this.geolocationData = await this.location.getUserPosition();
    this.latLng = this.geolocationData[0];
    this.currentLat = this.geolocationData[1];
    this.currentLng = this.geolocationData[2];

【讨论】:

    【解决方案2】:

    您似乎没有在 getUserPosition 函数中返回任何内容。你看,return this.latLng;then 的结果,而不是getUserPosition 的结果。为了解决这个问题,你可以等到 promise 完成然后返回值:

    async getUserPosition() {
        try {
            const position = await this.geolocation.getCurrentPosition();
            this.latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            this.currentLat = position.coords.latitude;
            this.currentLng = position.coords.longitude;
            return this.latLng;
        }, (err) => {
          console.log('There was an error');
        });
    }
    

    我强烈建议使用 typescript 来避免这种类型的错误——如果你正确地为函数添加类型,编译器会告诉你函数应该返回一个特定的类型,但会尝试返回 void

    【讨论】:

    • 我曾尝试从 getUserPosition 函数返回它,但它仍然说未定义。但是,我能够找到我发布的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    • 2012-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多