Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angular - Get current position in ionic2

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;
    }

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.

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

Thank you

EDITED

 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 
        };
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/

EDIT:

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

  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.

  2. 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
    }
    

EDIT 2:

A working example would be:

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
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...