using System;
using System.Device.Location;
using System.Windows.Forms;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
namespace Code2DReader
{
public partial class FrmLocation : Form
{
public FrmLocation()
{
InitializeComponent();
}
// Khai báo coordinate watcher.
private GeoCoordinateWatcher Watcher = null;
// Tạo và khởi chạy dịch vụ wathcer
private void FrmLocation_Load(object sender, EventArgs e)
{
// Tạo watcher.
Watcher = new GeoCoordinateWatcher();
// Bắt sự kiện StatusChanged.
Watcher.StatusChanged += Watcher_StatusChanged;
// Khởi chạy watcher.
Watcher.Start();
}
private void Watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
if (e.Status == GeoPositionStatus.Ready)
{
// Display the latitude and longitude.
if (Watcher.Position.Location.IsUnknown)
{
txtLatitude.Text = "Không tìm thấy dữ liệu vị trí";
}
else
{
txtLatitude.Text = Watcher.Position.Location.Latitude.ToString();
txtLongitude.Text = Watcher.Position.Location.Longitude.ToString();
}
}
}
private void btGetLocation_Click(object sender, EventArgs e)
{
GeoCoordinateWatcher watcher = new GeoCoordinateWatcher();
// Đợi 1000 milliseconds để chạy.
watcher.TryStart(false, TimeSpan.FromMilliseconds(1000));
GeoCoordinate coord = watcher.Position.Location;
if (coord.IsUnknown != true)
{
txtLatitude.Text = coord.Latitude.ToString();
txtLongitude.Text = coord.Longitude.ToString();
RootObject obj = getAddress(coord.Latitude, coord.Longitude);
txtAddress.Text = obj.display_name; //obj.address.suburb + ", " + obj.address.city;
}
else
{
MessageBox.Show("Không tìm thấy dữ liệu vị trí latitude vas longitude");
}
}
public static RootObject getAddress(double lat, double lon)
{
//Khắc phục lổi "could not create ssl/tls secure channel" khi dowload data từ webclient.
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
WebClient webClient = new WebClient();
webClient.Headers.Add("user-agent", "Mozilla/4.0(compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
webClient.Headers.Add("Referer", "http://www.microsoft.com");
var jsonData = webClient.DownloadData("http://nominatim.openstreetmap.org/reverse?format=json&lat=" + lat + "&lon=" + lon);
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(RootObject));
RootObject rootObject = (RootObject)ser.ReadObject(new MemoryStream(jsonData));
return rootObject;
}
}
}