StoreUtils.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.Linq;
  3. using Geocoding;
  4. using Geocoding.Google;
  5. using InABox.Core;
  6. using Address = InABox.Core.Address;
  7. using Location = Geocoding.Location;
  8. namespace Comal.Stores
  9. {
  10. public static class StoreUtils
  11. {
  12. public static string GoogleAPIKey { get; set; }
  13. public static void RegisterClasses()
  14. {
  15. CoreUtils.RegisterClasses(typeof(StoreUtils).Assembly);
  16. }
  17. public static void Geocode(Address address)
  18. {
  19. if (!address.IsChanged())
  20. return;
  21. if (string.IsNullOrEmpty(address.Street) || string.IsNullOrEmpty(address.City) || string.IsNullOrEmpty(address.State))
  22. {
  23. address.Location.Latitude = 0.0F;
  24. address.Location.Longitude = 0.0F;
  25. address.Location.Timestamp = DateTime.MinValue;
  26. return;
  27. }
  28. try
  29. {
  30. if (!string.IsNullOrWhiteSpace(GoogleAPIKey))
  31. {
  32. IGeocoder geocoder = new GoogleGeocoder(GoogleAPIKey);
  33. var add = geocoder.GeocodeAsync(string.Format("{0} {1} {2} Australia", address.Street, address.City, address.State)).Result
  34. .FirstOrDefault();
  35. if (add != null)
  36. {
  37. address.Location.Latitude = add.Coordinates.Latitude;
  38. address.Location.Longitude = add.Coordinates.Longitude;
  39. address.Location.Timestamp = DateTime.Now;
  40. }
  41. }
  42. }
  43. catch (Exception e)
  44. {
  45. address.Location.Latitude = 0.0F;
  46. address.Location.Longitude = 0.0F;
  47. address.Location.Timestamp = DateTime.MinValue;
  48. }
  49. }
  50. public static string ReverseGeocode(double latitude, double longitude)
  51. {
  52. if (string.IsNullOrEmpty(GoogleAPIKey))
  53. return "";
  54. IGeocoder geocoder = new GoogleGeocoder(GoogleAPIKey);
  55. var add = geocoder.ReverseGeocodeAsync(new Location(latitude, longitude)).Result.FirstOrDefault();
  56. return add != null ? add.FormattedAddress : "";
  57. }
  58. }
  59. }