LoginSignup
6
8

More than 5 years have passed since last update.

Xamarin.Forms でGPSを使用する

Posted at

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  

6
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8