| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="GoogleLocationService.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Globalization; |
| | | 9 | | using System.Linq; |
| | | 10 | | using System.Xml; |
| | | 11 | | using System.Xml.Linq; |
| | | 12 | | using MyNet.Geography; |
| | | 13 | | using MyNet.Primitives; |
| | | 14 | | |
| | | 15 | | namespace MyNet.Google.Maps; |
| | | 16 | | |
| | | 17 | | public class GoogleLocationService(string apikey, bool useHttps, Func<string, XDocument>? loadXDocument = null, Func<str |
| | | 18 | | { |
| | 24 | 19 | | private readonly string _urlProtocolPrefix = useHttps ? "https://" : "http://"; |
| | 24 | 20 | | private readonly Func<string, XDocument> _loadXDocument = loadXDocument ?? XDocument.Load; |
| | 24 | 21 | | private readonly Func<string, XmlDocument> _loadXmlDocument = loadXmlDocument ?? LoadXmlDocumentFromUrl; |
| | | 22 | | |
| | | 23 | | /// <summary> |
| | | 24 | | /// Initializes a new instance of the <see cref="GoogleLocationService"/> class. |
| | | 25 | | /// </summary> |
| | | 26 | | /// <param name="useHttps">Indicates whether to call the Google API over HTTPS or not.</param> |
| | | 27 | | public GoogleLocationService(bool useHttps) |
| | 0 | 28 | | : this(string.Empty, useHttps) { } |
| | | 29 | | |
| | | 30 | | /// <summary> |
| | | 31 | | /// Initializes a new instance of the <see cref="GoogleLocationService"/> class. Current calling the API over regula |
| | | 32 | | /// HTTP (not HTTPS). |
| | | 33 | | /// </summary> |
| | | 34 | | public GoogleLocationService() |
| | 0 | 35 | | : this(string.Empty, false) { } |
| | | 36 | | |
| | 9 | 37 | | private string ApiUrlRegionFromLatLong => _urlProtocolPrefix + Constants.ApiUriTemplates.ApiRegionFromLatLong; |
| | | 38 | | |
| | 12 | 39 | | private string ApiUrlLatLongFromAddress => _urlProtocolPrefix + Constants.ApiUriTemplates.ApiLatLongFromAddress; |
| | | 40 | | |
| | 3 | 41 | | private string ApiUrlDirections => _urlProtocolPrefix + Constants.ApiUriTemplates.ApiDirections; |
| | | 42 | | |
| | | 43 | | /// <summary> |
| | | 44 | | /// Translates a Latitude / Longitude into a Region (state) using Google Maps api. |
| | | 45 | | /// </summary> |
| | | 46 | | public Region? GetRegionFromCoordinates(double latitude, double longitude) |
| | | 47 | | { |
| | 3 | 48 | | var doc = _loadXDocument(string.Format(CultureInfo.InvariantCulture, ApiUrlRegionFromLatLong, latitude, longitud |
| | | 49 | | |
| | 3 | 50 | | var els = doc.Descendants("result").First().Descendants("address_component").FirstOrDefault(s => s.Descendants(" |
| | | 51 | | |
| | 3 | 52 | | return els != null ? new Region { Name = els.Descendants("long_name").First().Value, ShortCode = els.Descendants |
| | | 53 | | } |
| | | 54 | | |
| | | 55 | | /// <summary> |
| | | 56 | | /// Translates a Latitude / Longitude into an address using Google Maps api. |
| | | 57 | | /// </summary> |
| | | 58 | | public Address? GetAddressFromCoordinates(double latitude, double longitude) |
| | | 59 | | { |
| | 6 | 60 | | var addressCountry = string.Empty; |
| | 6 | 61 | | var addressCountryCode = string.Empty; |
| | 6 | 62 | | var addressLocality = string.Empty; |
| | 6 | 63 | | var addressSubLocality = string.Empty; |
| | 6 | 64 | | var addressRoute = string.Empty; |
| | 6 | 65 | | var addressStreetNumber = string.Empty; |
| | 6 | 66 | | var addressPostalCode = string.Empty; |
| | | 67 | | |
| | 6 | 68 | | var doc = _loadXmlDocument(string.Format(CultureInfo.InvariantCulture, ApiUrlRegionFromLatLong, latitude, longit |
| | 6 | 69 | | var element = doc.SelectSingleNode("//GeocodeResponse/status"); |
| | 6 | 70 | | if (element is not { InnerText: not Constants.ApiResponses.ZeroResults }) |
| | | 71 | | { |
| | 3 | 72 | | return null; |
| | | 73 | | } |
| | | 74 | | |
| | 3 | 75 | | var xnList = doc.SelectNodes("//GeocodeResponse/result/address_component"); |
| | | 76 | | |
| | 3 | 77 | | if (xnList == null) return null; |
| | | 78 | | |
| | 36 | 79 | | foreach (XmlNode? xn in xnList) |
| | | 80 | | { |
| | 15 | 81 | | var longName = xn?["long_name"]?.InnerText; |
| | 15 | 82 | | var shortname = xn?["short_name"]?.InnerText; |
| | 15 | 83 | | var typename = xn?["type"]?.InnerText; |
| | | 84 | | |
| | | 85 | | switch (typename) |
| | | 86 | | { |
| | | 87 | | case "country": |
| | 3 | 88 | | addressCountry = longName; |
| | 3 | 89 | | addressCountryCode = shortname; |
| | 3 | 90 | | break; |
| | | 91 | | case "locality": |
| | 3 | 92 | | addressLocality = longName; |
| | 3 | 93 | | break; |
| | | 94 | | case "sublocality": |
| | 0 | 95 | | addressSubLocality = longName; |
| | 0 | 96 | | break; |
| | | 97 | | case "neighborhood": |
| | | 98 | | case "colloquial_area": |
| | | 99 | | case "administrative_area_level_1": |
| | | 100 | | case "administrative_area_level_2": |
| | | 101 | | case "administrative_area_level_3": |
| | | 102 | | break; |
| | | 103 | | case "route": |
| | 3 | 104 | | addressRoute = shortname; |
| | 3 | 105 | | break; |
| | | 106 | | case "street_number": |
| | 3 | 107 | | addressStreetNumber = shortname; |
| | 3 | 108 | | break; |
| | | 109 | | case "postal_code": |
| | 3 | 110 | | addressPostalCode = longName; |
| | | 111 | | break; |
| | | 112 | | } |
| | | 113 | | } |
| | | 114 | | |
| | 3 | 115 | | var country = ResolveCountry(addressCountry, addressCountryCode); |
| | 3 | 116 | | var streetParts = new[] { addressStreetNumber, addressRoute, addressSubLocality }.Where(static x => x is not nul |
| | 3 | 117 | | return new Address(string.Join(" ", streetParts), addressPostalCode, addressLocality, country, new Coordinates(l |
| | | 118 | | } |
| | | 119 | | |
| | | 120 | | /// <summary> |
| | | 121 | | /// Gets the latitude and longitude that belongs to an address. |
| | | 122 | | /// </summary> |
| | | 123 | | /// <param name="address">The address.</param> |
| | | 124 | | public Coordinates? GetCoordinatesFromAddress(string address) |
| | | 125 | | { |
| | 9 | 126 | | var doc = _loadXDocument(string.Format(CultureInfo.InvariantCulture, ApiUrlLatLongFromAddress, Uri.EscapeDataStr |
| | | 127 | | |
| | 9 | 128 | | var status = doc.Descendants("status").FirstOrDefault()?.Value; |
| | | 129 | | switch (status) |
| | | 130 | | { |
| | | 131 | | case Constants.ApiResponses.OverQueryLimit: |
| | 3 | 132 | | throw new QueryLimitExceededException("QueryLimit exceeded, check your dashboard"); |
| | | 133 | | case Constants.ApiResponses.RequestDenied: |
| | 3 | 134 | | throw new RequestDeniedException("Request denied, it's likely you need to enable the necessary Google ma |
| | | 135 | | } |
| | | 136 | | |
| | 3 | 137 | | var els = doc.Descendants("result").Descendants("geometry").Descendants("location").FirstOrDefault(); |
| | 3 | 138 | | if (els == null) return null; |
| | 3 | 139 | | var latitude = ParseUs((els.Nodes().First() as XElement)?.Value); |
| | 3 | 140 | | var longitude = ParseUs((els.Nodes().ElementAt(1) as XElement)?.Value); |
| | 3 | 141 | | return latitude.HasValue && longitude.HasValue ? new Coordinates(latitude.Value, longitude.Value) : null; |
| | | 142 | | } |
| | | 143 | | |
| | | 144 | | /// <summary> |
| | | 145 | | /// Gets the latitude and longitude that belongs to an address. |
| | | 146 | | /// </summary> |
| | | 147 | | /// <param name="address">The address.</param> |
| | 0 | 148 | | public Coordinates? GetCoordinatesFromAddress(Address address) => GetCoordinatesFromAddress(address.ToString()); |
| | | 149 | | |
| | | 150 | | /// <summary> |
| | | 151 | | /// Gets an array of string addresses that matched a possibly ambiguous address. |
| | | 152 | | /// </summary> |
| | | 153 | | /// <param name="address">The address.</param> |
| | | 154 | | public string[] GetAddressesListFromAddress(string address) |
| | | 155 | | { |
| | 3 | 156 | | var doc = _loadXDocument(string.Format(CultureInfo.InvariantCulture, ApiUrlLatLongFromAddress, Uri.EscapeDataStr |
| | 3 | 157 | | var status = doc.Descendants("status").FirstOrDefault()?.Value; |
| | | 158 | | |
| | | 159 | | switch (status) |
| | | 160 | | { |
| | | 161 | | case Constants.ApiResponses.OverQueryLimit: |
| | 0 | 162 | | throw new QueryLimitExceededException("QueryLimit exceeded, check your dashboard"); |
| | | 163 | | case Constants.ApiResponses.RequestDenied: |
| | 0 | 164 | | throw new RequestDeniedException("Request denied, it's likely you need to enable the necessary Google ma |
| | | 165 | | } |
| | | 166 | | |
| | 3 | 167 | | var results = doc.Descendants("result").Descendants("formatted_address").ToArray(); |
| | 3 | 168 | | var addresses = (from elem in results select elem.Value).ToArray(); |
| | 3 | 169 | | return addresses.Length > 0 ? addresses : []; |
| | | 170 | | } |
| | | 171 | | |
| | | 172 | | /// <summary> |
| | | 173 | | /// Gets an array of string addresses that matched a possibly ambiguous address. |
| | | 174 | | /// </summary> |
| | | 175 | | /// <param name="address">The address.</param> |
| | 0 | 176 | | public string[] GetAddressesListFromAddress(Address address) => GetAddressesListFromAddress(address.ToString()); |
| | | 177 | | |
| | | 178 | | /// <summary> |
| | | 179 | | /// Gets the directions. |
| | | 180 | | /// </summary> |
| | | 181 | | /// <param name="fromAddress">From address.</param> |
| | | 182 | | /// <param name="toAddress">To address.</param> |
| | | 183 | | /// <returns>The directions.</returns> |
| | | 184 | | public Directions GetDirections(Address fromAddress, Address toAddress) |
| | | 185 | | { |
| | 3 | 186 | | var direction = new Directions(); |
| | | 187 | | |
| | 3 | 188 | | var doc = _loadXDocument(string.Format(CultureInfo.InvariantCulture, |
| | 3 | 189 | | ApiUrlDirections, |
| | 3 | 190 | | Uri.EscapeDataString(fromAddress.ToString()), |
| | 3 | 191 | | Uri.EscapeDataString(toAddress.ToString())) + "&key=" + apikey); |
| | | 192 | | |
| | 3 | 193 | | var status = (from s in doc.Descendants("DirectionsResponse").Descendants("status") |
| | 3 | 194 | | select s).FirstOrDefault(); |
| | | 195 | | |
| | 3 | 196 | | if (status is { Value: "OK" }) |
| | | 197 | | { |
| | 3 | 198 | | direction.StatusCode = Directions.Status.Ok; |
| | 3 | 199 | | var distance = (from d in doc.Descendants("DirectionsResponse").Descendants("route").Descendants("leg") |
| | 3 | 200 | | .Descendants("distance").Descendants("text") |
| | 3 | 201 | | select d).LastOrDefault(); |
| | | 202 | | |
| | 3 | 203 | | if (distance != null) |
| | | 204 | | { |
| | 3 | 205 | | direction.Distance = distance.Value; |
| | | 206 | | } |
| | | 207 | | |
| | 3 | 208 | | var duration = (from d in doc.Descendants("DirectionsResponse").Descendants("route").Descendants("leg") |
| | 3 | 209 | | .Descendants("duration").Descendants("text") |
| | 3 | 210 | | select d).LastOrDefault(); |
| | | 211 | | |
| | 3 | 212 | | if (duration != null) |
| | | 213 | | { |
| | 3 | 214 | | direction.Duration = duration.Value; |
| | | 215 | | } |
| | | 216 | | |
| | 3 | 217 | | var steps = from s in doc.Descendants("DirectionsResponse").Descendants("route").Descendants("leg").Descenda |
| | 3 | 218 | | select s; |
| | | 219 | | |
| | 12 | 220 | | foreach (var step in steps) |
| | | 221 | | { |
| | 3 | 222 | | var directionStep = new Step |
| | 3 | 223 | | { |
| | 3 | 224 | | Instruction = step?.Element("html_instructions")?.Value, |
| | 3 | 225 | | Distance = step?.Descendants("distance").First().Element("text")?.Value |
| | 3 | 226 | | }; |
| | 3 | 227 | | direction.Steps.Add(directionStep); |
| | | 228 | | } |
| | | 229 | | |
| | 3 | 230 | | return direction; |
| | | 231 | | } |
| | | 232 | | |
| | 0 | 233 | | if (status is not { Value: not "OK" }) |
| | 0 | 234 | | throw new InvalidOperationException("Unable to get Directions from Google"); |
| | 0 | 235 | | direction.StatusCode = Directions.Status.Failed; |
| | 0 | 236 | | return direction; |
| | | 237 | | } |
| | | 238 | | |
| | 3 | 239 | | private static Country? ResolveCountry(string? countryName, string? countryCode) => Country.TryFromValue(countryName |
| | 3 | 240 | | ? byName |
| | 3 | 241 | | : string.IsNullOrEmpty(countryCode) |
| | 3 | 242 | | ? null |
| | 3 | 243 | | : Country.All.FirstOrDefault(c => |
| | 3 | 244 | | string.Equals(c.Alpha2, countryCode, StringComparison.OrdinalIgnoreCase)); |
| | | 245 | | |
| | 6 | 246 | | private static double? ParseUs(string? value) => value is null ? null : double.Parse(value, new CultureInfo("en-US") |
| | | 247 | | |
| | | 248 | | private static XmlDocument LoadXmlDocumentFromUrl(string url) |
| | | 249 | | { |
| | 0 | 250 | | var doc = new XmlDocument(); |
| | 0 | 251 | | doc.Load(url); |
| | 0 | 252 | | return doc; |
| | | 253 | | } |
| | | 254 | | } |
| | | 255 | | |