• 小程序实现定位城市切换且城市根据首字母A-Z排序后端数据实现逻辑


    场景:

    话不多说后端提供数据实现步骤:

    1.controller层

    1. @Api(tags = {"[地区]-城市相关接口"})
    2. @RestController
    3. @RequestMapping("region")
    4. @Slf4j
    5. public class RegionController extends BaseController {
    6. @Resource
    7. private RegionService regionService;
    8. @ApiOperation("城市列表[A-Z]")
    9. @ApiImplicitParams({
    10. @ApiImplicitParam(name = "condition", value = "城市名称", required = false, paramType = "query")})
    11. @GetMapping("cityList")
    12. public JsonResult> cityList(@RequestParam(value = "condition", required = false) String condition) {
    13. return JsonResult.ok(this.regionService.smallProgramCityDisplayList(condition));
    14. }
    15. @ApiOperation("城市列表")
    16. @ApiImplicitParams({
    17. @ApiImplicitParam(name = "condition", value = "城市名称", required = false, paramType = "query")})
    18. @GetMapping("queryCityList")
    19. public JsonResult> queryCityList(@RequestParam(value = "condition", required = false) String condition) {
    20. return JsonResult.ok(this.regionService.queryCityList(condition));
    21. }
    22. @Resource
    23. private TencentMapUtil tencentMapUtil;
    24. @ApiOperation("根据经纬度查询地址")
    25. @GetMapping("tencent/map/reGeoCoder")
    26. public JsonResult reGeoCoder(String lat, String lng) {
    27. AssertUtil.notBlank(lat, "纬度不能为空");
    28. AssertUtil.notBlank(lng, "经度不能为空");
    29. JSONObject jsonObject = tencentMapUtil.reGeoCoder(lat, lng);
    30. if (EntityConstant.INVALID != jsonObject.getInteger("status")) {
    31. log.error("定位授权失败 , errorMsg = {}", jsonObject.getString("message"));
    32. throw SimpleException.getInstance("定位授权失败");
    33. }
    34. JSONObject adInfo = jsonObject.getJSONObject("result").getJSONObject("ad_info");
    35. String city_code = adInfo.getString("city_code");
    36. String nation_code = adInfo.getString("nation_code");
    37. jsonObject.getJSONObject("result").getJSONObject("ad_info").put("cityCode", city_code.replaceAll(nation_code, ""));
    38. return JsonResult.ok(jsonObject);
    39. }
    40. }

    2.service层

    1. @Service
    2. @Slf4j
    3. @Primary
    4. public class RegionServiceImpl extends BaseApplicationService implements RegionService {
    5. @Resource
    6. private RegionMapper regionMapper;
    7. private static final char[] alphabet = new char[26];
    8. static {
    9. // 使用循环填充数组元素
    10. for (int i = 0; i < alphabet.length; i++) {
    11. alphabet[i] = (char) ('A' + i);
    12. }
    13. }
    14. @Override
    15. public List smallProgramCityDisplayList(String condition) {
    16. List regionList = this.regionMapper.selectByExample(
    17. new ExampleLambda<>(Region.class)
    18. .andEqualTo(Region::getStatus, EntityConstant.NORMAL)
    19. .andEqualTo(Region::getLevel, 2)
    20. .andLike(Objects.nonNull(condition), Region::getName, condition)
    21. .end()
    22. );
    23. Map> cityMap = regionList.stream().collect(Collectors.groupingBy(Region::getInitial));
    24. List cityListVOList = new ArrayList<>(this.alphabet.length);
    25. for (char c : this.alphabet) {
    26. List tempList = cityMap.containsKey(String.valueOf(c)) ? cityMap.get(String.valueOf(c)).stream().map(item -> {
    27. AppletCityListVO.CityItem cityItem = new AppletCityListVO.CityItem();
    28. cityItem.setCode(item.getCode());
    29. cityItem.setName(item.getName());
    30. return cityItem;
    31. }).collect(Collectors.toList()) : new ArrayList<>(0);
    32. cityListVOList.add(AppletCityListVO.builder().initial(String.valueOf(c)).itemList(tempList).build());
    33. }
    34. return cityListVOList;
    35. }
    36. @Override
    37. public List queryCityList(String condition) {
    38. List regionList = this.regionMapper.selectByExample(
    39. new ExampleLambda<>(Region.class)
    40. .andEqualTo(Region::getStatus, EntityConstant.NORMAL)
    41. .andEqualTo(Region::getLevel, 2)
    42. .andLike(Objects.nonNull(condition), Region::getName, condition)
    43. .end()
    44. );
    45. return regionList.stream().map(item -> {
    46. AppletCityListVO.CityItem cityItem = new AppletCityListVO.CityItem();
    47. cityItem.setCode(item.getCode());
    48. cityItem.setName(item.getName());
    49. return cityItem;
    50. }).collect(Collectors.toList());
    51. }
    52. }
    53. @Builder
    54. @Data
    55. public class AppletCityListVO implements Serializable {
    56. @ApiModelProperty(value = "首字母")
    57. private String initial;
    58. @ApiModelProperty(value = "城市列表")
    59. private List itemList;
    60. @Data
    61. public static class CityItem {
    62. @ApiModelProperty(value = "code")
    63. private String code;
    64. @ApiModelProperty(value = "名称")
    65. private String name;
    66. public CityItem(String code, String name) {
    67. this.code = code;
    68. this.name = name;
    69. }
    70. public CityItem() {
    71. }
    72. }
    73. }

    3.mapper层

    1. public interface RegionMapper extends CrudMapper {
    2. }


    4.实体类

    1. @Table(name = "`region`")
    2. @Data
    3. public class Region extends BaseEntity implements Serializable {
    4. private static final long serialVersionUID = 1L;
    5. /**
    6. * Id
    7. */
    8. @Id
    9. @GeneratedValue(strategy = GenerationType.IDENTITY)
    10. private Long id;
    11. /**
    12. * 1
    13. */
    14. @Column(name = "level")
    15. private Integer level;
    16. /**
    17. * code
    18. */
    19. @Column(name = "code")
    20. private String code;
    21. /**
    22. * 父级code
    23. */
    24. @Column(name = "parent_code")
    25. private String parentCode;
    26. /**
    27. * 名称
    28. */
    29. @Column(name = "name")
    30. private String name;
    31. /**
    32. * 名称拼音
    33. */
    34. @Column(name = "pinyin")
    35. private String pinyin;
    36. /**
    37. * 首字母
    38. */
    39. @Column(name = "initial")
    40. private String initial;
    41. /**
    42. * 状态
    43. */
    44. @Column(name = "status")
    45. private Integer status;
    46. /**
    47. * 创建时间
    48. */
    49. @Column(name = "gmt_created")
    50. @JsonFormat(locale = "zh", pattern = "yyyy-MM-dd HH:mm:ss")
    51. private Date gmtCreated;
    52. /**
    53. * ModifyUser
    54. */
    55. @Column(name = "modify_user")
    56. private String modifyUser;
    57. /**
    58. * CreateUser
    59. */
    60. @Column(name = "create_user")
    61. private String createUser;
    62. /**
    63. * 更新时间
    64. */
    65. @Column(name = "gmt_modified")
    66. @JsonFormat(locale = "zh", pattern = "yyyy-MM-dd HH:mm:ss")
    67. private Date gmtModified;
    68. /**
    69. * 是否删除
    70. */
    71. @Column(name = "deleted")
    72. private Integer deleted;
    73. }


    5.腾讯地图处理工具类

    1. import cn.hutool.http.HttpUtil;
    2. import cn.hutool.json.JSONObject;
    3. import cn.hutool.json.JSONUtil;
    4. import lombok.extern.slf4j.Slf4j;
    5. import org.apache.commons.lang.StringUtils;
    6. import org.springframework.stereotype.Component;
    7. import java.util.HashMap;
    8. import java.util.Objects;
    9. @Slf4j
    10. @Component
    11. public class TencentMapUtil {
    12. private String qqAk = "xxxxx-xxxxx-xxxxx-xxxxx-xxxxx-xxxxx";
    13. private String geoCoder = "https://apis.map.qq.com/ws/geocoder/v1/";
    14. private String distance = "https://apis.map.qq.com/ws/distance/v1/";
    15. private String translate = "https://apis.map.qq.com/ws/coord/v1/translate";
    16. private String reGeoCoder = "https://apis.map.qq.com/ws/geocoder/v1/?location=";
    17. /**
    18. * 通过地址查询经纬度
    19. *
    20. * @param addr 地址
    21. * @return
    22. */
    23. public String geoCoder(String addr) {
    24. JSONObject jsonObject = geoCoderRequest(addr);
    25. if (null == jsonObject) {
    26. return null;
    27. }
    28. JSONObject location = JSONUtil.parseObj(JSONUtil.toJsonStr(jsonObject.get("location")));
    29. if (Objects.nonNull(location) && Objects.nonNull(location.get("lat")) && Objects.nonNull(location.get("lng"))) {
    30. return location.get("lat").toString() + "," + location.get("lng").toString();
    31. }
    32. return null;
    33. }
    34. public JSONObject geoCoderRequest(String addr) {
    35. try {
    36. if (StringUtils.isNotEmpty(addr)) {
    37. String url = geoCoder +
    38. "?address=" + addr +
    39. "&key=" + qqAk;// 腾讯地图ak
    40. String resultStr = HttpUtil.get(url);
    41. JSONObject tencentGeo = JSONUtil.parseObj(resultStr);
    42. log.info("地址转坐标响应结果:" + JSONUtil.toJsonStr(tencentGeo));
    43. if (Objects.nonNull(tencentGeo) && Objects.equals(0, tencentGeo.get("status"))) {
    44. return JSONUtil.parseObj(JSONUtil.toJsonStr(tencentGeo.get("result")));
    45. }
    46. }
    47. } catch (Exception e) {
    48. log.error("地址转坐标失败,地址:" + addr + ", e: " + e);
    49. }
    50. return null;
    51. }
    52. /**
    53. * 根据经纬度查询地址
    54. *
    55. * @param lat 纬度
    56. * @param lng 经度
    57. * @return
    58. */
    59. public JSONObject reGeoCoder(String lat, String lng) {
    60. StringBuilder url = new StringBuilder(reGeoCoder)
    61. .append(lat).append(",").append(lng)
    62. .append("&key=").append(qqAk);
    63. String resultStr = HttpUtil.get(url.toString());
    64. return JSONUtil.parseObj(resultStr);
    65. }
    66. /**
    67. * 将微信小程序经纬度转换成腾讯地图经纬度
    68. *
    69. * @param lat 纬度
    70. * @param lng 经度
    71. * @return
    72. */
    73. public JSONObject translate(String lat, String lng) {
    74. StringBuilder url = new StringBuilder(translate)
    75. .append("?key=").append(qqAk)// 腾讯地图ak
    76. .append("&type=1")// 1.GPS坐标 2.sogou经纬度 3.baidu经纬度 4.mapbar经纬度 5.[默认]腾讯、google、高德坐标 6.sogou墨卡托
    77. .append("&&locations=").append(lat).append(",").append(lng);
    78. String resultStr = HttpUtil.get(url.toString());
    79. return JSONUtil.parseObj(resultStr);
    80. }
    81. }
    6.region.sql文件 

     链接: https://pan.baidu.com/s/1m1WEgQPGXbUzgZ4qusvegQ 提取码: ztr6 复制这段内容后打开百度网盘手机App,操作更方便哦

     

  • 相关阅读:
    RTOS那些你得知道的事儿(一)
    Nest.js项目小结1
    win11系统中nginx简单的代理配置
    pycharm运行os.system出现�����ڲ����ⲿ���Ҳ���ǿ����еij��� ���������ļ���
    民办二本计算机毕业以后
    java的包装类
    GRE MGRE原理与配置
    基于springboot+vue的社区医院管理服务系统
    matlab实现神经网络算法,人工神经网络matlab代码
    C++征途 --- STL常用算法(上)
  • 原文地址:https://blog.csdn.net/qq_40083897/article/details/136363980