Help us understand the problem. What is going on with this article?

Xamarin.Forms でGPSを使用する

More than 3 years have passed since last update.

Mastering Xamarin.Forms1を見ながら、Xamarin.FormsでGPSを使用して、緯度・経度を取得する方法をまとめてみました。

動作確認環境

  • Mac OS X

  • Xamarin Studio 6.0

PCLの実装

位置情報(緯度・経度)を格納するクラスの実装

GeoCoords.cs
/// <summary>
/// 位置情報格納クラス
/// </summary>
public class GeoCoords
{
    /// <summary>
    /// 緯度
    /// </summary>
    public double Latitude { get; set; }
    /// <summary>
    /// 経度
    /// </summary>
    public double Longitude { get; set; }
}

位置情報取得処理のインターフェース追加

XamarinのIoC機能を使用して

ILocationService.cs
/// <summary>
/// 位置情報取得サービス
/// </summary>
public interface ILocationService
{
    /// <summary>
    /// 位置情報取得処理
    /// </summary>
    Task<GeoCoords> GetGeoCoordinatesAsync();
}

Android

LocationService.cs
/// <summary>
/// 位置情報取得サービスのAndroid実装
/// </summary>
public class LocationService : ILocationService
{
    public async Task<GeoCoords> GetGeoCoordinatesAsync()
    {
        var locator = new Geolocator(Forms.Context)
        {
            // 解像度を1.3mに設定
            DesiredAccuracy = 30
        };

        var position = await locator.GetPositionAsync(30000);

        var result = new GeoCoords
        {
            Latitude = position.Latitude,
            Longitude = position.Longitude
        };

        return result;
    }
}

iOS

LocationService.cs
public class LocationService : ILocationService
{
    public async Task<GeoCoords> GetGeoCoordinatesAsync()
    {
        var locator = new Geolocator
        {
            DesiredAccuracy = 30
        };

        var position = await locator.GetPositionAsync(30000);

        var result = new GeoCoords
        {
            Latitude = position.Latitude,
            Longitude = position.Longitude
        };

        return result;
    }
}

  1. Mastering Xamarin.Forms(Ed Snider 2016/1/30) ISBN:978-1-78528-719-0  

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away