12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- using System.Linq;
- using Geocoding;
- using Geocoding.Google;
- using InABox.Core;
- using Address = InABox.Core.Address;
- using Location = Geocoding.Location;
- using System;
- namespace Comal.Stores
- {
- public static class StoreUtils
- {
- public static string GoogleAPIKey { get; set; }
- public static void RegisterClasses()
- {
- CoreUtils.RegisterClasses(typeof(StoreUtils).Assembly);
- }
- public static void Geocode(Address address)
- {
- if (!address.IsChanged())
- return;
- if (string.IsNullOrEmpty(address.Street) || string.IsNullOrEmpty(address.City) || string.IsNullOrEmpty(address.State))
- {
- address.Location.Latitude = 0.0F;
- address.Location.Longitude = 0.0F;
- address.Location.Timestamp = DateTime.MinValue;
- return;
- }
- try
- {
- if (!string.IsNullOrWhiteSpace(GoogleAPIKey))
- {
- IGeocoder geocoder = new GoogleGeocoder(GoogleAPIKey);
- var add = geocoder.GeocodeAsync(string.Format("{0} {1} {2} Australia", address.Street, address.City, address.State)).Result
- .FirstOrDefault();
- if (add != null)
- {
- address.Location.Latitude = add.Coordinates.Latitude;
- address.Location.Longitude = add.Coordinates.Longitude;
- address.Location.Timestamp = DateTime.Now;
- }
- }
- }
- catch (Exception e)
- {
- address.Location.Latitude = 0.0F;
- address.Location.Longitude = 0.0F;
- address.Location.Timestamp = DateTime.MinValue;
- }
- }
- public static string ReverseGeocode(double latitude, double longitude)
- {
- if (string.IsNullOrEmpty(GoogleAPIKey))
- return "";
- IGeocoder geocoder = new GoogleGeocoder(GoogleAPIKey);
- Geocoding.Address? add = null;
- var geocode = Task.Run(async () =>
- {
- try
- {
- var adds = await geocoder.ReverseGeocodeAsync(new Location(latitude, longitude));
- add = adds.FirstOrDefault();
- }
- catch (Exception e)
- {
- Logger.Send(LogType.Error, "",$"Gecode Error: {e.Message}\n{e.StackTrace}");
- }
- }
- );
- return add?.FormattedAddress ?? string.Empty;
- }
- }
- }
|