获取 ionic2 中的当前位置 [英] Get current position in ionic2

查看:16
本文介绍了获取 ionic2 中的当前位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Ionic 2 的新手,正在学习一些教程.

I am new to Ionic 2 and following some tutorials.

在这种情况下,我需要更改以下方法:

In this case I need to change following method:

 applyHaversine(locations){

        let usersLocation = {


            lat: 40.713744, 
            lng: -74.009056
        };

        locations.map((location) => {

            let placeLocation = {
                lat: location.latitude,
                lng: location.longitude
            };

            location.distance = this.getDistanceBetweenPoints(
                usersLocation,
                placeLocation,
                'miles'
            ).toFixed(2);
        });

        return locations;
    }

可以看到变量 usersLocation 是硬编码的:

You can see that variable usersLocation is hard-coded:

let usersLocation = {


            lat: 40.713744, 
            lng: -74.009056
        };

我想获得真实的用户位置.

I would like to get there the real user location.

我见过 Geolocation.getCurrentPosition() 方法,但我不知道在这种情况下如何实现它.

I have seen the method Geolocation.getCurrentPosition(), but I don´t know how to implement it in this case.

谢谢

已编辑

 applyHaversine(locations){
        Geolocation.getCurrentPosition().then((resp) => {

        let  latitud = resp.coords.latitude
        let longitud = resp.coords.longitude
        }).catch((error) => {
          console.log('Error getting location', error);
        });

  console.log(this.latitud);
        let usersLocation = {

           lat:  this.latitud, 
           lng:  this.longitud 
        };

推荐答案

我会使用 Geolocation cordova 插件.您可以使用 ionic-native 访问它.首先你需要安装插件:

I would use the Geolocation cordova plugin. You can access it with ionic-native. First you need to install the plugin:

$ ionic plugin add cordova-plugin-geolocation --save

然后你可以像这样使用它:

You can then use it like this:

import { Geolocation } from 'ionic-native';

Geolocation.getCurrentPosition().then(res => {
  // res.coords.latitude
  // res.coords.longitude
}).catch((error) => {
  console.log('Error getting location', error);
});

https://ionicframework.com/docs/v2/native/geolocation/

您更新的代码几乎是正确的.您在代码中犯了 2 个小错误:

Your updated code is almost correct. You made 2 small mistakes in your code:

  1. 您定义了 2 个局部变量(let latitudlet longitud),但随后在您的代码中您使用 this.latitud 访问它们this.longitud.this 总是引用在你的类中定义的变量,所以这些变量是未定义的.您必须使用局部变量或类范围变量,但这取决于您的体系结构.两者都有效.

  1. You defined 2 local variables (let latitud and let longitud), but then later in your code you access them by using this.latitudand this.longitud. this always refers to variables defined in your class, so those will be undefined. You either have to use local variables or class wide variables, but that depends on your architecture. Both work.

Geolocation.getCurrentPosition() 返回一个承诺.这意味着 .then(() => {}) 中的代码将在稍后执行(只要插件具有您的位置的结果).但是您的其余代码在 then 之外,这意味着它将在您获得位置之前执行.因此,您需要将整个代码复制到 then 中,如下所示:

Geolocation.getCurrentPosition() returns a promise. This means that the code inside .then(() => {}) will be executed later (as soon as the plugin has the result with your location). But the rest of your code is outside the then, which means that it will be executed before you have the location. So you need to copy your whole code into the then like this:

applyHaversine(locations) {
  Geolocation.getCurrentPosition().then(res => {
    let usersLocation = {
      lat: res.coords.latitude, 
      lng: res.coords.longitude
    };

    locations.map((location) => {

      let placeLocation = {
        lat: location.latitude,
        lng: location.longitude
      };

      location.distance = this.getDistanceBetweenPoints(
        usersLocation,
        placeLocation,
        'miles'
      ).toFixed(2);
    });

  console.log(locations); // This will now have your updated distances

  }).catch((error) => {
    console.log('Error getting location', error);
  });

  return locations; // this will not work because the code above is asynchronous
}

编辑 2:

一个可行的例子是:

applyHaversine(locations) {
  return new Promise((resolve, reject) => {
    Geolocation.getCurrentPosition().then(res => {
      let usersLocation = {
        lat: res.coords.latitude, 
        lng: res.coords.longitude
      };

      locations.map((location) => {

        let placeLocation = {
          lat: location.latitude,
          lng: location.longitude
        };

        location.distance = this.getDistanceBetweenPoints(
          usersLocation,
          placeLocation,
          'miles'
        ).toFixed(2);
      });

    resolve(locations); // As soon as this is called, the "then" in will be executed in the function below.

    }).catch(reject);
  });
}

以及你在哪里使用这个功能:

And where you use this function:

doSomething(locations) {
  this.applyHaversine(locations).then(res => {
    // The logic after you have your new results goes here.
    console.log(res); // res will be the value that you passed into the resolve function above, in this case your updated locations array
  }
}

这篇关于获取 ionic2 中的当前位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆