diff --git a/ghy-admin/src/main/java/com/ghy/web/controller/goods/GoodsController.java b/ghy-admin/src/main/java/com/ghy/web/controller/goods/GoodsController.java index 58989f7b..dd72ddaa 100644 --- a/ghy-admin/src/main/java/com/ghy/web/controller/goods/GoodsController.java +++ b/ghy-admin/src/main/java/com/ghy/web/controller/goods/GoodsController.java @@ -31,6 +31,7 @@ import javax.annotation.Resource; import java.math.BigDecimal; import java.util.*; import java.util.stream.Collectors; +import com.ghy.common.utils.BaiduMapUtils; @Controller @RequestMapping("/goods/goods") @@ -58,6 +59,8 @@ public class GoodsController extends BaseController { private IDeptCategoryInsuranceRelationService deptCategoryInsuranceRelationService; @Resource private ShopService shopService; + @Resource + private BaiduMapUtils baiduMapUtils; @RequiresPermissions("goods:goods:view") @GetMapping() @@ -436,28 +439,20 @@ public class GoodsController extends BaseController { countryName != null || streetName != null || address != null)) { try { - // 调用百度地理编码接口获取经纬度 - JSONObject geocodeBody = new JSONObject(); - geocodeBody.put("provinceName", provinceName); - geocodeBody.put("cityName", cityName); - geocodeBody.put("countryName", countryName); - geocodeBody.put("streetName", streetName); - geocodeBody.put("address", address); + // 使用BaiduMapUtils工具类获取经纬度 + Map coordinates = baiduMapUtils.getCoordinatesByAddress( + provinceName, cityName, countryName, streetName, address + ); - String url = "https://gmhl.gmjlb.com/tool/baidu/geocode"; - String resultStr = HttpUtils.sendPost(url, geocodeBody.toJSONString()); - - JSONObject responseJson = JSONObject.parseObject(resultStr); - if (responseJson.getInteger("code") == 200) { - JSONObject data = responseJson.getJSONObject("data"); - userLongitude = data.getDouble("longitude"); - userLatitude = data.getDouble("latitude"); + if (coordinates != null) { + userLongitude = coordinates.get("longitude"); + userLatitude = coordinates.get("latitude"); logger.info("通过地址获取到用户经纬度: 经度={}, 纬度={}", userLongitude, userLatitude); } else { - logger.warn("通过地址获取用户经纬度失败: {}", responseJson.getString("msg")); + logger.warn("通过地址获取用户经纬度失败"); } } catch (Exception e) { - logger.error("调用百度地理编码接口异常: {}", e.getMessage(), e); + logger.error("调用百度地图API异常: {}", e.getMessage(), e); } } @@ -658,28 +653,20 @@ public class GoodsController extends BaseController { (provinceName != null || cityName != null || countryName != null || streetName != null || address != null)) { try { - // 调用百度地理编码接口获取经纬度 - JSONObject geocodeBody = new JSONObject(); - geocodeBody.put("provinceName", provinceName); - geocodeBody.put("cityName", cityName); - geocodeBody.put("countryName", countryName); - geocodeBody.put("streetName", streetName); - geocodeBody.put("address", address); + // 使用BaiduMapUtils工具类获取经纬度 + Map coordinates = baiduMapUtils.getCoordinatesByAddress( + provinceName, cityName, countryName, streetName, address + ); - String url = "https://gmhl.gmjlb.com/tool/baidu/geocode"; - String resultStr = HttpUtils.sendPost(url, geocodeBody.toJSONString()); - - JSONObject responseJson = JSONObject.parseObject(resultStr); - if (responseJson.getInteger("code") == 200) { - JSONObject data = responseJson.getJSONObject("data"); - longitude = data.getDouble("longitude"); - latitude = data.getDouble("latitude"); + if (coordinates != null) { + longitude = coordinates.get("longitude"); + latitude = coordinates.get("latitude"); logger.info("通过地址获取到用户经纬度: 经度={}, 纬度={}", longitude, latitude); } else { - logger.warn("通过地址获取用户经纬度失败: {}", responseJson.getString("msg")); + logger.warn("通过地址获取用户经纬度失败"); } } catch (Exception e) { - logger.error("调用百度地理编码接口异常: {}", e.getMessage(), e); + logger.error("调用百度地图API异常: {}", e.getMessage(), e); } } diff --git a/ghy-common/src/main/java/com/ghy/common/utils/BaiduMapUtils.java b/ghy-common/src/main/java/com/ghy/common/utils/BaiduMapUtils.java new file mode 100644 index 00000000..543f896c --- /dev/null +++ b/ghy-common/src/main/java/com/ghy/common/utils/BaiduMapUtils.java @@ -0,0 +1,208 @@ +package com.ghy.common.utils; + +import com.alibaba.fastjson.JSONObject; +import com.ghy.common.utils.http.HttpUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + +/** + * 百度地图API工具类 + * 专门用于地址转经纬度等地理编码功能 + * + * @author system + */ +@Component +public class BaiduMapUtils { + + private static final Logger logger = LoggerFactory.getLogger(BaiduMapUtils.class); + + @Value("${baidu.ak}") + private String baiduAk; + + /** + * 通过详细地址获取经纬度坐标 + * + * @param provinceName 省份名称 + * @param cityName 城市名称 + * @param countryName 区县名称 + * @param streetName 街道名称 + * @param detailAddress 详细地址 + * @return 包含经纬度的Map,失败返回null + */ + public Map getCoordinatesByAddress(String provinceName, String cityName, + String countryName, String streetName, + String detailAddress) { + try { + // 构建完整地址 + StringBuilder fullAddress = new StringBuilder(); + if (provinceName != null && !provinceName.trim().isEmpty()) { + fullAddress.append(provinceName); + } + if (cityName != null && !cityName.trim().isEmpty()) { + fullAddress.append(cityName); + } + if (countryName != null && !countryName.trim().isEmpty()) { + fullAddress.append(countryName); + } + if (streetName != null && !streetName.trim().isEmpty()) { + fullAddress.append(streetName); + } + if (detailAddress != null && !detailAddress.trim().isEmpty()) { + fullAddress.append(detailAddress); + } + + String address = fullAddress.toString(); + if (address.trim().isEmpty()) { + logger.warn("地址信息为空,无法获取坐标"); + return null; + } + + logger.info("开始调用百度地图API解析地址: {}", address); + + // 调用百度地图正向地理编码API + String encoded = URLEncoder.encode(address, StandardCharsets.UTF_8.name()); + String url = "https://api.map.baidu.com/geocoding/v3/?output=json&ak=" + baiduAk + "&address=" + encoded; + + // 使用HttpUtils发送GET请求 + String result = HttpUtils.sendGet(url); + if (result == null || result.trim().isEmpty()) { + logger.error("百度地图API返回结果为空"); + return null; + } + + result = result.replaceAll("\n", "").replaceAll("\t", ""); + + // 解析返回结果 + JSONObject resultJson = JSONObject.parseObject(result); + if ("0".equals(resultJson.getString("status"))) { + JSONObject location = resultJson.getJSONObject("result").getJSONObject("location"); + Double lng = location.getDouble("lng"); + Double lat = location.getDouble("lat"); + + Map coordinates = new HashMap<>(); + coordinates.put("longitude", lng); + coordinates.put("latitude", lat); + + logger.info("百度地图API解析成功: {} -> 经度={}, 纬度={}", address, lng, lat); + return coordinates; + } else { + logger.error("百度地图API解析失败: {} - {}", address, resultJson.getString("msg")); + return null; + } + + } catch (Exception e) { + logger.error("调用百度地图API失败: {} - {}", + String.format("省:%s,市:%s,区:%s,街道:%s,详细:%s", + provinceName, cityName, countryName, streetName, detailAddress), + e.getMessage(), e); + return null; + } + } + + /** + * 通过完整地址字符串获取经纬度坐标 + * + * @param fullAddress 完整地址字符串 + * @return 包含经纬度的Map,失败返回null + */ + public Map getCoordinatesByFullAddress(String fullAddress) { + try { + if (fullAddress == null || fullAddress.trim().isEmpty()) { + logger.warn("完整地址为空,无法获取坐标"); + return null; + } + + logger.info("开始调用百度地图API解析完整地址: {}", fullAddress); + + // 调用百度地图正向地理编码API + String encoded = URLEncoder.encode(fullAddress, StandardCharsets.UTF_8.name()); + String url = "https://api.map.baidu.com/geocoding/v3/?output=json&ak=" + baiduAk + "&address=" + encoded; + + // 使用HttpUtils发送GET请求 + String result = HttpUtils.sendGet(url); + if (result == null || result.trim().isEmpty()) { + logger.error("百度地图API返回结果为空"); + return null; + } + + result = result.replaceAll("\n", "").replaceAll("\t", ""); + + // 解析返回结果 + JSONObject resultJson = JSONObject.parseObject(result); + if ("0".equals(resultJson.getString("status"))) { + JSONObject location = resultJson.getJSONObject("result").getJSONObject("location"); + Double lng = location.getDouble("lng"); + Double lat = location.getDouble("lat"); + + Map coordinates = new HashMap<>(); + coordinates.put("longitude", lng); + coordinates.put("latitude", lat); + + logger.info("百度地图API解析成功: {} -> 经度={}, 纬度={}", fullAddress, lng, lat); + return coordinates; + } else { + logger.error("百度地图API解析失败: {} - {}", fullAddress, resultJson.getString("msg")); + return null; + } + + } catch (Exception e) { + logger.error("调用百度地图API失败: {} - {}", fullAddress, e.getMessage(), e); + return null; + } + } + + /** + * 通过经纬度获取地址信息(逆地理编码) + * + * @param longitude 经度 + * @param latitude 纬度 + * @return 包含地址信息的JSONObject,失败返回null + */ + public JSONObject getAddressByCoordinates(Double longitude, Double latitude) { + try { + if (longitude == null || latitude == null) { + logger.warn("经纬度参数为空,无法获取地址"); + return null; + } + + logger.info("开始调用百度地图API逆解析坐标: 经度={}, 纬度={}", longitude, latitude); + + // 调用百度地图逆地理编码API + String location = longitude + "," + latitude; + String url = "https://api.map.baidu.com/reverse_geocoding/v3/?ak=" + baiduAk + + "&output=json&coordtype=wgs84ll&location=" + location; + + // 使用HttpUtils发送GET请求 + String result = HttpUtils.sendGet(url); + if (result == null || result.trim().isEmpty()) { + logger.error("百度地图API返回结果为空"); + return null; + } + + result = result.replaceAll("\n", "").replaceAll("\t", ""); + + // 解析返回结果 + JSONObject resultJson = JSONObject.parseObject(result); + if ("0".equals(resultJson.getString("status"))) { + logger.info("百度地图API逆解析成功: 经度={}, 纬度={}", longitude, latitude); + return resultJson; + } else { + logger.error("百度地图API逆解析失败: 经度={}, 纬度={} - {}", + longitude, latitude, resultJson.getString("msg")); + return null; + } + + } catch (Exception e) { + logger.error("调用百度地图API逆解析失败: 经度={}, 纬度={} - {}", + longitude, latitude, e.getMessage(), e); + return null; + } + } +} diff --git a/ghy-shop/src/main/java/com/ghy/shop/service/impl/ShopServiceImpl.java b/ghy-shop/src/main/java/com/ghy/shop/service/impl/ShopServiceImpl.java index fb79f9ad..c1e7a4a9 100644 --- a/ghy-shop/src/main/java/com/ghy/shop/service/impl/ShopServiceImpl.java +++ b/ghy-shop/src/main/java/com/ghy/shop/service/impl/ShopServiceImpl.java @@ -5,6 +5,7 @@ import com.ghy.shop.domain.ShopDistanceQuery; import com.ghy.shop.mapper.ShopMapper; import com.ghy.shop.service.ShopService; import com.ghy.common.utils.LocationUtils; +import com.ghy.common.utils.BaiduMapUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -20,6 +21,9 @@ public class ShopServiceImpl implements ShopService { @Autowired private ShopMapper shopMapper; + + @Autowired + private BaiduMapUtils baiduMapUtils; @Override public int addShop(Shop shop) { @@ -95,16 +99,14 @@ public class ShopServiceImpl implements ShopService { } else if (query.hasAddressInfo()) { // 通过传入的地址信息生成用户位置的经纬度 try { - String fullAddress = query.getFullAddress(); - if (!fullAddress.isEmpty()) { - logger.info("通过传入的地址信息生成用户位置经纬度: {}", fullAddress); - - Map coordinates = getCoordinatesByAddress(fullAddress); - if (coordinates != null) { - userLat = coordinates.get("latitude"); - userLng = coordinates.get("longitude"); - logger.info("通过传入地址成功生成用户位置经纬度: 经度={}, 纬度={}", userLng, userLat); - } + Map coordinates = baiduMapUtils.getCoordinatesByAddress( + query.getProvinceName(), query.getCityName(), + query.getCountryName(), query.getStreetName(), query.getAddress() + ); + if (coordinates != null) { + userLat = coordinates.get("latitude"); + userLng = coordinates.get("longitude"); + logger.info("通过传入地址成功生成用户位置经纬度: 经度={}, 纬度={}", userLng, userLat); } } catch (Exception e) { logger.warn("通过传入地址生成用户位置经纬度失败: {}", e.getMessage()); @@ -119,34 +121,24 @@ public class ShopServiceImpl implements ShopService { } else if (shop.getAddress() != null && !shop.getAddress().trim().isEmpty()) { // 通过店铺的地址信息生成经纬度 try { - // 构建完整地址 - StringBuilder fullAddress = new StringBuilder(); - if (shop.getProvinceName() != null) fullAddress.append(shop.getProvinceName()); - if (shop.getCityName() != null) fullAddress.append(shop.getCityName()); - if (shop.getCountryName() != null) fullAddress.append(shop.getCountryName()); - if (shop.getStreetName() != null) fullAddress.append(shop.getStreetName()); - if (shop.getAddress() != null) fullAddress.append(shop.getAddress()); - - String address = fullAddress.toString(); - if (!address.isEmpty()) { - logger.info("通过店铺地址信息生成经纬度: {}", address); + Map coordinates = baiduMapUtils.getCoordinatesByAddress( + shop.getProvinceName(), shop.getCityName(), + shop.getCountryName(), shop.getStreetName(), shop.getAddress() + ); + if (coordinates != null) { + shopLat = coordinates.get("latitude"); + shopLng = coordinates.get("longitude"); + logger.info("通过店铺地址成功生成经纬度: 经度={}, 纬度={}", shopLng, shopLat); - Map coordinates = getCoordinatesByAddress(address); - if (coordinates != null) { - shopLat = coordinates.get("latitude"); - shopLng = coordinates.get("longitude"); - logger.info("通过店铺地址成功生成经纬度: 经度={}, 纬度={}", shopLng, shopLat); - - // 更新店铺的经纬度信息 - shop.setLatitude(shopLat); - shop.setLongitude(shopLng); - - // 如果请求更新店铺位置信息,则保存到数据库 - if (query.getUpdateShopLocation() != null && query.getUpdateShopLocation()) { - shopMapper.update(shop); - logger.info("已更新并保存店铺[{}]的经纬度: 经度={}, 纬度={}", - shop.getShopName(), shopLng, shopLat); - } + // 更新店铺的经纬度信息 + shop.setLatitude(shopLat); + shop.setLongitude(shopLng); + + // 如果请求更新店铺位置信息,则保存到数据库 + if (query.getUpdateShopLocation() != null && query.getUpdateShopLocation()) { + shopMapper.update(shop); + logger.info("已更新并保存店铺[{}]的经纬度: 经度={}, 纬度={}", + shop.getShopName(), shopLng, shopLat); } } } catch (Exception e) { @@ -170,49 +162,4 @@ public class ShopServiceImpl implements ShopService { return -1; } } - - /** - * 通过地址获取经纬度坐标 - * 直接调用百度地图正向地理编码API - */ - private Map getCoordinatesByAddress(String address) { - try { - if (address == null || address.trim().isEmpty()) { - logger.warn("地址为空,无法获取坐标"); - return null; - } - - logger.info("开始调用百度地图API解析地址: {}", address); - - // 调用百度地图正向地理编码API - String encoded = java.net.URLEncoder.encode(address, "UTF-8"); - String url = "https://api.map.baidu.com/geocoding/v3/?output=json&ak=ZQTgMW7W0GTuE7Ripb0HDp5TqRaOI6PZ&address=" + encoded; - - // 使用HttpUtils发送GET请求 - String result = com.ghy.common.utils.http.HttpUtils.sendGet(url); - result = result.replaceAll("\n", "").replaceAll("\t", ""); - - // 解析返回结果 - com.alibaba.fastjson.JSONObject resultJson = com.alibaba.fastjson.JSONObject.parseObject(result); - if ("0".equals(resultJson.getString("status"))) { - com.alibaba.fastjson.JSONObject location = resultJson.getJSONObject("result").getJSONObject("location"); - Double lng = location.getDouble("lng"); - Double lat = location.getDouble("lat"); - - Map coordinates = new HashMap<>(); - coordinates.put("longitude", lng); - coordinates.put("latitude", lat); - - logger.info("百度地图API解析成功: {} -> 经度={}, 纬度={}", address, lng, lat); - return coordinates; - } else { - logger.error("百度地图API解析失败: {} - {}", address, resultJson.getString("msg")); - return null; - } - - } catch (Exception e) { - logger.error("调用百度地图API失败: {} - {}", address, e.getMessage(), e); - return null; - } - } } \ No newline at end of file