harini
harini

Reputation: 73

how to get latitude and longitude of current location using c#

I am new to c#,i have try to get the current location's latitude and longitude. below is my code what i have tried.

Code

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;
}

Upvotes: 1

Views: 13234

Answers (3)

Arunav .Net
Arunav .Net

Reputation: 76

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();
}

Upvotes: 0

Sohail Ali
Sohail Ali

Reputation: 468

Use this code to get the current user location

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();
    }

Upvotes: 1

Abhishek
Abhishek

Reputation: 7045

Here you go

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
}

Upvotes: 4

Related Questions