Get current location using C#
Asked Answered
F

1

7

My skill level: Beginner

Code: C# (wpf)

Hardware: Dell Venue 11 Pro tablet (windows 8.1)

I would like to get the current location of my computer via cellular triangulation in coordinates(latitude/longitude). Using the following link as a reference (Getting GPS coordinates on Windows phone 7), I have been attempting to pull the lat/lon coordinates from Windows Location Services. I have verified that Windows Location Services is receiving the coordinates via cell tower triangulation, but every time I run the following code the coordinates are listed as "NaN". Any help here would be greatly appreciated.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Device.Location;

namespace GPS
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        private GeoCoordinateWatcher watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);


        public MainWindow()
        {
            InitializeComponent();

            watcher.Start();

            LocationMessage(); 
        }



        private void LocationMessage()
        {

            var whereat = watcher.Position.Location;

            var Lat = whereat.Latitude.ToString("0.000000");
            var Lon = whereat.Longitude.ToString("0.000000");


            //optional parameters for future use
            whereat.Altitude.ToString();
            whereat.HorizontalAccuracy.ToString();
            whereat.VerticalAccuracy.ToString();
            whereat.Course.ToString();
            whereat.Speed.ToString();

            MessageBox.Show(string.Format("Lat: {0}\nLon: {1}",Lat,Lon)); 
        }


    }


}
Feedback answered 21/8, 2015 at 18:28 Comment(1)
Try subscribing to the OnPositionChanged event and then try to get the position. It could be that not enough time has elapsed to actually get the location.Allamerican
V
2

If you only need your current position once, and not continous update as you move, you can replace Start with TryStart:

if (watcher.TryStart(false, TimeSpan.FromSeconds(3)))
{
    LocationMessage();
}
else
{
    // Position not found after 3 seconds...
}

Keep in mind that this method returns synchronously, so it is best not to run in on the UI thread.

Veronique answered 23/2, 2016 at 13:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.