package com.cdzy.ebikemaintenance.utils; import com.alibaba.fastjson2.JSONObject; import lombok.extern.slf4j.Slf4j; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.Arrays; /** * 地址解析、反解析工具类。 * * @author dingchao * @date 2025/4/3 * @modified by: */ @Slf4j @Service public class GeoCodingUtil { private final static String LOCATION_TO_ADDRESS = "location"; private final static String ADDRESS_TO_LOCATION = "address"; private final String url; private final String accessKey; private final OkHttpClient client; /** * 地理编码工具类构造函数。 * 目前实现的腾讯地图webservice * * @param apiUrl * @param accessKey */ public GeoCodingUtil(String apiUrl, String accessKey) { this.url = apiUrl; this.accessKey = accessKey; this.client = new OkHttpClient(); } /** * 输入经纬度,返回地址。 * * @param location 经纬度 * @return 地址 */ public String getLocationToaddress(JSONObject location) { Request request = new Request.Builder() .url(url + "/?"+LOCATION_TO_ADDRESS+"=" + String.format("%f,%f", location.getDouble("lat"), location.getDouble("lng")) + "&key=" + accessKey) .build(); try(Response response = client.newCall(request).execute()) { if(response.isSuccessful()) { if (response.body()!= null) { String result = response.body().string(); JSONObject jsonObject = JSONObject.parseObject(result); if (jsonObject.getInteger("status") == 0) { return jsonObject.getJSONObject("result").getJSONObject("formatted_addresses").getString("standard_address"); } logError("地址解析失败==>{}", jsonObject.getString("message")); return null; } logError("地址解析失败==>{}", response.message()); return null; } logError("地址解析失败==>{}", response.message()); return null; } catch (Exception e) { logError("地址解析失败==>{}", e.getMessage() + Arrays.toString(e.getStackTrace())); return null; } } /** * 输入地址,返回经纬度(GCJ02)。 * * @param address 地址 * @return 经纬度 */ public JSONObject getAddressToLocation(String address) { Request request = new Request.Builder() .url(url + "/?"+ADDRESS_TO_LOCATION+"=" + address + "&key=" + accessKey) .build(); try(Response response = client.newCall(request).execute()) { if(response.isSuccessful()) { if (response.body() != null) { String result = response.body().string(); JSONObject jsonObject = JSONObject.parseObject(result); if (jsonObject.getInteger("status") == 0) { return jsonObject.getJSONObject("result").getJSONObject("location"); }else{ logError("位置解析失败==>{}", jsonObject.getString("message")); return null; } }else{ logError("位置解析失败==>{}", response.message()); return null; } }else{ logError("位置解析失败==>{}", response.message()); return null; } } catch (Exception e) { logError("位置解析失败==>{}", e.getMessage() + Arrays.toString(e.getStackTrace())); return null; } } private void logError(String errDesc, String errorMessage) { log.error(errDesc, errorMessage); } }