如何使用c#获取当前位置的纬度和经度

时间:2015-05-18 07:23:05

标签: c#

我是c#的新手,我试图获取当前位置的经度和纬度。以下是我试过的代码。

代码

public string GetLocationProperty()
{
    double a = 0.0;
    string b = "";
    GeoCoordinateWatcher watcher = new GeoCoordinateWatcher();

    // Do not suppress prompt, and wait 1000 milliseconds to start.
    watcher.TryStart(false, TimeSpan.FromMilliseconds(1000));

    GeoCoordinate coord = watcher.Position.Location;

    if (coord.IsUnknown != true)
    {
        //Console.WriteLine("Lat: {0}, Long: {1}",
        //    coord.Latitude,
        //    coord.Longitude);
        a = coord.Latitude;
        b = a.ToString();
    }
    else
    {
         Console.WriteLine("Unknown latitude and longitude.");
    }
    return b;
}

3 个答案:

答案 0 :(得分:5)

你去吧

GeoCoordinateWatcher watcher= new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
watcher.Start(); //started watcher
GeoCoordinate coord = watcher.Position.Location;
if (!watcher.Position.Location.IsUnknown)
{
    double lat = coord.Latitude; //latitude
    double long = coord.Longitude;  //logitude
}

答案 1 :(得分:1)

使用此代码获取当前用户位置

static void Main(string[] args)
    {
        GeoCoordinateWatcher watcher;
        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();

        Console.ReadKey();
    }

答案 2 :(得分:0)

GeoCoordinateWatcher _geoWatcher = new GeoCoordinateWatcher();
_geoWatcher.PositionChanged += GeoWatcher_PositionChanged;

bool isStarted = _geoWatcher.TryStart(suppressPermissionPrompt, timeOut);
_currentLocation = (isStarted && !_geoWatcher.Position.Location.IsUnknown) ? _geoWatcher.Position.Location: new GeoCoordinate();

private void GeoWatcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
    _currentLocation = e.Position.Location;
    _geoWatcher.Stop();
}