Having recently started with Ionic2, I came across a helpful tutorial that worked flawlessly for me. The tutorial, which can be found at , demonstrates listing nearby places and calculating the distance between these locations and a hardcoded place in the code. My goal was to use the device's current location instead of the predefined one in the code. Here is a screenshot showing my progress so far: view screenshot of my application. Additionally, here is the code snippet from my locations provider:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import {Geolocation} from '@ionic-native/geolocation';
/*
Generated class for the LocationsProvider provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class LocationsProvider {
data: any;
Currentlatitude: any;
Currentlongitude: any;
constructor(public http: Http, public geolocation: Geolocation) {
console.log('Hello LocationsProvider Provider');
}
load(){
this.geolocation.watchPosition().subscribe((position) => {
this.Currentlatitude = position.coords.latitude;
this.Currentlongitude = position.coords.longitude;
});
if(this.data){
return Promise.resolve(this.data);
}
return new Promise(resolve => {
this.http.get('assets/data/locations.json').map(res => res.json()).subscribe(data => {
this.data = this.applyHaversine(data.locations);
this.data.sort((locationA, locationB) => {
return locationA.distance - locationB.distance;
});
resolve(this.data);
});
});
}
applyHaversine(locations){
// this must change according to the device location
/*
let usersLocation = {
lat: 40.713744,
lng: -74.009056
}; */
console.log("this.Currentlatitude ",this.Currentlatitude);
let usersLocation = {
latitude: this.Currentlatitude,
longitude: this.Currentlongitude
};
console.log("usersLocation.latitude ",usersLocation.latitude);
locations.map((location) => {
let placeLocation = {
latitude: location.latitude,
longitude: location.longitude
};
location.distance = this.getDistanceBetweenPoints(usersLocation, placeLocation, 'km').toFixed(2);
});
return locations;
}
getDistanceBetweenPoints(start, end, units){
let earthRadius = {
miles: 3958.8,
km: 6371
};
let R = earthRadius[units || 'km'];
let lat1 = start.latitude;
let lon1 = start.longitude;
let lat2 = end.latitude;
let lon2 = end.longitude;
console.log("lon1 ",lat1); // here it gives me undefined
let dLat = this.toRad((lat2 - lat1));
let dLon = this.toRad((lon2 - lon1));
let a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(this.toRad(lat1)) * Math.cos(this.toRad(lat2)) *
Math.sin(dLon / 2) *
Math.sin(dLon / 2);
let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
let d = R * c;
return d;
}
toRad(x){
return x * Math.PI / 180;
}
}