如何在C#中获取当前设备位置的经纬度

时间:2016-03-14 08:27:55

标签: c# google-maps

我想获取当前设备位置的纬度和经度,这是我的代码不能正常工作。 “coord.IsUnknown == false”总是返回true,这就是为什么我无法获得纬度和经度。

public partial class PoultryDirectory_HomeMaster : System.Web.UI.MasterPage
{
   protected void Page_Load(object sender, EventArgs e)
    {

    }


   protected void btnSingUp_Click(object sender, EventArgs e)
   {
       getLatLng();
   }

  private void getLatLng()
    {

        GeoCoordinateWatcher watcher = new GeoCoordinateWatcher();

        watcher.TryStart(false, TimeSpan.FromMilliseconds(1000));

        GeoCoordinate coord = watcher.Position.Location;

        if (coord.IsUnknown == false)
        {
            double lat = coord.Latitude;
            double lng = coord.Longitude;
            Console.WriteLine("Lat: {0}, Long: {1}",lat,lng);
        }
        else
        {
            Console.WriteLine("Unknown latitude and longitude.");
        }
    }
}

1 个答案:

答案 0 :(得分:1)

确保您的笔记本电脑/ Pc的位置设置已开启。

 GeoCoordinateWatcher watcher = new GeoCoordinateWatcher();

            watcher.PositionChanged += (sender, e) =>
            {
                var coordinate = e.Position.Location;
                Console.WriteLine("Lat: {0}, Long: {1}", coordinate.Latitude,
                    coordinate.Longitude);
                // Uncomment to get only one event.
                // watcher.Stop(); 
            };

            // Begin listening for location updates.
            watcher.Start();