no message

This commit is contained in:
cb 2025-08-25 08:44:15 +08:00
parent 353e302df9
commit 620af65906
3 changed files with 258 additions and 116 deletions

View File

@ -31,6 +31,7 @@ import javax.annotation.Resource;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import com.ghy.common.utils.BaiduMapUtils;
@Controller @Controller
@RequestMapping("/goods/goods") @RequestMapping("/goods/goods")
@ -58,6 +59,8 @@ public class GoodsController extends BaseController {
private IDeptCategoryInsuranceRelationService deptCategoryInsuranceRelationService; private IDeptCategoryInsuranceRelationService deptCategoryInsuranceRelationService;
@Resource @Resource
private ShopService shopService; private ShopService shopService;
@Resource
private BaiduMapUtils baiduMapUtils;
@RequiresPermissions("goods:goods:view") @RequiresPermissions("goods:goods:view")
@GetMapping() @GetMapping()
@ -436,28 +439,20 @@ public class GoodsController extends BaseController {
countryName != null || streetName != null || countryName != null || streetName != null ||
address != null)) { address != null)) {
try { try {
// 调用百度地理编码接口获取经纬度 // 使用BaiduMapUtils工具类获取经纬度
JSONObject geocodeBody = new JSONObject(); Map<String, Double> coordinates = baiduMapUtils.getCoordinatesByAddress(
geocodeBody.put("provinceName", provinceName); provinceName, cityName, countryName, streetName, address
geocodeBody.put("cityName", cityName); );
geocodeBody.put("countryName", countryName);
geocodeBody.put("streetName", streetName);
geocodeBody.put("address", address);
String url = "https://gmhl.gmjlb.com/tool/baidu/geocode"; if (coordinates != null) {
String resultStr = HttpUtils.sendPost(url, geocodeBody.toJSONString()); userLongitude = coordinates.get("longitude");
userLatitude = coordinates.get("latitude");
JSONObject responseJson = JSONObject.parseObject(resultStr);
if (responseJson.getInteger("code") == 200) {
JSONObject data = responseJson.getJSONObject("data");
userLongitude = data.getDouble("longitude");
userLatitude = data.getDouble("latitude");
logger.info("通过地址获取到用户经纬度: 经度={}, 纬度={}", userLongitude, userLatitude); logger.info("通过地址获取到用户经纬度: 经度={}, 纬度={}", userLongitude, userLatitude);
} else { } else {
logger.warn("通过地址获取用户经纬度失败: {}", responseJson.getString("msg")); logger.warn("通过地址获取用户经纬度失败");
} }
} catch (Exception e) { } 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 || (provinceName != null || cityName != null || countryName != null ||
streetName != null || address != null)) { streetName != null || address != null)) {
try { try {
// 调用百度地理编码接口获取经纬度 // 使用BaiduMapUtils工具类获取经纬度
JSONObject geocodeBody = new JSONObject(); Map<String, Double> coordinates = baiduMapUtils.getCoordinatesByAddress(
geocodeBody.put("provinceName", provinceName); provinceName, cityName, countryName, streetName, address
geocodeBody.put("cityName", cityName); );
geocodeBody.put("countryName", countryName);
geocodeBody.put("streetName", streetName);
geocodeBody.put("address", address);
String url = "https://gmhl.gmjlb.com/tool/baidu/geocode"; if (coordinates != null) {
String resultStr = HttpUtils.sendPost(url, geocodeBody.toJSONString()); longitude = coordinates.get("longitude");
latitude = coordinates.get("latitude");
JSONObject responseJson = JSONObject.parseObject(resultStr);
if (responseJson.getInteger("code") == 200) {
JSONObject data = responseJson.getJSONObject("data");
longitude = data.getDouble("longitude");
latitude = data.getDouble("latitude");
logger.info("通过地址获取到用户经纬度: 经度={}, 纬度={}", longitude, latitude); logger.info("通过地址获取到用户经纬度: 经度={}, 纬度={}", longitude, latitude);
} else { } else {
logger.warn("通过地址获取用户经纬度失败: {}", responseJson.getString("msg")); logger.warn("通过地址获取用户经纬度失败");
} }
} catch (Exception e) { } catch (Exception e) {
logger.error("调用百度地理编码接口异常: {}", e.getMessage(), e); logger.error("调用百度地图API异常: {}", e.getMessage(), e);
} }
} }

View File

@ -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<String, Double> 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<String, Double> 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<String, Double> 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<String, Double> 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;
}
}
}

View File

@ -5,6 +5,7 @@ import com.ghy.shop.domain.ShopDistanceQuery;
import com.ghy.shop.mapper.ShopMapper; import com.ghy.shop.mapper.ShopMapper;
import com.ghy.shop.service.ShopService; import com.ghy.shop.service.ShopService;
import com.ghy.common.utils.LocationUtils; import com.ghy.common.utils.LocationUtils;
import com.ghy.common.utils.BaiduMapUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -21,6 +22,9 @@ public class ShopServiceImpl implements ShopService {
@Autowired @Autowired
private ShopMapper shopMapper; private ShopMapper shopMapper;
@Autowired
private BaiduMapUtils baiduMapUtils;
@Override @Override
public int addShop(Shop shop) { public int addShop(Shop shop) {
return shopMapper.insert(shop); return shopMapper.insert(shop);
@ -95,16 +99,14 @@ public class ShopServiceImpl implements ShopService {
} else if (query.hasAddressInfo()) { } else if (query.hasAddressInfo()) {
// 通过传入的地址信息生成用户位置的经纬度 // 通过传入的地址信息生成用户位置的经纬度
try { try {
String fullAddress = query.getFullAddress(); Map<String, Double> coordinates = baiduMapUtils.getCoordinatesByAddress(
if (!fullAddress.isEmpty()) { query.getProvinceName(), query.getCityName(),
logger.info("通过传入的地址信息生成用户位置经纬度: {}", fullAddress); query.getCountryName(), query.getStreetName(), query.getAddress()
);
Map<String, Double> coordinates = getCoordinatesByAddress(fullAddress); if (coordinates != null) {
if (coordinates != null) { userLat = coordinates.get("latitude");
userLat = coordinates.get("latitude"); userLng = coordinates.get("longitude");
userLng = coordinates.get("longitude"); logger.info("通过传入地址成功生成用户位置经纬度: 经度={}, 纬度={}", userLng, userLat);
logger.info("通过传入地址成功生成用户位置经纬度: 经度={}, 纬度={}", userLng, userLat);
}
} }
} catch (Exception e) { } catch (Exception e) {
logger.warn("通过传入地址生成用户位置经纬度失败: {}", e.getMessage()); logger.warn("通过传入地址生成用户位置经纬度失败: {}", e.getMessage());
@ -119,34 +121,24 @@ public class ShopServiceImpl implements ShopService {
} else if (shop.getAddress() != null && !shop.getAddress().trim().isEmpty()) { } else if (shop.getAddress() != null && !shop.getAddress().trim().isEmpty()) {
// 通过店铺的地址信息生成经纬度 // 通过店铺的地址信息生成经纬度
try { try {
// 构建完整地址 Map<String, Double> coordinates = baiduMapUtils.getCoordinatesByAddress(
StringBuilder fullAddress = new StringBuilder(); shop.getProvinceName(), shop.getCityName(),
if (shop.getProvinceName() != null) fullAddress.append(shop.getProvinceName()); shop.getCountryName(), shop.getStreetName(), shop.getAddress()
if (shop.getCityName() != null) fullAddress.append(shop.getCityName()); );
if (shop.getCountryName() != null) fullAddress.append(shop.getCountryName()); if (coordinates != null) {
if (shop.getStreetName() != null) fullAddress.append(shop.getStreetName()); shopLat = coordinates.get("latitude");
if (shop.getAddress() != null) fullAddress.append(shop.getAddress()); shopLng = coordinates.get("longitude");
logger.info("通过店铺地址成功生成经纬度: 经度={}, 纬度={}", shopLng, shopLat);
String address = fullAddress.toString(); // 更新店铺的经纬度信息
if (!address.isEmpty()) { shop.setLatitude(shopLat);
logger.info("通过店铺地址信息生成经纬度: {}", address); shop.setLongitude(shopLng);
Map<String, Double> coordinates = getCoordinatesByAddress(address); // 如果请求更新店铺位置信息则保存到数据库
if (coordinates != null) { if (query.getUpdateShopLocation() != null && query.getUpdateShopLocation()) {
shopLat = coordinates.get("latitude"); shopMapper.update(shop);
shopLng = coordinates.get("longitude"); logger.info("已更新并保存店铺[{}]的经纬度: 经度={}, 纬度={}",
logger.info("通过店铺地址成功生成经纬度: 经度={}, 纬度={}", shopLng, shopLat); 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) { } catch (Exception e) {
@ -170,49 +162,4 @@ public class ShopServiceImpl implements ShopService {
return -1; return -1;
} }
} }
/**
* 通过地址获取经纬度坐标
* 直接调用百度地图正向地理编码API
*/
private Map<String, Double> 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<String, Double> 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;
}
}
} }