StoreUtils.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System.Linq;
  2. using Geocoding;
  3. using Geocoding.Google;
  4. using InABox.Core;
  5. using Address = InABox.Core.Address;
  6. using Location = Geocoding.Location;
  7. using System;
  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. Geocoding.Address? add = null;
  56. var geocode = Task.Run(async () =>
  57. {
  58. try
  59. {
  60. var adds = await geocoder.ReverseGeocodeAsync(new Location(latitude, longitude));
  61. add = adds.FirstOrDefault();
  62. }
  63. catch (Exception e)
  64. {
  65. Logger.Send(LogType.Error, "",$"Gecode Error: {e.Message}\n{e.StackTrace}");
  66. }
  67. }
  68. );
  69. return add?.FormattedAddress ?? string.Empty;
  70. }
  71. }
  72. }