zoukankan      html  css  js  c++  java
  • 高德地图API实现web服务端导航和定位等功能

    package com.example.combat.gaodemapUtils;
    
    import cn.hutool.core.io.FileUtil;
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    import com.example.combat.gaodemapUtils.param.GaodeMapConstant;
    import com.example.combat.gaodemapUtils.param.Geocodes;
    import com.example.combat.gaodemapUtils.param.req.*;
    import com.google.common.collect.Maps;
    import com.sun.org.apache.regexp.internal.RE;
    import io.swagger.annotations.ApiImplicitParam;
    import io.swagger.annotations.ApiImplicitParams;
    import io.swagger.annotations.ApiOperation;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.codec.binary.Base64;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.utils.URIBuilder;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.cglib.beans.BeanMap;
    import org.springframework.stereotype.Component;
    import org.springframework.util.StringUtils;
    import sun.misc.BASE64Decoder;
    
    import javax.imageio.ImageIO;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletResponse;
    import java.awt.image.BufferedImage;
    import java.awt.image.RenderedImage;
    import java.io.*;
    import java.net.URL;
    import java.net.URLDecoder;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.Random;
    import java.util.zip.GZIPOutputStream;
    
    import static com.example.combat.gaodemapUtils.HttpUtil.covertParams2NVPS;
    
    /**
     * @description: 高德地图工具类
     * @author: zhucj
     * @date: 2019-11-25 17:22
     */
    @Component
    @Slf4j
    public class GaodeMapUtil {
    
    
        @Value("${gaodemap.key}")
        private String key;
    
        @Value("${gaodemap.pathImg}")
        private String pathImg;
    
        /**
         * 结构化地址信息查询
         * @param geocodeRequestVo
         * @return
         */
        @ApiOperation(value ="结构化地址信息查询")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "address",value = "结构化地址信息",required = true,dataType = "String"),
                @ApiImplicitParam(name = "city",value = "指定查询城市 城市的中文或中文全拼 ",required = false,dataType = "String")
        })
        public R getGeocodes(GeocodeRequestVo geocodeRequestVo) {
            log.info("==>查询结构化地址:"+geocodeRequestVo.getAddress());
            //是否支持批量查询 true:支持 false:不支持
            geocodeRequestVo.setBatch(false);
            //支持的格式XML,JSON
            geocodeRequestVo.setOutput(GaodeMapConstant.JSON);
            Map<String, Object> stringObjectMap = beanToMap(geocodeRequestVo);
            stringObjectMap.put(GaodeMapConstant.KEY,key);
            String resultJson = null;
            try {
                resultJson = HttpUtil.httpGet(GaodeMapConstant.GEOCODE_GEO, stringObjectMap);
            } catch (Exception e) {
                log.error("请求服务异常:{}",e.getMessage());
                return R.error("请求服务异常").setCode(SystemConstant.SERVER_ERROR_CODE);
            }
            JSONObject jsonObject = JSON.parseObject(resultJson);
            if (Objects.equals(GaodeMapConstant.SUCCESS,jsonObject.get("status"))){
                String geocodes = JSON.toJSONString(jsonObject.get("geocodes"));
                List<Geocodes> geocodes1 = JSON.parseArray(geocodes, Geocodes.class);
                return R.ok(geocodes1.get(0)).setCode(SystemConstant.SUCCESS_CODE);
            }else {
                log.info("获取地址信息失败,原因:{}",jsonObject.get("info"));
                return R.error(jsonObject.get("info").toString()).setCode(SystemConstant.SERVER_ERROR_CODE);
            }
        }
    
        /**
         * 通过经纬度,获取地理位置信息
         * @param geocodeRequestVo
         * @return
         */
        @ApiOperation(value = "获取逆地理编码信息列表",notes = "朱传捷")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "location",value = "经纬度(格式:116.481488,39.990464)",required = true,dataType = "String"),
                @ApiImplicitParam(name = "poitype",value = "返回附近POI类型(extensions 参数为 all 时才生效)",required = false,dataType = "String"),
                @ApiImplicitParam(name = "radius",value = "搜索半径",required = false,dataType = "String"),
                @ApiImplicitParam(name = "extensions",value = "返回结果控制(base和all)",required = false,dataType = "String"),
                @ApiImplicitParam(name = "roadlevel",value = "道路等级",required = false,dataType = "String")
        })
        public R getReGeocodes(GeocodeRequestVo geocodeRequestVo) {
            //是否支持批量查询 true:支持 false:不支持
            geocodeRequestVo.setBatch(false);
            //支持的格式XML,JSON
            geocodeRequestVo.setOutput(GaodeMapConstant.JSON);
            Map<String, Object> stringObjectMap = beanToMap(geocodeRequestVo);
            stringObjectMap.put(GaodeMapConstant.KEY,key);
            try {
                String resultJson = HttpUtil.httpGet(GaodeMapConstant.GEOCODE_REGEO, stringObjectMap);
                JSONObject jsonObject = JSON.parseObject(resultJson);
                if (Objects.equals(GaodeMapConstant.SUCCESS,jsonObject.get("status"))){
                    return R.ok(jsonObject.get("regeocode")).setCode(SystemConstant.SUCCESS_CODE);
                }else {
                    return R.error(jsonObject.get("info").toString()).setCode(SystemConstant.SERVER_ERROR_CODE);
                }
            } catch (Exception e) {
                log.error("通过经纬度获取地址失败:{}",e.getMessage());
                return R.error("获取地址失败").setCode(SystemConstant.SERVER_ERROR_CODE);
            }
        }
    
        /**
         * 路线规划
         * @param directionRequestVo
         * @return
         */
        @ApiOperation(value = "地图路线规划,支持步行、公交、驾车方式")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "directionType",value = "交通工具类型1:步行 2:公交 3:驾车",required = true,dataType = "Integer"),
                @ApiImplicitParam(name = "origin",value = "出发点经纬度",required = true,dataType = "String"),
                @ApiImplicitParam(name = "destination",value = "终点经纬度",required = true,dataType = "String"),
                @ApiImplicitParam(name = "city",value = "城市/跨城规划时的起点城市,directionType = 2时必传",required = false,dataType = "String"),
                @ApiImplicitParam(name = "strategy",value = "换乘策略",required = false,dataType = "Integer")
        })
        public R getDirection(DirectionRequestVo directionRequestVo) {
            if (StringUtils.isEmpty(directionRequestVo.getOrigin())){
                return R.error(GaodeMapConstant.ERR_ORIGIN_PARAM_NULL).setCode(SystemConstant.PARAM_INCORRECT_CODE);
            }
            if (StringUtils.isEmpty(directionRequestVo.getDestination())){
                return R.error(GaodeMapConstant.ERR_DESTINATION_PARAM_NULL).setCode(SystemConstant.PARAM_INCORRECT_CODE);
            }
            //判断路线规划类型,目前只支持3种,strategy=2时,city城市名称
            String reqUrl = null;
            switch (directionRequestVo.getStrategy()){
                case 1:
                    reqUrl = GaodeMapConstant.DIRECTION_WALKING;
                    break;
                case 2:
                    if (StringUtils.isEmpty(directionRequestVo.getCity())){
                        return R.error(GaodeMapConstant.ERR_CITY_PARAM_NULL).setCode(SystemConstant.PARAM_INCORRECT_CODE);
                    }
                    reqUrl = GaodeMapConstant.DIRECTION_INTEGRATED;
                    break;
    
                case 3:
                    reqUrl = GaodeMapConstant.DIRECTION_DRIVING;
                    break;
                    default:
                        return R.error(GaodeMapConstant.ERR_DIRECTIONTYPE_PARAM_NULL).setCode(SystemConstant.PARAM_INCORRECT_CODE);
            }
            Map<String, Object> stringObjectMap = beanToMap(directionRequestVo);
            stringObjectMap.put(GaodeMapConstant.KEY,key);
            try {
                String rusultStr = HttpUtil.httpGet(reqUrl, stringObjectMap);
                JSONObject jsonObject = JSON.parseObject(rusultStr);
                if (Objects.equals(GaodeMapConstant.SUCCESS,jsonObject.get("status"))){
                    return R.ok(jsonObject.get("route"));
                }else {
                    log.error("查询路线规划失败:{}",jsonObject.get("info").toString());
                    return R.error(jsonObject.get("info").toString()).setCode(SystemConstant.SERVER_ERROR_CODE);
                }
            } catch (Exception e) {
                log.error("查询路线规划异常:{}",e.getMessage());
                return R.error("查询路线规划异常").setCode(SystemConstant.SERVER_ERROR_CODE);
            }
        }
    
        /**
         * 静态地图
         * @param staticMapRequest
         */
        @ApiOperation(value = "生成静态地图")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "locations",value = "经纬度集合",required = true,dataType = "List"),
                @ApiImplicitParam(name = "zoom",value = "地图缩放级别:[1,17]",required = true,dataType = "String"),
                @ApiImplicitParam(name = "size",value = "图片宽度*图片高度。最大值为1024*1024",required = true,dataType = "String"),
                @ApiImplicitParam(name = "scale",value = "清晰度",required = true,dataType = "Integer")
        })
        public void staticMap(StaticMapRequest staticMapRequest, HttpServletResponse response){
    
            //设置地图缩放级别
            staticMapRequest.setZoom(staticMapRequest.getZoom());
            //地图大小
            staticMapRequest.setSize(staticMapRequest.getSize());
            //设置高清
            staticMapRequest.setScale(staticMapRequest.getScale());
            List<String> localhosts = staticMapRequest.getLocalhosts();
            //设置默认第一个和最后一个点,标注,起,终
            Markers marker1 = Markers
                    .builder()
                    .color("0xFF0000")
                    .size("mid")
                    .label("起:"+localhosts.get(0))
                    .build();
            Markers markers2 = Markers
                    .builder()
                    .size("mid")
                    .color("0xFF0000")
                    .label("终:"+localhosts.get(localhosts.size()-1))
                    .build();
            //拼接markers属性
            String setMarkers1 = marker1.getSize()+","+marker1.getColor()+","+marker1.getLabel();
            String setMarkers2 = markers2.getSize()+","+markers2.getColor()+","+markers2.getLabel();
            staticMapRequest.setMarkers(setMarkers1+"|"+setMarkers2);
            //绘制折线
            Paths paths = Paths
                    .builder()
                    .weight(5)
                    .color("0xFF0000")
                    .transparency("1")
                    .build();
            StringBuilder stringBuilder = new StringBuilder();
            for (String localhost:localhosts){
                stringBuilder.append(localhost+";");
            }
            String s = stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString();
            String path = paths.getWeight()+","+paths.getColor()+","+paths.getTransparency()+","+","+":"+s;
            staticMapRequest.setPaths(path);
            Map<String, Object> stringObjectMap = beanToMap(staticMapRequest);
            stringObjectMap.put(GaodeMapConstant.KEY,key);
            try {
                // 转换请求参数
                List<NameValuePair> pairs = covertParams2NVPS(stringObjectMap);
                // 装载请求地址和参数
                URIBuilder ub = new URIBuilder();
                ub.setPath(GaodeMapConstant.STATUC_MAP);
                ub.setParameters(pairs);
                String s1 = ub.toString();
                String compress = compress(s1,pathImg );
                exportImg(response,pathImg+compress);
            } catch (Exception e) {
                log.error("下载图片异常"+e.getMessage());
            }
        }
        /**
         * bean -> map 实体类转map
         * @param bean
         * @param <T>
         * @return
         */
        public static <T> Map<String, Object> beanToMap(T bean) {
            Map<String, Object> map = Maps.newHashMap();
            if (bean != null) {
                BeanMap beanMap = BeanMap.create(bean);
                for (Object key : beanMap.keySet()) {
                    if (Objects.nonNull(beanMap.get(key)) && !(Objects.equals("",beanMap.get(key)))){
                        map.put(key + "",beanMap.get(key));
                    }
                }
            }
            return map;
        }
    
        /**
         * 下载地图
         * @param url
         * @param path
         * @return
         */
        public static String compress(String url,String path) {
            try {
                String imageName = "map.png";
                File file = new File(path +  imageName);
                //判断文件是否已经存在
                if (file.exists()) {
                    file.delete();
                }
                file.createNewFile();
                URL uri = new URL(url);
                InputStream in = uri.openStream();
                FileOutputStream fo = new FileOutputStream(file);
                byte[] buf = new byte[1024];
                int length = 0;
                while ((length = in.read(buf, 0, buf.length)) != -1) {
                    fo.write(buf, 0, length);
                }
                in.close();
                fo.close();
                return imageName;
            } catch (Exception e) {
                log.error("下载失败",e.getMessage());
                return null;
            }
    
        }
    
        /**
         * 输出图片
         * @param response
         * @param filePath
         */
        public static void exportImg(HttpServletResponse response, String filePath) {
            File file = new File(filePath);
            response.setCharacterEncoding("utf-8");
            //设置响应的内容类型
            response.setContentType("text/plain");
            //设置文件的名称和格式
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + file.getName());
            BufferedOutputStream buff = null;
            ServletOutputStream outStr = null;
            try {
                outStr = response.getOutputStream();
                buff = new BufferedOutputStream(outStr);
                buff.write(FileUtil.readBytes(filePath));
                buff.flush();
                buff.close();
            } catch (Exception e) {
                e.printStackTrace();
                log.error("文件导出异常:", e);
            } finally {
                try {
                    buff.close();
                } catch (Exception e) {
                    log.error("流关闭异常:", e);
                }
                try {
                    outStr.close();
                } catch (Exception e) {
                    log.error("流关闭异常:", e);
                }
            }
        }
    
    }
    package com.example.combat.gaodemapUtils;
    
    import com.alibaba.fastjson.JSON;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.codec.binary.Base64;
    import org.apache.http.HttpEntity;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.methods.HttpRequestBase;
    import org.apache.http.client.utils.URIBuilder;
    import org.apache.http.config.Registry;
    import org.apache.http.config.RegistryBuilder;
    import org.apache.http.conn.socket.ConnectionSocketFactory;
    import org.apache.http.conn.socket.PlainConnectionSocketFactory;
    import org.apache.http.conn.ssl.NoopHostnameVerifier;
    import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.entity.ContentType;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.ssl.SSLContextBuilder;
    import org.apache.http.ssl.SSLContexts;
    import org.apache.http.ssl.TrustStrategy;
    import org.apache.http.util.EntityUtils;
    
    import javax.net.ssl.SSLContext;
    import java.io.*;
    import java.nio.charset.StandardCharsets;
    import java.security.KeyStore;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.zip.GZIPInputStream;
    import java.util.zip.GZIPOutputStream;
    
    @Slf4j
    public class HttpUtil {
    
        public static final ContentType TEXT_PLAIN = ContentType.create("text/plain", StandardCharsets.UTF_8);
    
        /**
         * HttpClient 连接池
         */
        private static PoolingHttpClientConnectionManager cm = null;
    
        static {
            // 初始化连接池,可用于请求HTTP/HTTPS(信任所有证书)
            cm = new PoolingHttpClientConnectionManager(getRegistry());
            // 整个连接池最大连接数
            cm.setMaxTotal(200);
            // 每路由最大连接数,默认值是2
            cm.setDefaultMaxPerRoute(5);
        }
    
        /**
         * 发送 HTTP GET请求
         * <p>不带请求参数和请求头</p>
         * @param url 地址
         * @return
         * @throws Exception
         */
        public static String httpGet(String url) throws Exception {
            log.info("请求参数:{}",url);
            HttpGet httpGet = new HttpGet(url);
    
            return doHttp(httpGet);
        }
    
        /**
         * 发送 HTTP GET请求
         * <p>带请求参数,不带请求头</p>
         * @param url    地址
         * @param params 参数
         * @return
         * @throws Exception
         * @throws Exception
         */
        public static String httpGet(String url, Map<String, Object> params) throws Exception {
            // 转换请求参数
            List<NameValuePair> pairs = covertParams2NVPS(params);
    
            // 装载请求地址和参数
            URIBuilder ub = new URIBuilder();
            ub.setPath(url);
            ub.setParameters(pairs);
            HttpGet httpGet = new HttpGet(ub.build());
    
            return doHttp(httpGet);
        }
    
        /**
         * 发送 HTTP GET请求
         * <p>带请求参数和请求头</p>
         * @param url     地址
         * @param headers 请求头
         * @param params  参数
         * @return
         * @throws Exception
         * @throws Exception
         */
        public static String httpGet(String url, Map<String, Object> headers, Map<String, Object> params) throws Exception {
            // 转换请求参数
            List<NameValuePair> pairs = covertParams2NVPS(params);
    
            // 装载请求地址和参数
            URIBuilder ub = new URIBuilder();
            ub.setPath(url);
            ub.setParameters(pairs);
    
            HttpGet httpGet = new HttpGet(ub.build());
            // 设置请求头
            for (Map.Entry<String, Object> param : headers.entrySet()){
                httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));}
    
            return doHttp(httpGet);
        }
    
        /**
         * 发送 HTTP POST请求
         * <p>不带请求参数和请求头</p>
         *
         * @param url 地址
         * @return
         * @throws Exception
         */
        public static String httpPost(String url) throws Exception {
            HttpPost httpPost = new HttpPost(url);
    
            return doHttp(httpPost);
        }
    
        /**
         * 发送 HTTP POST请求
         * <p>带请求参数,不带请求头</p>
         *
         * @param url    地址
         * @param params 参数
         * @return
         * @throws Exception
         */
        public static String httpPost(String url, Map<String, Object> params) throws Exception {
            // 转换请求参数
            List<NameValuePair> pairs = covertParams2NVPS(params);
    
            HttpPost httpPost = new HttpPost(url);
            // 设置请求参数
            httpPost.setEntity(new UrlEncodedFormEntity(pairs, StandardCharsets.UTF_8.name()));
    
            return doHttp(httpPost);
        }
    
        /**
         * 发送 HTTP POST请求
         * <p>带请求参数和请求头</p>
         *
         * @param url     地址
         * @param headers 请求头
         * @param params  参数
         * @return
         * @throws Exception
         */
        public static String httpPost(String url, Map<String, Object> headers, Map<String, Object> params) throws Exception {
            log.info("POST请求参数:{}",params);
            HttpPost httpPost = new HttpPost(url);
            // 设置请求参数
            StringEntity entity = new StringEntity(JSON.toJSONString(params),ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 设置请求头
            for (Map.Entry<String, Object> param : headers.entrySet()){
                httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));}
    
            return doHttp(httpPost);
        }
    
    
    
    
        /**
         * 转换请求参数
         *
         * @param params
         * @return
         */
        public static List<NameValuePair> covertParams2NVPS(Map<String, Object> params) {
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    
            for (Map.Entry<String, Object> param : params.entrySet()){
                pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));}
    
            return pairs;
        }
    
        /**
         * 发送 HTTP 请求
         *
         * @param request
         * @return
         * @throws Exception
         */
        private static String doHttp(HttpRequestBase request) throws Exception {
            // 通过连接池获取连接对象
            CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
    
            return doRequest(httpClient, request);
        }
    
        /**
         * 发送 HTTPS 请求
         * <p>使用指定的证书文件及密码</p>
         *
         * @param request
         * @param path
         * @param password
         * @return
         * @throws Exception
         * @throws Exception
         */
        private static String doHttps(HttpRequestBase request, String path, String password) throws Exception {
            // 获取HTTPS SSL证书
            SSLConnectionSocketFactory csf = getSSLFactory(path, password);
            // 通过连接池获取连接对象
            CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
    
            return doRequest(httpClient, request);
        }
    
        /**
         * 获取HTTPS SSL连接工厂
         * <p>使用指定的证书文件及密码</p>
         *
         * @param path     证书全路径
         * @param password 证书密码
         * @return
         * @throws Exception
         * @throws Exception
         */
        private static SSLConnectionSocketFactory getSSLFactory(String path, String password) throws Exception {
    
            // 初始化证书,指定证书类型为“PKCS12”
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            // 读取指定路径的证书
            FileInputStream input = new FileInputStream(new File(path));
    
            try {
                // 装载读取到的证书,并指定证书密码
                keyStore.load(input, password.toCharArray());
            } finally {
                input.close();
            }
    
            // 获取HTTPS SSL证书连接上下文
            SSLContext sslContext = SSLContexts.custom().loadKeyMaterial(keyStore, password.toCharArray()).build();
    
            // 获取HTTPS连接工厂,指定TSL版本
            SSLConnectionSocketFactory sslCsf = new SSLConnectionSocketFactory(sslContext, new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    
            return sslCsf;
        }
    
        /**
         * 获取HTTPS SSL连接工厂
         * <p>跳过证书校验,即信任所有证书</p>
         *
         * @return
         * @throws Exception
         */
        private static SSLConnectionSocketFactory getSSLFactory() throws Exception {
            // 设置HTTPS SSL证书信息,跳过证书校验,即信任所有证书请求HTTPS
            SSLContextBuilder sslBuilder = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            });
    
            // 获取HTTPS SSL证书连接上下文
            SSLContext sslContext = sslBuilder.build();
    
            // 获取HTTPS连接工厂
            SSLConnectionSocketFactory sslCsf = new SSLConnectionSocketFactory(sslContext, new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
    
            return sslCsf;
        }
    
        /**
         * 获取 HTTPClient注册器
         *
         * @return
         * @throws Exception
         */
        private static Registry<ConnectionSocketFactory> getRegistry() {
            Registry<ConnectionSocketFactory> registry = null;
    
            try {
                registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", new PlainConnectionSocketFactory()).register("https", getSSLFactory()).build();
            } catch (Exception e) {
                log.error("获取 HTTPClient注册器失败", e);
            }
    
            return registry;
        }
    
    
        /**
         * 处理Http/Https请求,并返回请求结果
         * <p>注:默认请求编码方式 UTF-8</p>
         *
         * @param httpClient
         * @param request
         * @return
         * @throws Exception
         */
        private static String doRequest(CloseableHttpClient httpClient, HttpRequestBase request) throws Exception {
            String result = null;
            CloseableHttpResponse response = null;
    
            try {
                // 获取请求结果
                response = httpClient.execute(request);
                // 解析请求结果
                HttpEntity entity = response.getEntity();
                if ((entity.getContentEncoding() != null)
                        && entity.getContentEncoding().getValue().contains("gzip")) {
                    GZIPInputStream gzip = new GZIPInputStream(
                            new ByteArrayInputStream(EntityUtils.toByteArray(entity)));
                    InputStreamReader isr = new InputStreamReader(gzip);
                    BufferedReader br = new BufferedReader(isr);
                    StringBuilder sb = new StringBuilder();
                    String temp;
                    while((temp = br.readLine()) != null){
                        sb.append(temp);
                        sb.append("
    ");
                    }
                    isr.close();
                    gzip.close();
                    return sb.toString();
                }
                // 转换结果
                result = EntityUtils.toString(entity, StandardCharsets.UTF_8.name());
                // 关闭IO流
                EntityUtils.consume(entity);
            } finally {
                if (null != response){
                    response.close();}
            }
    
            return result;
        }
    
    
    }
    package com.example.combat.gaodemapUtils;
    
    import io.swagger.annotations.ApiModel;
    import io.swagger.annotations.ApiModelProperty;
    import lombok.ToString;
    
    import java.io.Serializable;
    
    /**
     * 返回类型
     * @author choleece
     * @date 2018/9/27
     */
    @ApiModel
    @ToString
    public class R<T> implements Serializable {
    
        private static final long serialVersionUID = -6287952131441663819L;
    
        /**
         * 编码
         */
        @ApiModelProperty(value = "响应码", example = "200")
        private int code = 200;
    
        /**
         * 成功标志
         */
        @ApiModelProperty(value = "成功标志", example = "true")
        private Boolean success;
    
        /**
         * 返回消息
         */
        @ApiModelProperty(value = "返回消息说明", example = "操作成功")
        private String msg="操作成功";
    
        /**
         * 返回数据
         */
        @ApiModelProperty(value = "返回数据")
        private T data;
    
        /**
         * 创建实例
         * @return
         */
        public static R instance() {
            return new R();
        }
    
        public int getCode() {
            return code;
        }
    
        public R setCode(int code) {
            this.code = code;
            return this;
        }
    
        public Boolean getSuccess() {
            return success;
        }
    
        public R setSuccess(Boolean success) {
            this.success = success;
            return this;
        }
    
        public String getMsg() {
            return msg;
        }
    
        public R setMsg(String msg) {
            this.msg = msg;
            return this;
        }
    
        public T getData() {
            return data;
        }
        public R setData(T data) {
            this.data = data;
            return this;
        }
    
        public static R ok() {
            return R.instance().setSuccess(true);
        }
    
        public static R ok(Object data) {
            return ok().setData(data);
        }
    
        public static R ok(Object data, String msg) {
            return ok(data).setMsg(msg);
        }
    
        public static R error() {
            return R.instance().setSuccess(false);
        }
    
        public static R error(String msg) {
            return error().setMsg(msg);
        }
    
        /**
         * 无参
         */
        public R() {
        }
    
        public R(int code, String msg) {
            this.code = code;
            this.msg = msg;
        }
    
        public R(int code, T data){
            this.code = code;
            this.data = data;
        }
    
        /**
         * 有全参
         * @param code
         * @param msg
         * @param data
         * @param success
         */
        public R(int code, String msg, T data, Boolean success) {
            this.code = code;
            this.msg = msg;
            this.data = data;
            this.success = success;
        }
    
        /**
         * 有参
         * @param code
         * @param msg
         * @param data
         */
        public R(int code, String msg, T data) {
            this.code = code;
            this.msg = msg;
            this.data = data;
        }
    }
    package com.example.combat.gaodemapUtils;
    
    /** 前端返回信息
     * @Author: zhucj
     * @Date: 2019/5/21 16:19
     */
    public class SystemConstant {
    
    
        /** 传参不规范,code:400*/
        public static final Integer PARAM_INCORRECT_CODE = 400;
    
        /** 成功,code:200*/
        public static final Integer SUCCESS_CODE = 200;
    
        /** 服务内部调用失败,code:500*/
        public static final Integer SERVER_ERROR_CODE = 500;
    
        /** 登录失效,code:401*/
        public static final Integer AUTH_FAIL_CODE = 401;
    
        /** 无对应接口权限,code:402*/
        public static final Integer HAVE_NOT_PERMISSION_CODE = 402;
    
        /** 操作无记录,code:403*/
        public static final Integer NO_RECORD_OPERATION = 403;
    
    
    
    
    
    }
    package com.example.combat.gaodemapUtils.param.req;
    
    import io.swagger.annotations.ApiModel;
    import lombok.*;
    
    /**
     * @description:
     * @author: zhucj
     * @date: 2019-08-05 11:19
     */
    @Data
    @ApiModel(description = "路径规划请求视图")
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    @ToString
    public class DirectionRequestVo {
    
        /**
         * 交通工具类型 1:步行 2:公交 3:驾车
         */
        private Integer  directionType;
        /**
         * 出发点 lon,lat(经度,纬度), “,”分割,如117.500244, 40.417801
         */
        private String origin;
    
        /**
         * 目的地 lon,lat(经度,纬度), “,”分割,如117.500244, 40.417801
         */
        private String destination;
    
        /**
         * 城市/跨城规划时的起点城市,directionType = 2时必传
         */
        private String city;
    
        /**
         * 公交换乘策略 directionType = 2和3时选传 默认0 可选值:
         * 0:最快捷模式,1:最经济模式,2:最少换乘模式,3:最少步行模式,5:不乘地铁模式
         * 下方10~20的策略,会返回多条路径规划结果。(高德地图APP策略也包含在内,强烈建议从此策略之中选择)
         * 下方策略 0~9的策略,仅会返回一条路径规划结果
         */
        /**
         * 下方策略仅返回一条路径规划结果
         * 0,速度优先,不考虑当时路况,此路线不一定距离最短
         * 1,费用优先,不走收费路段,且耗时最少的路线
         * 2,距离优先,不考虑路况,仅走距离最短的路线,但是可能存在穿越小路/小区的情况
         * 3,速度优先,不走快速路,例如京通快速路(因为策略迭代,建议使用13)
         * 4,躲避拥堵,但是可能会存在绕路的情况,耗时可能较长
         * 5,多策略(同时使用速度优先、费用优先、距离优先三个策略计算路径)。
         * 其中必须说明,就算使用三个策略算路,会根据路况不固定的返回一~三条路径规划信息。
         * 6,速度优先,不走高速,但是不排除走其余收费路段
         * 7,费用优先,不走高速且避免所有收费路段
         * 8,躲避拥堵和收费,可能存在走高速的情况,并且考虑路况不走拥堵路线,但有可能存在绕路和时间较长
         * 9,躲避拥堵和收费,不走高速
         * 下方策略返回多条路径规划结果
         * 10,返回结果会躲避拥堵,路程较短,尽量缩短时间,与高德地图的默认策略也就是不进行任何勾选一致
         * 11,返回三个结果包含:时间最短;距离最短;躲避拥堵 (由于有更优秀的算法,建议用10代替)
         * 12,返回的结果考虑路况,尽量躲避拥堵而规划路径,与高德地图的“躲避拥堵”策略一致
         * 13,返回的结果不走高速,与高德地图“不走高速”策略一致
         * 14,返回的结果尽可能规划收费较低甚至免费的路径,与高德地图“避免收费”策略一致
         * 15,返回的结果考虑路况,尽量躲避拥堵而规划路径,并且不走高速,与高德地图的“躲避拥堵&不走高速”策略一致
         * 16,返回的结果尽量不走高速,并且尽量规划收费较低甚至免费的路径结果,与高德地图的“避免收费&不走高速”策略一致
         * 17,返回路径规划结果会尽量的躲避拥堵,并且规划收费较低甚至免费的路径结果,与高德地图的“躲避拥堵&避免收费”策略一致
         * 18,返回的结果尽量躲避拥堵,规划收费较低甚至免费的路径结果,并且尽量不走高速路,与高德地图的“避免拥堵&避免收费&不走高速”策略一致
         * 19,返回的结果会优先选择高速路,与高德地图的“高速优先”策略一致
         * 20,返回的结果会优先考虑高速路,并且会考虑路况躲避拥堵,与高德地图的“躲避拥堵&高速优先”策略一致
         */
        private Integer strategy;
    
    }
    package com.example.combat.gaodemapUtils.param.req;
    
    import io.swagger.annotations.ApiModel;
    import lombok.*;
    
    /**
     * @description:
     * @author:zhucj
     * @date: 2019-08-02 11:50
     */
    @Data
    @ApiModel(description = "地理名称请求视图")
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    @ToString
    public class GeocodeRequestVo {
    
        //TODO: 地理编码参数
        /**
         * 结构化地址信息
         * 如:北京市朝阳区阜通东大街6号。如果需要解析多个地址的话,
         * 请用"|"进行间隔,并且将 batch 参数设置为 true,
         * 最多支持 10 个地址进进行"|"分割形式的请求。
         */
        private String address;
    
        /**
         * 城市名称
         * 指定城市的中文(如北京)、指定城市的中文全拼(beijing)、
         * citycode(010)、adcode(110000),不支持县级市。
         */
        private String city;
    
        /**
         * 批量查询控制
         * batch 参数设置为 true 时进行批量查询操作,最多支持 10 个地址进行批量查询。
         * batch 参数设置为 false 时进行单点查询,此时即使传入多个地址也只返回第一个地址的解析查询结果。
         */
        private Boolean batch;
    
        /**
         * 返回数据格式类型
         * 可选输入内容包括:JSON,XML
         */
        private String output;
    
        /**
         * 数字签名
         */
        private String sig;
    
        /**
         * 回调函数
         */
        private String callback;
    
        //TODO:逆地理编码参数
    
        /**
         * 经纬度坐标
         * 经度在前,纬度在后,经纬度间以“,”分割,经纬度小数点后不要超过 6 位
         */
        private String location;
    
        /**
         * 搜索半径
         * radius取值范围在0~3000,默认是1000。单位:米
         */
        private String radius ;
    
        /**
         * 返回结果控制
         * extensions 参数默认取值是 base,也就是返回基本地址信息;
         * extensions 参数取值为 all 时会返回基本地址信息、附近 POI 内容、道路信息以及道路交叉口信息。
         */
        private String extensions;
    
        /**
         *道路等级
         * 以下内容需要 extensions 参数为 all 时才生效。
         * 可选值:0,1
         * 当roadlevel=0时,显示所有道路
         * 当roadlevel=1时,过滤非主干道路,仅输出主干道路数据
         */
        private String roadlevel;
    
        /**
         * 是否优化POI返回顺序
         * 以下内容需要 extensions 参数为 all 时才生效。
         * homeorcorp 参数的设置可以影响召回 POI 内容的排序策略,目前提供三个可选参数:
         * 0:不对召回的排序策略进行干扰。
         * 1:综合大数据分析将居家相关的 POI 内容优先返回,即优化返回结果中 pois 字段的poi顺序。
         * 2:综合大数据分析将公司相关的 POI 内容优先返回,即优化返回结果中 pois 字段的poi顺序。
         */
        private String homeorcorp;
    }
    package com.example.combat.gaodemapUtils.param.req;
    
    import io.swagger.annotations.ApiModel;
    import lombok.*;
    
    /**
     * @description:
     * @author: zhucj
     * @date: 2019-11-26 11:15
     */
    @Data
    @ApiModel(description = "标注视图")
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    @ToString
    public class Markers {
    
        /**
         * 可选值: small,mid,large
         */
        private String size;
    
        /**
         * 0x000000 black,
         * 0x008000 green,
         * 0x800080 purple,
         * 0xFFFF00 yellow,
         * 0x0000FF blue,
         * 0x808080 gray,
         * 0xffa500 orange,
         * 0xFF0000 red,
         * 0xFFFFFF white
         */
        private String color;
    
        /**
         * 0-9]、[A-Z]、[单个中文字] 当size为small时,图片不展现标注名。
         * 格式 A:116.31604,39.96491
         */
        private String label;
    }
    package com.example.combat.gaodemapUtils.param.req;
    
    import io.swagger.annotations.ApiModel;
    import lombok.*;
    
    /**
     * @description:
     * @author: zhucj
     * @date: 2019-11-26 11:20
     */
    @Data
    @ApiModel(description = "折线视图")
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    @ToString
    public class Paths {
    
        /**
         * 线条粗细。
         * 可选值: [2,15]
         */
        private Integer weight;
    
        /**
         * 折线颜色。 选值范围:[0x000000, 0xffffff]
         * 例如:
         * 0x000000 black,
         * 0x008000 green,
         * 0x800080 purple,
         * 0xFFFF00 yellow,
         * 0x0000FF blue,
         * 0x808080 gray,
         * 0xffa500 orange,
         * 0xFF0000 red,
         * 0xFFFFFF white
         */
        private String color;
    
        /**
         * 透明度。
         * 可选值[0,1],小数后最多2位,0表示完全透明,1表示完全不透明。
         */
        private String transparency;
    
        /**
         * 多边形的填充颜色,此值不为空时折线封闭成多边形。取值规则同color
         */
        private String fillcolor;
    
        /**
         * 填充面透明度。
         * 可选值[0,1],小数后最多2位,0表示完全透明,1表示完全不透明
         */
        private String fillTransparency;
    }
    package com.example.combat.gaodemapUtils.param.req;
    
    import io.swagger.annotations.ApiModel;
    import lombok.*;
    
    import java.util.List;
    
    /**
     * @description: 绘制静态地图请求实体
     * @author:zhucj
     * @date: 2019-11-26 10:48
     */
    @Data
    @ApiModel(description = "绘制静态地图请求视图")
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    @ToString
    public class StaticMapRequest {
    
        /**
         * 路线主键Id
         */
        private Long id;
    
        /**
         * 地图中心点 中心点坐标。
         * 规则:经度和纬度用","分隔 经纬度小数点后不得超过6位。
         */
        private String location;
    
        /**
         * 地图缩放级别:[1,17]
         */
        private Integer zoom;
    
        /**
         * 图片宽度*图片高度。最大值为1024*1024
         */
        private String size;
    
        /**
         *1:返回普通图;
         * 2:调用高清图,图片高度和宽度都增加一倍,zoom也增加一倍(当zoom为最大值时,zoom不再改变)。
         */
        private Integer scale;
    
        /**
         * 标注
         */
        private String markers;
    
        /**
         * 折线
         */
        private String paths;
    
    
        /**
         * 经纬度集合
         */
        private List<String> localhosts;
    
    }
    package com.example.combat.gaodemapUtils.param;
    
    /**
     * @description: 高德地图服务枚举
     * @author:zhucj
     * @date: 2019-08-02 11:25
     */
    public class GaodeMapConstant {
    
        /**
         * 前端返回字段不匹配异常信息
         **/
        public static final String ERR_ORIGIN_PARAM_NULL = "出发点经纬度,不为空!";
    
        public static final String ERR_CITY_PARAM_NULL = "公交路线规划,传入的城市名称不为空!";
    
    
        public static final String ERR_DESTINATION_PARAM_NULL = "目的地经纬度,不为空!";
    
        public static final String ERR_DIRECTIONTYPE_PARAM_NULL = "传入的规划类型,暂不支持目前只有1,2,3";
    
        /**
         * 地理请求地址
         */
        public static final String GEOCODE_GEO = "https://restapi.amap.com/v3/geocode/geo";
    
    
        /**
         * 逆地理请求地址
         */
        public static final String GEOCODE_REGEO = "https://restapi.amap.com/v3/geocode/regeo";
    
        /**
         * 步行规划路线请求地址
         */
        public static final String DIRECTION_WALKING =  "https://restapi.amap.com/v3/direction/walking";
    
        /**
         * 公交规划路线请求地址
         */
        public static final String DIRECTION_INTEGRATED =   "https://restapi.amap.com/v3/direction/transit/integrated";
    
        /**
         * 驾车路线规划
         */
        public static final String DIRECTION_DRIVING =   "https://restapi.amap.com/v3/direction/driving";
    
        /**
         * 货车路线规划
         */
        public static final String DIRECTION_TRUCK =  "https://restapi.amap.com/v4/direction/truck";
    
        /**
         * 距离测量
         */
        public static final String DISTANCE =  "https://restapi.amap.com/v3/distance";
    
        /**
         * 静态地图
         */
        public static final String STATUC_MAP = "https://restapi.amap.com/v3/staticmap";
    
    
    
        /**
         * 返回状态码 成功
         */
        public static final String SUCCESS = "1";
    
        /**
         * 返回状态码 失败
         */
        public static final String FAIL= "0";
    
        /**
         * 返回数据格式
         */
        public static final String JSON = "JSON";
    
        /**
         * 高德地图key秘钥
         */
        public static final String KEY = "key";
    }
    package com.example.combat.gaodemapUtils.param;
    
    import lombok.AllArgsConstructor;
    import lombok.Builder;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    /**
     * @description: 地址编码返回参数
     * @author: zhucj
     * @date: 2019-11-25 18:17
     */
    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public class Geocodes {
    
        private String formatted_address;
    
        private String country;
    
        private String province;
    
        private String city;
    
        private String citycode;
    
        private String district;
    
        private String street;
    
        private String number;
    
        private String adcode;
    
        private String location;
    
        private String level;
    }
    #高德地图配置
    gaodemap:
      key: ********
      pathImg: E://upload/
  • 相关阅读:
    luogu 5311 [Ynoi2011]D1T3 动态点分治+树状数组
    LOJ #6145. 「2017 山东三轮集训 Day7」Easy 点分树+线段树
    BZOJ 2117: [2010国家集训队]Crash的旅游计划 动态点分治+二分
    BZOJ 1095: [ZJOI2007]Hide 捉迷藏 动态点分治+堆
    BZOJ 3924: [Zjoi2015]幻想乡战略游戏 动态点分治
    luogu 3241 [HNOI2015]开店 动态点分治+二分+vector
    luogu 2993 [FJOI2014]最短路径树问题 Dijkstra+点分治
    BZOJ 3697: 采药人的路径 点分治
    启动elasticsearch报错的几种原因及解决方法
    SpringBoot与MybatisPlus3.X整合示例(十六)
  • 原文地址:https://www.cnblogs.com/varchar-pig/p/14223663.html
Copyright © 2011-2022 走看看