forked from cafeasp/googleGeoCodingApi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vpGeo
94 lines (80 loc) · 2.84 KB
/
vpGeo
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
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace GeoCoding
{
public class vpGeo
{
public enum Result
{
OK,
ZERO_RESULTS,
OVER_QUERY_LIMIT,
REQUEST_DENIED,
INVALID_REQUEST,
UNKNOWN_ERROR
}
const string GGeoCodeJsonServiceUrl = "https://maps.googleapis.com/maps/api/geocode/json?address={0}&key={1}";
public string Key { get; set; }
public Result GeoResult { get; set; }
public GeoResult GoogleGeoCodeInfo(Address address)
{
if (string.IsNullOrEmpty(Key))
{
throw new MissingFieldException("Your Google API Key is missing");
}
using (var client = new WebClient())
{
string formatAddress = string.Format(GGeoCodeJsonServiceUrl, EncodeAddress(address),Key);
var result = client.DownloadString(formatAddress);
var O = JsonConvert.DeserializeObject<GeoResult>(result);
SetGeoResultFlag(O.Status);
return O;
}
}
private string EncodeAddress(Address address)
{
var sb = new StringBuilder();
if (!string.IsNullOrEmpty(address.Address1))
sb.Append(Uri.EscapeUriString(" " +address.Address1));
if (!string.IsNullOrEmpty(address.Address2))
sb.Append(Uri.EscapeUriString(" " + address.Address2));
if (!string.IsNullOrEmpty(address.City))
sb.Append(Uri.EscapeUriString(" " + address.City));
if (!string.IsNullOrEmpty(address.State))
sb.Append(Uri.EscapeUriString(" " + address.State));
if (!string.IsNullOrEmpty(address.Zip))
sb.Append(Uri.EscapeUriString(" " + address.Zip));
return sb.ToString();
}
private void SetGeoResultFlag(string status)
{
switch (status)
{
case "OK":
GeoResult = Result.OK;
break;
case "ZERO_RESULTS":
GeoResult = Result.ZERO_RESULTS;
break;
case "OVER_QUERY_LIMIT":
GeoResult = Result.OVER_QUERY_LIMIT;
break;
case "REQUEST_DENIED":
GeoResult = Result.REQUEST_DENIED;
break;
case "INVALID_REQUEST":
GeoResult = Result.INVALID_REQUEST;
break;
case "UNKNOWN_ERROR":
GeoResult = Result.UNKNOWN_ERROR;
break;
}
}
}
}