using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text.Json;
using Newtonsoft.Json;
namespace ZR.Common;
///
///
///
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("", "");
}
}
///
/// 高德地图逆地理编码API返回结果
///
public class ReGeoCodeResult
{
///
/// 返回结果状态值
/// 0:请求失败;1:请求成功
///
public int Status { get; set; }
///
/// 返回状态说明
/// 当status为0时,info返回错误原因;否则返回"OK"
///
public string Info { get; set; }
///
/// 返回状态码
///
public string Infocode { get; set; }
///
/// 逆地理编码结果
///
public Regeocode Regeocode { get; set; }
}
///
/// 逆地理编码详细信息
///
public class Regeocode
{
///
/// 结构化地址信息
/// 例如:"广东省广州市天河区体育西路189号"
///
public string Formatted_Address { get; set; }
///
/// 地址组成元素
/// 包含国家、省份、城市等信息
///
public AddressComponent AddressComponent { get; set; }
// 可以根据需要添加其他字段
}
///
/// 地址组成元素
///
public class AddressComponent
{
///
/// 国家名称
/// 例如:"中国"
///
public string Country { get; set; }
///
/// 省份名称
/// 例如:"广东省"
///
public string Province { get; set; }
///
/// 城市名称
/// 例如:"广州市"
///
public string City { get; set; }
///
/// 区县名称
/// 例如:"天河区"
///
public string District { get; set; }
///
/// 乡镇/街道名称
/// 例如:"天园街道"
///
public string Township { get; set; }
// 可以根据需要添加其他字段
}