3

I want to get the current position of the user and calculate the distance between this position and others positions. I am using this tutorial : Create a Nearby Places List with Google Maps in Ionic 2. This is the code:

let usersLocation;
Geolocation.getCurrentPosition().then((position) => {

   usersLocation = { lat :position.coords.latitude ,  lng : position.coords.longitude }
   locations.map((location) => {

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

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

});

The problem is : The usersLocation variable is not set with the latitude and the longitude of the current user's postion. Can you help me!!

6
  • Your .then function is only used when successful outcome of calling getCurrentPosition. You should have a good way to catch errors, using error function: developers.google.com/web/fundamentals/getting-started/primers/…. The error function will help you determine what failure may be happening when calling getCurrentPosition(). I bet your getting an error from calling getCurrentPosition() and are eating it. Commented Mar 10, 2017 at 17:52
  • I used the method indicated in the link above , but it does not enter in the 2 cases success or error. I am calling the function getCurrentPosition() in another provider and it work fine. Commented Mar 10, 2017 at 18:18
  • Does your config.xml have feature allowing permissions for gps Commented Mar 10, 2017 at 18:49
  • No. It does not have that feature. Commented Mar 10, 2017 at 18:53
  • Make sure you've followed cordova.apache.org/docs/en/latest/reference/… to enable using gps. Commented Mar 10, 2017 at 18:56

2 Answers 2

13
calculateDistance(lat1:number,lat2:number,long1:number,long2:number){
    let p = 0.017453292519943295;    // Math.PI / 180
    let c = Math.cos;
    let a = 0.5 - c((lat1-lat2) * p) / 2 + c(lat2 * p) *c((lat1) * p) * (1 - c(((long1- long2) * p))) / 2;
    let dis = (12742 * Math.asin(Math.sqrt(a))); // 2 * R; R = 6371 km
    return dis;
  }
Sign up to request clarification or add additional context in comments.

2 Comments

Yes. Multiply by 0.621371 to convert into miles.
So, if I divide "dis" by 1000, I get value in meters, right?
0

Try google DirectionsService:

https://developers.google.com/maps/documentation/javascript/directions

Scroll to the end of the page, the last example calculates the distance between the points.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.