mehdi
mehdi

Reputation: 147

calculate distance between 2 points using Javascript API in IONIC 2

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

Upvotes: 3

Views: 10672

Answers (2)

illya yurkevich
illya yurkevich

Reputation: 234

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

Upvotes: 13

Biranchi
Biranchi

Reputation: 16327

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.

Upvotes: 0

Related Questions