- 先在Package.appxmanifest中配置位置权限
2. 创建LocationManager类
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using Windows.Devices.Geolocation; 7 8 namespace Weather 9 { 10 public class LocationManager 11 { 12 public static async Task<Geoposition> GetPosition() 13 { 14 //请求位置访问权限 15 var accessStatus = await Geolocator.RequestAccessAsync(); 16 //如果不允许就抛出异常 17 if (accessStatus != GeolocationAccessStatus.Allowed) throw new Exception(); 18 //实例类 19 var geolocator = new Geolocator { DesiredAccuracyInMeters = 0 }; 20 //获取设备位置 21 var position = await geolocator.GetGeopositionAsync(); 22 //返回位置信息 23 return position; 24 } 25 } 26 }
3.获取位置
var position = await LocationManager.GetPosition(); double lat = position.Coordinate.Point.Position.Latitude; double lon = position.Coordinate.Point.Position.Longitude;