高德地图API:如何根据经纬度获取位置信息

高德地图API:如何根据经纬度获取位置信息

根据前端传入的经纬度获取用户当前所在位置


工具类

package com.daihuoyu.bargain.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.daihuoyu.bargain.vo.LocationVO;
import com.daihuoyu.base.utils.HttpClientBuilder;
import com.daihuoyu.user.web.account.log.AccountLoggerEnum;
import com.owitho.arch.logger.ArchLogger;
import com.owitho.arch.logger.LoggerManager;
import org.apache.commons.lang3.StringUtils;
import java.util.SortedMap;
import java.util.TreeMap;

public class LocationUtil {
    private static final ArchLogger ERROR_LOGGER = LoggerManager.getLogger(AccountLoggerEnum.C_SPU_ERROR.getValue());
	// httpClient
    private static final HttpClientBuilder.HttpClient httpClient = new HttpClientBuilder().build();
    private static final String KEY = "";
    public static final String AMAP_LOCATION_URL = "http://restapi.amap.com/v3/geocode/regeo";

    /**
     * 定位
     * @param userlng 经度
     * @param userlat 维度
     */
    public static LocationVO locate(String userlng, String userlat) {
        LocationVO locationVO = new LocationVO();

        SortedMap<String, String> map = new TreeMap<>();
        map.put("key", KEY);
        map.put("extensions", "all");
        map.put("location", userlng + "," + userlat);

        JSONObject result = new JSONObject();
        try {
            String resp = httpClient.open(AMAP_LOCATION_URL).get(map);
            result = JSON.parseObject(resp);
        } catch (Exception e) {
            ERROR_LOGGER.error("locate exception",e);
        }

        JSONObject regeocode = result.getJSONObject("regeocode");
        if (regeocode != null) {
            JSONObject addressComponent = regeocode.getJSONObject("addressComponent");
            JSONObject streetNumber = addressComponent.getJSONObject("streetNumber");
            if (streetNumber != null) {
                String address = streetNumber.getString("street") + streetNumber.getString("number");
                String city = addressComponent.getString("city");
                if (StringUtils.isBlank(city) || city.contains("[]")) {
                    city = addressComponent.getString("province");
                }
                locationVO.setLocationName(city + addressComponent.getString("district") + address);
            }

            JSONArray aois = regeocode.getJSONArray("aois");
            if (aois != null && !aois.isEmpty()) {
                JSONObject aoi = aois.getJSONObject(0);
               locationVO.setLocationName(locationVO.getLocationName() + aoi.getString("name"));
            }
        }
        return locationVO;
    }

    public static void main(String[] args) {
        String lng="121.444013",lat="31.280771";
        LocationVO locate = locate(lng, lat);
        System.out.println(locate);
    }

你可能感兴趣的:(util,工具类,定位,java,小程序)