WorkCamera/server/Zr.Admin.NET/ZR.Common/GeoCodeService.cs
2025-12-27 12:17:46 +08:00

136 lines
3.4 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text.Json;
using Newtonsoft.Json;
namespace ZR.Common;
/// <summary>
///
/// </summary>
public class GeoCodeService
{
public static string ApiKey = "938a85a1cc3114b200522fb7ee579b27";
public const string BaseUrl = "https://restapi.amap.com/v3/geocode/regeo";
private readonly HttpClient _httpClient;
public GeoCodeService(HttpClient httpClient)
{
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
}
public async Task<(string, string)?> GetReGeoCodeAsync(string location, string coordsys = "gcj02")
{
if (string.IsNullOrWhiteSpace(location))
{
throw new ArgumentException("Location cannot be null or empty.", nameof(location));
}
var requestUrl = $"{BaseUrl}?key={ApiKey}&location={location}&coordsys={coordsys}";
try
{
var response = await _httpClient.GetAsync(requestUrl);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
var json = JsonDocument.Parse(content);
// 直接提取 formatted_address
var j = json.RootElement
.GetProperty("regeocode")
.GetProperty("formatted_address")
.GetString();
return new(j, content);
}
catch (HttpRequestException ex)
{
//throw new ApplicationException("Error calling AMap API", ex);
}
return new("", "");
}
}
/// <summary>
/// 高德地图逆地理编码API返回结果
/// </summary>
public class ReGeoCodeResult
{
/// <summary>
/// 返回结果状态值
/// 0请求失败1请求成功
/// </summary>
public int Status { get; set; }
/// <summary>
/// 返回状态说明
/// 当status为0时info返回错误原因否则返回"OK"
/// </summary>
public string Info { get; set; }
/// <summary>
/// 返回状态码
/// </summary>
public string Infocode { get; set; }
/// <summary>
/// 逆地理编码结果
/// </summary>
public Regeocode Regeocode { get; set; }
}
/// <summary>
/// 逆地理编码详细信息
/// </summary>
public class Regeocode
{
/// <summary>
/// 结构化地址信息
/// 例如:"广东省广州市天河区体育西路189号"
/// </summary>
public string Formatted_Address { get; set; }
/// <summary>
/// 地址组成元素
/// 包含国家、省份、城市等信息
/// </summary>
public AddressComponent AddressComponent { get; set; }
// 可以根据需要添加其他字段
}
/// <summary>
/// 地址组成元素
/// </summary>
public class AddressComponent
{
/// <summary>
/// 国家名称
/// 例如:"中国"
/// </summary>
public string Country { get; set; }
/// <summary>
/// 省份名称
/// 例如:"广东省"
/// </summary>
public string Province { get; set; }
/// <summary>
/// 城市名称
/// 例如:"广州市"
/// </summary>
public string City { get; set; }
/// <summary>
/// 区县名称
/// 例如:"天河区"
/// </summary>
public string District { get; set; }
/// <summary>
/// 乡镇/街道名称
/// 例如:"天园街道"
/// </summary>
public string Township { get; set; }
// 可以根据需要添加其他字段
}