Get Geolocation with Ionic 2

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
});
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值