PS: it takes at least one minute for cold start, so it is best to initialize the public class and use it directly when calling it.
The geocoordinatewatcher class provides coordinate-based location data from the current location provider. Coordinate-based location data from the current location provider, which is the highest priority location provider on the computer. Its priority depends on a series of factors, such: time and accuracy of data from all providers, accuracy of location application requests, power consumption associated with location providers, and performance impact. The current location provider may change over time, for example, when the gps device loses its internal ancillary signal function and the Wi-Fi three-way conversion method provider becomes the most accurate provider on the computer.
To access location data, create geocoordinatewatcher and call start or trystart to obtain data from the current location provider.
You can check the status attribute to determine whether the data is available. If the data is available, you can obtain the location from the position attribute at a time, or receive consecutive location updates by processing the positionchanged event.
The permission, status, and position attributes support inotifypropertychanged. Therefore, applications can bind data to these attributes.
In Windows 7, if the location provider has been installed and can parse the location of the computer, all the system. device. Location classes are completely normal.
Note: |
On Windows 7 starter, the only supported location provider is the default location provider in the control panel, and an external program must be installed to specify the latitude and longitude. |
Note: In versions earlier than Windows 7, the following conditions apply:
You can create all system. device. Location objects with constructors, but the status attribute always has a value of disabled.
The position indicated by the location attribute of position is always unknown.
No location events are triggered.
using System;using System.Device.Location; namespace GetLocationEvent{ class Program { static void Main(string[] args) { CLocation myLocation = new CLocation(); myLocation.GetLocationEvent(); Console.WriteLine("Enter any key to quit."); Console.ReadLine(); } class CLocation { GeoCoordinateWatcher watcher; public void GetLocationEvent() { this.watcher = new GeoCoordinateWatcher(); this.watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged); bool started = this.watcher.TryStart(false, TimeSpan.FromMilliseconds(2000)); if (!started) { Console.WriteLine("GeoCoordinateWatcher timed out on start."); } } void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e) { PrintPosition(e.Position.Location.Latitude, e.Position.Location.Longitude); } void PrintPosition(double Latitude, double Longitude) { Console.WriteLine("Latitude: {0}, Longitude {1}", Latitude, Longitude); } } }}