GoogleMapTools.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using OASystem.Domain.ViewModels.SmallFun;
  2. using System.Text.Json;
  3. namespace OASystem.API.OAMethodLib.GoogleMapAPI
  4. {
  5. /// <summary>
  6. /// 谷歌地图API
  7. /// </summary>
  8. public static class GoogleMapTools
  9. {
  10. private static string _appKey = "AIzaSyBdLf8u8DinXQWVPLEkdrxOJpClXSqEnho"; //谷歌地图AppKey
  11. private static readonly HttpClient _httpClient = new HttpClient { BaseAddress = new Uri("https://maps.googleapis.com") };
  12. /// <summary>
  13. /// googleMapApi 获取距离And时间
  14. /// </summary>
  15. /// <param name="origin"></param>
  16. /// <param name="destination"></param>
  17. /// <returns></returns>
  18. public static async Task<Result> GetForeignAndTime(string origin, string destination)
  19. {
  20. var result = new Result() { Code = -2, Msg = "未知错误" };
  21. if (string.IsNullOrEmpty(origin) || string.IsNullOrEmpty(destination))
  22. {
  23. result.Msg = "起始地或目的地为空";
  24. return result;
  25. }
  26. string url = string.Format(@"/maps/api/directions/json?origin={0}&destination={1}&key={2}", origin, destination, _appKey);
  27. var req = await _httpClient.GetAsync(url);
  28. if (req.IsSuccessStatusCode)
  29. {
  30. var strResponse = await req.Content.ReadAsStringAsync();
  31. var resultData = System.Text.Json.JsonSerializer.Deserialize<GoogleMapResultView>(strResponse,
  32. new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
  33. if (resultData.Status == "OK")
  34. {
  35. if (resultData.Routes == null)
  36. {
  37. result.Msg = resultData.Status;
  38. return result;
  39. }
  40. var data = JsonConvert.DeserializeObject<dynamic>(resultData.Routes.ToJson());
  41. var dataView = new DistanceAndTimeView
  42. {
  43. DistanceText = data[0]["legs"][0]["distance"]["text"].ToString(),
  44. DistanceValue = data[0]["legs"][0]["distance"]["value"],
  45. DurationText = data[0]["legs"][0]["duration"]["text"].ToString(),
  46. DurationValue = data[0]["legs"][0]["duration"]["value"],
  47. };
  48. result.Code = 0;
  49. result.Data = dataView;
  50. }
  51. else
  52. {
  53. result.Msg = resultData.Status;
  54. }
  55. }
  56. else
  57. {
  58. result.Msg = "GoogleMapApi接口网络异常链接超时";
  59. }
  60. return result;
  61. }
  62. }
  63. }