Resume
In my work, sometimes I need to get the geolocation while programming an App with Ionic 2. In this passage, we will see how could we simply get the geolocation with Ionic 2.
Library
In your TypeScript file, you need to import this library to use Geolocation.class
import {Geolocation} from 'ionic-native';
Code
We should just simply use the following code to get latitude and longitude.
Attention, getting geolocation is an asynchrone function. The system will create another thread to get the information. So that you should put your code which require the geolocation in the call back function unless you may not have the geolocation.
Geolocation.getCurrentPosition().then((resp) => {
this.circuitService.getCircuit(duration, new Coordinate(resp.coords.latitude, resp.coords.longitude))
.subscribe(
r => { circuits = r; console.log(circuits); },
error => console.log("Error", error)
);
});
I’ve created a service named CircuitService which needs the geolocation to get data by Ajax. So I need to put my function in the call back function of Geolocation.
Geolocation.getCurrentPosition().then((resp) => {
resp.coords.latitude;
resp.coords.longitude;//Here is the geo information
});