-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGeolocation.cs
106 lines (99 loc) · 3.48 KB
/
Geolocation.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml.Linq;
namespace ConsoleApplication1
{
public class Geolocation
{
static string baseUri = "http://maps.googleapis.com/maps/api/geocode/xml?latlng={0},{1}&sensor=false";
static string result;
public static void RetrieveFormatedAddress(string lat, string lng)
{
string requestUri = string.Format(baseUri, lat, lng);
using (WebClient wc = new WebClient())
{
wc.Encoding = Encoding.GetEncoding("utf-8");
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
wc.DownloadStringAsync(new Uri(requestUri));
}
}
static void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var xmlElm = XElement.Parse(e.Result);
var status = (from elm in xmlElm.Descendants()
where elm.Name == "status"
select elm).FirstOrDefault();
if (status.Value.ToLower() == "ok")
{
var res = (from elm in xmlElm.Descendants()
where elm.Name == "formatted_address"
select elm).FirstOrDefault();
DataTableSave(res.Value);
}
else
{
DataTableSave(result = "No Address Found");
}
}
public static void DataTableSave(string content)
{
string con = ConfigurationManager.ConnectionStrings["Test"].ToString();
SqlConnection connection = new SqlConnection(con);
connection.Open();
string query = "INSERT INTO Location (Address) VALUES (@Address)";
SqlCommand cmd = new SqlCommand(query, connection);
try
{
if (connection.State == ConnectionState.Closed)
connection.Open();
cmd.Parameters.AddWithValue("@Address", content);
cmd.ExecuteNonQuery();
cmd.Dispose();
connection.Close();
}
catch
{
throw;
}
finally
{
connection.Close();
connection.Dispose();
}
}
public static void DataTableRow()
{
string con = ConfigurationManager.ConnectionStrings["Test"].ToString();
SqlConnection connection = new SqlConnection(con);
connection.Open();
string query = "Select * from Coordinate";
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader dataReader = command.ExecuteReader();
try
{
if (dataReader.HasRows)
while (dataReader.Read())
{
string lat = dataReader["Latitude"].ToString();
string lon = dataReader["Longitude"].ToString();
RetrieveFormatedAddress(lat, lon);
}
}
catch
{
throw;
}
finally
{
dataReader.Close();
connection.Close();
connection.Dispose();
}
}
}
}