forked from chadly/Geocoding.net
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGoogleGeocoder.cs
More file actions
494 lines (418 loc) · 16.1 KB
/
GoogleGeocoder.cs
File metadata and controls
494 lines (418 loc) · 16.1 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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Xml.XPath;
namespace Geocoding.Google
{
/// <remarks>
/// http://code.google.com/apis/maps/documentation/geocoding/
/// </remarks>
public class GoogleGeocoder : IGeocoder, IAsyncGeocoder
{
string apiKey;
BusinessKey businessKey;
const string keyMessage = "Only one of BusinessKey or ApiKey should be set on the GoogleGeocoder.";
public GoogleGeocoder() { }
public GoogleGeocoder(BusinessKey businessKey)
{
BusinessKey = businessKey;
}
public GoogleGeocoder(string apiKey)
{
ApiKey = apiKey;
}
public string ApiKey
{
get { return apiKey; }
set
{
if (businessKey != null)
throw new InvalidOperationException(keyMessage);
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentException("ApiKey can not be null or empty");
apiKey = value;
}
}
public BusinessKey BusinessKey
{
get { return businessKey; }
set
{
if (!string.IsNullOrEmpty(apiKey))
throw new InvalidOperationException(keyMessage);
if (value == null)
throw new ArgumentException("BusinessKey can not be null");
businessKey = value;
}
}
public IWebProxy Proxy { get; set; }
public string Language { get; set; }
public string RegionBias { get; set; }
public Bounds BoundsBias { get; set; }
public string ServiceUrl
{
get
{
var builder = new StringBuilder();
builder.Append("https://maps.googleapis.com/maps/api/geocode/xml?{0}={1}&sensor=false");
if (!string.IsNullOrEmpty(Language))
{
builder.Append("&language=");
builder.Append(HttpUtility.UrlEncode(Language));
}
if (!string.IsNullOrEmpty(RegionBias))
{
builder.Append("®ion=");
builder.Append(HttpUtility.UrlEncode(RegionBias));
}
if (!string.IsNullOrEmpty(ApiKey))
{
builder.Append("&key=");
builder.Append(HttpUtility.UrlEncode(ApiKey));
}
if (BusinessKey != null)
{
builder.Append("&client=");
builder.Append(HttpUtility.UrlEncode(BusinessKey.ClientId));
}
if (BoundsBias != null)
{
builder.Append("&bounds=");
builder.Append(BoundsBias.SouthWest.Latitude.ToString(CultureInfo.InvariantCulture));
builder.Append(",");
builder.Append(BoundsBias.SouthWest.Longitude.ToString(CultureInfo.InvariantCulture));
builder.Append("|");
builder.Append(BoundsBias.NorthEast.Latitude.ToString(CultureInfo.InvariantCulture));
builder.Append(",");
builder.Append(BoundsBias.NorthEast.Longitude.ToString(CultureInfo.InvariantCulture));
}
return builder.ToString();
}
}
public IEnumerable<GoogleAddress> Geocode(string address)
{
if (string.IsNullOrEmpty(address))
throw new ArgumentNullException("address");
HttpWebRequest request = BuildWebRequest("address", HttpUtility.UrlEncode(address));
return ProcessRequest(request);
}
public IEnumerable<GoogleAddress> ReverseGeocode(Location location)
{
if (location == null)
throw new ArgumentNullException("location");
return ReverseGeocode(location.Latitude, location.Longitude);
}
public IEnumerable<GoogleAddress> ReverseGeocode(double latitude, double longitude)
{
HttpWebRequest request = BuildWebRequest("latlng", BuildGeolocation(latitude, longitude));
return ProcessRequest(request);
}
public Task<IEnumerable<GoogleAddress>> GeocodeAsync(string address)
{
if (string.IsNullOrEmpty(address))
throw new ArgumentNullException("address");
HttpWebRequest request = BuildWebRequest("address", HttpUtility.UrlEncode(address));
return ProcessRequestAsync(request);
}
public Task<IEnumerable<GoogleAddress>> GeocodeAsync(string address, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(address))
throw new ArgumentNullException("address");
HttpWebRequest request = BuildWebRequest("address", HttpUtility.UrlEncode(address));
return ProcessRequestAsync(request, cancellationToken);
}
public Task<IEnumerable<GoogleAddress>> ReverseGeocodeAsync(double latitude, double longitude)
{
HttpWebRequest request = BuildWebRequest("latlng", BuildGeolocation(latitude, longitude));
return ProcessRequestAsync(request);
}
public Task<IEnumerable<GoogleAddress>> ReverseGeocodeAsync(double latitude, double longitude, CancellationToken cancellationToken)
{
HttpWebRequest request = BuildWebRequest("latlng", BuildGeolocation(latitude, longitude));
return ProcessRequestAsync(request, cancellationToken);
}
private string BuildAddress(string street, string city, string state, string postalCode, string country)
{
return string.Format("{0} {1}, {2} {3}, {4}", street, city, state, postalCode, country);
}
private string BuildGeolocation(double latitude, double longitude)
{
return string.Format(CultureInfo.InvariantCulture, "{0},{1}", latitude, longitude);
}
private IEnumerable<GoogleAddress> ProcessRequest(HttpWebRequest request)
{
try
{
using (WebResponse response = request.GetResponse())
{
return ProcessWebResponse(response);
}
}
catch (GoogleGeocodingException)
{
//let these pass through
throw;
}
catch (Exception ex)
{
//wrap in google exception
throw new GoogleGeocodingException(ex);
}
}
private Task<IEnumerable<GoogleAddress>> ProcessRequestAsync(HttpWebRequest request, CancellationToken? cancellationToken = null)
{
if (cancellationToken != null)
{
cancellationToken.Value.ThrowIfCancellationRequested();
cancellationToken.Value.Register(() => request.Abort());
}
var requestState = new RequestState(request, cancellationToken);
return Task.Factory.FromAsync(
(callback, asyncState) => SendRequestAsync((RequestState)asyncState, callback),
result => ProcessResponseAsync((RequestState)result.AsyncState, result),
requestState
);
}
private IAsyncResult SendRequestAsync(RequestState requestState, AsyncCallback callback)
{
try
{
return requestState.request.BeginGetResponse(callback, requestState);
}
catch (Exception ex)
{
throw new GoogleGeocodingException(ex);
}
}
private IEnumerable<GoogleAddress> ProcessResponseAsync(RequestState requestState, IAsyncResult result)
{
if (requestState.cancellationToken != null)
requestState.cancellationToken.Value.ThrowIfCancellationRequested();
try
{
using (var response = (HttpWebResponse)requestState.request.EndGetResponse(result))
{
return ProcessWebResponse(response);
}
}
catch (GoogleGeocodingException)
{
//let these pass through
throw;
}
catch (Exception ex)
{
//wrap in google exception
throw new GoogleGeocodingException(ex);
}
}
IEnumerable<Address> IGeocoder.Geocode(string address)
{
return Geocode(address).Cast<Address>();
}
IEnumerable<Address> IGeocoder.Geocode(string street, string city, string state, string postalCode, string country)
{
return Geocode(BuildAddress(street, city, state, postalCode, country)).Cast<Address>();
}
IEnumerable<Address> IGeocoder.ReverseGeocode(Location location)
{
return ReverseGeocode(location).Cast<Address>();
}
IEnumerable<Address> IGeocoder.ReverseGeocode(double latitude, double longitude)
{
return ReverseGeocode(latitude, longitude).Cast<Address>();
}
Task<IEnumerable<Address>> IAsyncGeocoder.GeocodeAsync(string address)
{
return GeocodeAsync(address)
.ContinueWith(task => task.Result.Cast<Address>());
}
Task<IEnumerable<Address>> IAsyncGeocoder.GeocodeAsync(string address, CancellationToken cancellationToken)
{
return GeocodeAsync(address, cancellationToken)
.ContinueWith(task => task.Result.Cast<Address>(), cancellationToken);
}
Task<IEnumerable<Address>> IAsyncGeocoder.GeocodeAsync(string street, string city, string state, string postalCode, string country)
{
return GeocodeAsync(BuildAddress(street, city, state, postalCode, country))
.ContinueWith(task => task.Result.Cast<Address>());
}
Task<IEnumerable<Address>> IAsyncGeocoder.GeocodeAsync(string street, string city, string state, string postalCode, string country, CancellationToken cancellationToken)
{
return GeocodeAsync(BuildAddress(street, city, state, postalCode, country), cancellationToken)
.ContinueWith(task => task.Result.Cast<Address>(), cancellationToken);
}
Task<IEnumerable<Address>> IAsyncGeocoder.ReverseGeocodeAsync(double latitude, double longitude)
{
return ReverseGeocodeAsync(latitude, longitude)
.ContinueWith(task => task.Result.Cast<Address>());
}
Task<IEnumerable<Address>> IAsyncGeocoder.ReverseGeocodeAsync(double latitude, double longitude, CancellationToken cancellationToken)
{
return ReverseGeocodeAsync(latitude, longitude, cancellationToken)
.ContinueWith(task => task.Result.Cast<Address>(), cancellationToken);
}
private HttpWebRequest BuildWebRequest(string type, string value)
{
string url = string.Format(ServiceUrl, type, value);
if (BusinessKey != null)
url = BusinessKey.GenerateSignature(url);
var req = WebRequest.Create(url) as HttpWebRequest;
if (this.Proxy != null)
{
req.Proxy = Proxy;
}
req.Method = "GET";
return req;
}
private IEnumerable<GoogleAddress> ProcessWebResponse(WebResponse response)
{
XPathDocument xmlDoc = LoadXmlResponse(response);
XPathNavigator nav = xmlDoc.CreateNavigator();
GoogleStatus status = EvaluateStatus((string)nav.Evaluate("string(/GeocodeResponse/status)"));
if (status != GoogleStatus.Ok && status != GoogleStatus.ZeroResults)
throw new GoogleGeocodingException(status);
if (status == GoogleStatus.Ok)
return ParseAddresses(nav.Select("/GeocodeResponse/result")).ToArray();
return new GoogleAddress[0];
}
private XPathDocument LoadXmlResponse(WebResponse response)
{
using (Stream stream = response.GetResponseStream())
{
XPathDocument doc = new XPathDocument(stream);
return doc;
}
}
private IEnumerable<GoogleAddress> ParseAddresses(XPathNodeIterator nodes)
{
while (nodes.MoveNext())
{
XPathNavigator nav = nodes.Current;
GoogleAddressType type = EvaluateType((string)nav.Evaluate("string(type)"));
string place_id = (string)nav.Evaluate("string(place_id)");
string formattedAddress = (string)nav.Evaluate("string(formatted_address)");
var components = ParseComponents(nav.Select("address_component")).ToArray();
double latitude = (double)nav.Evaluate("number(geometry/location/lat)");
double longitude = (double)nav.Evaluate("number(geometry/location/lng)");
Location coordinates = new Location(latitude, longitude);
double neLatitude = (double)nav.Evaluate("number(geometry/viewport/northeast/lat)");
double neLongitude = (double)nav.Evaluate("number(geometry/viewport/northeast/lng)");
Location neCoordinates = new Location(neLatitude, neLongitude);
double swLatitude = (double)nav.Evaluate("number(geometry/viewport/southwest/lat)");
double swLongitude = (double)nav.Evaluate("number(geometry/viewport/southwest/lng)");
Location swCoordinates = new Location(swLatitude, swLongitude);
var viewport = new GoogleViewport { Northeast = neCoordinates, Southwest = swCoordinates };
GoogleLocationType locationType = EvaluateLocationType((string)nav.Evaluate("string(geometry/location_type)"));
bool isPartialMatch;
bool.TryParse((string)nav.Evaluate("string(partial_match)"), out isPartialMatch);
yield return new GoogleAddress(type, formattedAddress, components, coordinates, viewport, isPartialMatch, locationType, place_id);
}
}
private IEnumerable<GoogleAddressComponent> ParseComponents(XPathNodeIterator nodes)
{
while (nodes.MoveNext())
{
XPathNavigator nav = nodes.Current;
string longName = (string)nav.Evaluate("string(long_name)");
string shortName = (string)nav.Evaluate("string(short_name)");
var types = ParseComponentTypes(nav.Select("type")).ToArray();
if (types.Any()) //don't return an address component with no type
yield return new GoogleAddressComponent(types, longName, shortName);
}
}
private IEnumerable<GoogleAddressType> ParseComponentTypes(XPathNodeIterator nodes)
{
while (nodes.MoveNext())
yield return EvaluateType(nodes.Current.InnerXml);
}
/// <remarks>
/// http://code.google.com/apis/maps/documentation/geocoding/#StatusCodes
/// </remarks>
private GoogleStatus EvaluateStatus(string status)
{
switch (status)
{
case "OK": return GoogleStatus.Ok;
case "ZERO_RESULTS": return GoogleStatus.ZeroResults;
case "OVER_QUERY_LIMIT": return GoogleStatus.OverQueryLimit;
case "REQUEST_DENIED": return GoogleStatus.RequestDenied;
case "INVALID_REQUEST": return GoogleStatus.InvalidRequest;
default: return GoogleStatus.Error;
}
}
/// <remarks>
/// http://code.google.com/apis/maps/documentation/geocoding/#Types
/// </remarks>
private GoogleAddressType EvaluateType(string type)
{
switch (type)
{
case "street_address": return GoogleAddressType.StreetAddress;
case "route": return GoogleAddressType.Route;
case "intersection": return GoogleAddressType.Intersection;
case "political": return GoogleAddressType.Political;
case "country": return GoogleAddressType.Country;
case "administrative_area_level_1": return GoogleAddressType.AdministrativeAreaLevel1;
case "administrative_area_level_2": return GoogleAddressType.AdministrativeAreaLevel2;
case "administrative_area_level_3": return GoogleAddressType.AdministrativeAreaLevel3;
case "colloquial_area": return GoogleAddressType.ColloquialArea;
case "locality": return GoogleAddressType.Locality;
case "sublocality": return GoogleAddressType.SubLocality;
case "neighborhood": return GoogleAddressType.Neighborhood;
case "premise": return GoogleAddressType.Premise;
case "subpremise": return GoogleAddressType.Subpremise;
case "postal_code": return GoogleAddressType.PostalCode;
case "natural_feature": return GoogleAddressType.NaturalFeature;
case "airport": return GoogleAddressType.Airport;
case "park": return GoogleAddressType.Park;
case "point_of_interest": return GoogleAddressType.PointOfInterest;
case "post_box": return GoogleAddressType.PostBox;
case "street_number": return GoogleAddressType.StreetNumber;
case "floor": return GoogleAddressType.Floor;
case "room": return GoogleAddressType.Room;
case "postal_town": return GoogleAddressType.PostalTown;
case "establishment": return GoogleAddressType.Establishment;
case "sublocality_level_1": return GoogleAddressType.SubLocalityLevel1;
case "sublocality_level_2": return GoogleAddressType.SubLocalityLevel2;
case "sublocality_level_3": return GoogleAddressType.SubLocalityLevel3;
case "sublocality_level_4": return GoogleAddressType.SubLocalityLevel4;
case "sublocality_level_5": return GoogleAddressType.SubLocalityLevel5;
case "postal_code_suffix": return GoogleAddressType.PostalCodeSuffix;
default: return GoogleAddressType.Unknown;
}
}
/// <remarks>
/// https://developers.google.com/maps/documentation/geocoding/?csw=1#Results
/// </remarks>
private GoogleLocationType EvaluateLocationType(string type)
{
switch (type)
{
case "ROOFTOP": return GoogleLocationType.Rooftop;
case "RANGE_INTERPOLATED": return GoogleLocationType.RangeInterpolated;
case "GEOMETRIC_CENTER": return GoogleLocationType.GeometricCenter;
case "APPROXIMATE": return GoogleLocationType.Approximate;
default: return GoogleLocationType.Unknown;
}
}
protected class RequestState
{
public readonly HttpWebRequest request;
public readonly CancellationToken? cancellationToken;
public RequestState(HttpWebRequest request, CancellationToken? cancellationToken)
{
if (request == null) throw new ArgumentNullException("request");
this.request = request;
this.cancellationToken = cancellationToken;
}
}
}
}