GoogleMapTools.cs 2.7 KB

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