forked from chadly/Geocoding.net
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMapQuestGeocoder.cs
More file actions
270 lines (236 loc) · 7.34 KB
/
MapQuestGeocoder.cs
File metadata and controls
270 lines (236 loc) · 7.34 KB
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
namespace Geocoding.MapQuest
{
/// <remarks>
/// <see cref="http://open.mapquestapi.com/geocoding/"/>
/// <seealso cref="http://developer.mapquest.com/"/>
/// </remarks>
public class MapQuestGeocoder : IGeocoder, IBatchGeocoder
{
readonly string key;
volatile bool useOSM;
/// <summary>
/// When true, will use the Open Street Map API
/// </summary>
public virtual bool UseOSM
{
get { return useOSM; }
set { useOSM = value; }
}
public IWebProxy Proxy { get; set; }
public MapQuestGeocoder(string key)
{
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentException("key can not be null or blank");
this.key = key;
}
IEnumerable<Address> HandleSingleResponse(MapQuestResponse res)
{
if (res != null && !res.Results.IsNullOrEmpty())
{
return HandleSingleResponse(from r in res.Results
where r != null && !r.Locations.IsNullOrEmpty()
from l in r.Locations
select l);
}
else
return new Address[0];
}
IEnumerable<Address> HandleSingleResponse(IEnumerable<MapQuestLocation> locs)
{
if (locs == null)
return new Address[0];
else
{
return from l in locs
where l != null && l.Quality < Quality.COUNTRY
let q = (int)l.Quality
let c = string.IsNullOrWhiteSpace(l.Confidence) ? "ZZZZZZ" : l.Confidence
orderby q ascending, c ascending
select l;
}
}
public IEnumerable<Address> Geocode(string address)
{
if (string.IsNullOrWhiteSpace(address))
throw new ArgumentException("address can not be null or empty!");
var f = new GeocodeRequest(key, address) { UseOSM = this.UseOSM };
MapQuestResponse res = Execute(f);
return HandleSingleResponse(res);
}
public IEnumerable<Address> Geocode(string street, string city, string state, string postalCode, string country)
{
var sb = new StringBuilder ();
if (!string.IsNullOrWhiteSpace (street))
sb.AppendFormat ("{0}, ", street);
if (!string.IsNullOrWhiteSpace (city))
sb.AppendFormat ("{0}, ", city);
if (!string.IsNullOrWhiteSpace (state))
sb.AppendFormat ("{0} ", state);
if (!string.IsNullOrWhiteSpace (postalCode))
sb.AppendFormat ("{0} ", postalCode);
if (!string.IsNullOrWhiteSpace (country))
sb.AppendFormat ("{0} ", country);
if (sb.Length > 1)
sb.Length--;
string s = sb.ToString ().Trim ();
if (string.IsNullOrWhiteSpace (s))
throw new ArgumentException ("Concatenated input values can not be null or blank");
if (s.Last () == ',')
s = s.Remove (s.Length - 1);
return Geocode (s);
}
public IEnumerable<Address> ReverseGeocode(Location location)
{
if (location == null)
throw new ArgumentNullException ("location");
var f = new ReverseGeocodeRequest(key, location) { UseOSM = this.UseOSM };
MapQuestResponse res = Execute(f);
return HandleSingleResponse(res);
}
public IEnumerable<Address> ReverseGeocode(double latitude, double longitude)
{
return ReverseGeocode(new Location(latitude, longitude));
}
public MapQuestResponse Execute(BaseRequest f)
{
HttpWebRequest request = Send(f);
MapQuestResponse r = Parse(request);
if (r != null && !r.Results.IsNullOrEmpty())
{
foreach (MapQuestResult o in r.Results)
{
if (o == null)
continue;
foreach (MapQuestLocation l in o.Locations)
{
if (!string.IsNullOrWhiteSpace(l.FormattedAddress) || o.ProvidedLocation == null)
continue;
if (string.Compare(o.ProvidedLocation.FormattedAddress, "unknown", true) != 0)
l.FormattedAddress = o.ProvidedLocation.FormattedAddress;
else
l.FormattedAddress = o.ProvidedLocation.ToString();
}
}
}
return r;
}
HttpWebRequest Send(BaseRequest f)
{
if (f == null)
throw new ArgumentNullException("f");
HttpWebRequest request;
bool hasBody = false;
switch (f.RequestVerb)
{
case "GET":
case "DELETE":
case "HEAD":
{
var u = string.Format("{0}json={1}&", f.RequestUri, HttpUtility.UrlEncode(f.RequestBody));
request = WebRequest.Create(u) as HttpWebRequest;
}
break;
case "POST":
case "PUT":
default:
{
request = WebRequest.Create(f.RequestUri) as HttpWebRequest;
hasBody = !string.IsNullOrWhiteSpace(f.RequestBody);
}
break;
}
request.Method = f.RequestVerb;
request.ContentType = "application/" + f.InputFormat;
if (Proxy != null)
request.Proxy = Proxy;
if (hasBody)
{
byte[] buffer = Encoding.UTF8.GetBytes(f.RequestBody);
request.ContentLength = buffer.Length;
using (Stream rs = request.GetRequestStream())
{
rs.Write(buffer, 0, buffer.Length);
rs.Flush();
rs.Close();
}
}
return request;
}
MapQuestResponse Parse(HttpWebRequest request)
{
if (request == null)
throw new ArgumentNullException("request");
string requestInfo = string.Format("[{0}] {1}", request.Method, request.RequestUri);
try
{
string json;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if ((int)response.StatusCode >= 300) //error
throw new HttpException((int)response.StatusCode, response.StatusDescription);
using (var sr = new StreamReader(response.GetResponseStream()))
json = sr.ReadToEnd();
}
if (string.IsNullOrWhiteSpace(json))
throw new ApplicationException("Remote system response with blank: " + requestInfo);
MapQuestResponse o = json.FromJSON<MapQuestResponse>();
if (o == null)
throw new ApplicationException("Unable to deserialize remote response: " + requestInfo + " => " + json);
return o;
}
catch (WebException wex) //convert to simple exception & close the response stream
{
using (HttpWebResponse response = wex.Response as HttpWebResponse)
{
var sb = new StringBuilder(requestInfo);
sb.Append(" | ");
sb.Append(response.StatusDescription);
sb.Append(" | ");
using (var sr = new StreamReader(response.GetResponseStream()))
{
sb.Append(sr.ReadToEnd());
}
throw new HttpException((int)response.StatusCode, sb.ToString());
}
}
}
public IEnumerable<ResultItem> Geocode(IEnumerable<string> addresses)
{
if (addresses == null)
throw new ArgumentNullException("addresses");
string[] adr = (from a in addresses
where !string.IsNullOrWhiteSpace(a)
group a by a into ag
select ag.Key).ToArray();
if (adr.IsNullOrEmpty())
throw new ArgumentException("Atleast one none blank item is required in addresses");
var f = new BatchGeocodeRequest(key, adr) { UseOSM = this.UseOSM };
MapQuestResponse res = Execute(f);
return HandleBatchResponse(res);
}
ICollection<ResultItem> HandleBatchResponse(MapQuestResponse res)
{
if (res != null && !res.Results.IsNullOrEmpty())
{
return (from r in res.Results
where r != null && !r.Locations.IsNullOrEmpty()
let resp = HandleSingleResponse(r.Locations)
where resp != null
select new ResultItem(r.ProvidedLocation, resp)).ToArray();
}
else
return new ResultItem[0];
}
public IEnumerable<ResultItem> ReverseGeocode(IEnumerable<Location> locations)
{
throw new NotSupportedException("ReverseGeocode(...) is not available for MapQuestGeocoder.");
}
}
}