我的编程空间,编程开发者的网络收藏夹
学习永远不晚

Java环境下高德地图Api的使用方式

短信预约 -IT技能 免费直播动态提醒
省份

北京

  • 北京
  • 上海
  • 天津
  • 重庆
  • 河北
  • 山东
  • 辽宁
  • 黑龙江
  • 吉林
  • 甘肃
  • 青海
  • 河南
  • 江苏
  • 湖北
  • 湖南
  • 江西
  • 浙江
  • 广东
  • 云南
  • 福建
  • 海南
  • 山西
  • 四川
  • 陕西
  • 贵州
  • 安徽
  • 广西
  • 内蒙
  • 西藏
  • 新疆
  • 宁夏
  • 兵团
手机号立即预约

请填写图片验证码后获取短信验证码

看不清楚,换张图片

免费获取短信验证码

Java环境下高德地图Api的使用方式

Java高德地图Api的使用

使用高德经纬度获取地址信息

一些准备用到的常量


    
    private static final String KEY = "密钥,可以去高德地图免费申请";
    
    private static final String OUTPUT = "JSON";
    
    private static final String GET_LNG_LAT_URL = "http://restapi.amap.com/v3/geocode/geo";
    
    private static final String GET_ADDRESS_URL = http://restapi.amap.com/v3/geocode/regeo;

HttpClientUtils


import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Lists;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NoHttpResponseException;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
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.protocol.HttpContext;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.UnknownHostException;
import java.nio.charset.CodingErrorAction;
import java.util.List;
import java.util.Map;

public class HttpClientUtils {
    
    private static final int MAX_TOTAL_CONNECTIONS = 4000;
    
    private static final int DEFAULT_MAX_PER_ROUTE = 200;
    
    private static final int REQUEST_CONNECTION_TIMEOUT = 8 * 1000;
    
    private static final int REQUEST_SOCKET_TIMEOUT = 8 * 1000;
    
    private static final int REQUEST_CONNECTION_REQUEST_TIMEOUT = 5 * 1000;
    
    private static final int VALIDATE_AFTER_IN_ACTIVITY = 2 * 1000;
    
    private static final int SOCKET_CONFIG_SO_LINGER = 60;
    
    private static final int SOCKET_CONFIG_SO_TIMEOUT = 5 * 1000;
    
    private static int RETRY_COUNT = 5;
    
    private static volatile CloseableHttpClient httpClient = null;
    
    public static String doGet(String uri) {
        String responseBody;
        HttpGet httpGet = new HttpGet(uri);
        try {
            httpGet.setConfig(getRequestConfig());
            responseBody = executeRequest(httpGet);
        } catch (IOException e) {
            throw new RuntimeException("httpclient doGet方法异常 ", e);
        } finally {
            httpGet.releaseConnection();
        }
        return responseBody;
    }
    
    public static String doGet(String uri, Map<String, String> params) {
        return doGet(getGetUrlFromParams(uri, params));
    }
    
    private static String getGetUrlFromParams(String uri, Map<String, String> params) {
        List<BasicNameValuePair> resultList = FluentIterable.from(params.entrySet()).transform(
                new Function<Map.Entry<String, String>, BasicNameValuePair>() {
                    @Override
                    public BasicNameValuePair apply(Map.Entry<String, String> innerEntry) {
                        return new BasicNameValuePair(innerEntry.getKey(), innerEntry.getValue());
                    }
                }).toList();
        String paramSectionOfUrl = URLEncodedUtils.format(resultList, Consts.UTF_8);
        StringBuffer resultUrl = new StringBuffer(uri);
        if (StringUtils.isEmpty(uri)) {
            return uri;
        } else {
            if (!StringUtils.isEmpty(paramSectionOfUrl)) {
                if (uri.endsWith("?")) {
                    resultUrl.append(paramSectionOfUrl);
                } else {
                    resultUrl.append("?").append(paramSectionOfUrl);
                }
            }
            return resultUrl.toString();
        }
    }
    
    public static String doPost(String uri, Map<String, String> params) {
        String responseBody;
        HttpPost httpPost = new HttpPost(uri);
        try {
            List<NameValuePair> nvps = Lists.newArrayList();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                nvps.add(new BasicNameValuePair(key, value));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
            httpPost.setConfig(getRequestConfig());
            responseBody = executeRequest(httpPost);
        } catch (Exception e) {
            throw new RuntimeException("httpclient doPost方法异常 ", e);
        } finally {
            httpPost.releaseConnection();
        }
        return responseBody;
    }
    
    public static String doPost(String uri, String param, ContentType contentType) {
        String responseBody;
        HttpPost httpPost = new HttpPost(uri);
        try {
            StringEntity reqEntity = new StringEntity(param, contentType);
            httpPost.setEntity(reqEntity);
            httpPost.setConfig(getRequestConfig());
            responseBody = executeRequest(httpPost);
        } catch (IOException e) {
            throw new RuntimeException("httpclient doPost方法异常 ", e);
        } finally {
            httpPost.releaseConnection();
        }
        return responseBody;
    }
    
    private static RequestConfig getRequestConfig() {
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                //.setCookieSpec(CookieSpecs.DEFAULT)
                .setExpectContinueEnabled(true)
                //.setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
                //.setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
                .build();
        return RequestConfig.copy(defaultRequestConfig)
                .setSocketTimeout(REQUEST_CONNECTION_TIMEOUT)
                .setConnectTimeout(REQUEST_SOCKET_TIMEOUT)
                .setConnectionRequestTimeout(REQUEST_CONNECTION_REQUEST_TIMEOUT)
                .build();
    }
    
    private static String executeRequest(HttpUriRequest method) throws IOException {
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
            @Override
            public String handleResponse(final HttpResponse response) throws IOException {
                int status = response.getStatusLine().getStatusCode();
                String result;
                if (status >= HttpStatus.SC_OK && status < HttpStatus.SC_MULTIPLE_CHOICES) {
                    HttpEntity entity = response.getEntity();
                    result = entity != null ? EntityUtils.toString(entity) : null;
                    EntityUtils.consume(entity);
                    return result;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }
        };
        String result = getHttpClientInstance().execute(method, responseHandler);
        return result;
    }
    
    private static CloseableHttpClient getHttpClientInstance() {
        if (httpClient == null) {
            synchronized (CloseableHttpClient.class) {
                if (httpClient == null) {
                    httpClient = HttpClients.custom().setConnectionManager(initConfig()).setRetryHandler(getRetryHandler()).build();
                }
            }
        }
        return httpClient;
    }
    
    private static HttpRequestRetryHandler getRetryHandler() {
        // 请求重试处理
        return new HttpRequestRetryHandler() {
            @Override
            public boolean retryRequest(IOException exception,
                                        int executionCount, HttpContext context) {
                if (executionCount >= RETRY_COUNT) {
                    // 假设已经重试了5次,就放弃
                    return false;
                }
                if (exception instanceof NoHttpResponseException) {
                    // 假设server丢掉了连接。那么就重试
                    return true;
                }
                if (exception instanceof SSLHandshakeException) {
                    // 不要重试SSL握手异常
                    return false;
                }
                if (exception instanceof InterruptedIOException) {
                    // 超时
                    return false;
                }
                if (exception instanceof UnknownHostException) {
                    // 目标server不可达
                    return false;
                }
                if (exception instanceof ConnectTimeoutException) {
                    // 连接被拒绝
                    return false;
                }
                if (exception instanceof SSLException) {
                    // SSL握手异常
                    return false;
                }
                HttpRequest request = HttpClientContext.adapt(context).getRequest();
                // 假设请求是幂等的,就再次尝试
                return !(request instanceof HttpEntityEnclosingRequest);
            }
        };
    }
    
    private static PoolingHttpClientConnectionManager initConfig() {
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", new SSLConnectionSocketFactory(SSLContexts.createSystemDefault()))
                .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        
        SocketConfig socketConfig = SocketConfig.custom()
                .setTcpNoDelay(true)
                .setSoReuseAddress(true)
                .setSoTimeout(SOCKET_CONFIG_SO_TIMEOUT)
                //.setSoLinger(SOCKET_CONFIG_SO_LINGER)
                //.setSoKeepAlive(true)
                .build();
        connManager.setDefaultSocketConfig(socketConfig);
        connManager.setValidateAfterInactivity(VALIDATE_AFTER_IN_ACTIVITY);
        ConnectionConfig connectionConfig = ConnectionConfig.custom()
                .setMalformedInputAction(CodingErrorAction.IGNORE)
                .setUnmappableInputAction(CodingErrorAction.IGNORE)
                .setCharset(Consts.UTF_8)
                .build();
        connManager.setDefaultConnectionConfig(connectionConfig);
        connManager.setDefaultMaxPerRoute(DEFAULT_MAX_PER_ROUTE);
        connManager.setMaxTotal(MAX_TOTAL_CONNECTIONS);
        return connManager;
    }
}

GaoDeMapUtils


import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class GaoDeMapUtils {
    
    private static final String KEY = "密钥,可以去高德地图免费申请";
    
    private static final String OUTPUT = "JSON";
    
    private static final String GET_LNG_LAT_URL = "http://restapi.amap.com/v3/geocode/geo";
    
    private static final String GET_ADDRESS_URL = "http://restapi.amap.com/v3/geocode/regeo";
    
    public static String getAddressByLonLat(double gdLon, double gdLat) {
        String location = gdLon + "," + gdLat;
        Map<String, String> params = new HashMap<>();
        params.put("location", location);
        // Map<String, String> result = new HashMap<>();
        try {
            // 拼装url
            String url = jointUrl(params, OUTPUT, KEY, GET_ADDRESS_URL);
            // 调用高德SDK
            return HttpClientUtils.doPost(url, params);
            // 解析Json字符串,获取城市名称
            // JSONObject jsonObject = JSON.parseObject(jsonResult);
            // String regeocode = jsonObject.getString("regeocode");
            // JSONObject regeocodeObj = JSON.parseObject(regeocode);
            // String address = regeocodeObj.getString("formatted_address");
            // 组装结果
            // result.put(location, address);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static String getLonLarByAddress(String address) {
        Map<String, String> params = new HashMap<>();
        params.put("address", address);
        // Map<String, String> result = new HashMap<>();
        try {
            // 拼装url
            String url = jointUrl(params, OUTPUT, KEY, GET_LNG_LAT_URL);
            // 调用高德地图SDK
            return HttpClientUtils.doPost(url, params);
            // 解析JSON字符串,取到高德经纬度
            // JSONObject jsonObject = JSON.parseObject(jsonResult);
            // JSONArray geocodes = jsonObject.getJSONArray("geocodes");
            // String geocode = JSON.toJSONString(geocodes.get(0));
            // JSONObject geocodeObj = JSON.parseObject(geocode);
            // String lonAndLat = geocodeObj.getString("location");
            // 组装结果
            // result.put(address, lonAndLat);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    private static String jointUrl(Map<String, String> params, String output, String key, String url) throws IOException {
        StringBuilder baseUrl = new StringBuilder();
        baseUrl.append(url);
        int index = 0;
        Set<Map.Entry<String, String>> entrys = params.entrySet();
        for (Map.Entry<String, String> param : entrys) {
            // 判断是否是第一个参数
            if (index == 0) {
                baseUrl.append("?");
            } else {
                baseUrl.append("&");
            }
            baseUrl.append(param.getKey()).append("=").append(URLEncoder.encode(param.getValue(), "utf-8"));
            index++;
        }
        baseUrl.append("&output=").append(output).append("&key=").append(key);
        return baseUrl.toString();
    }
}

返回结果

// 这是根据高德经纬度获取的返回报文
{"status":"1","info":"OK","infocode":"10000","regeocode":{"formatted_address":"北京市东城区东华门街道天安门","addressComponent":{"country":"中国","province":"北京市","city":[],"citycode":"010","district":"东城区","adcode":"110101","township":"东华门街道","towncode":"110101001000","neighborhood":{"name":[],"type":[]},"building":{"name":"天安门","type":"风景名胜;风景名胜相关;旅游景点"},"streetNumber":{"street":"广场东侧路","number":"44号","location":"116.39795,39.9097239","direction":"北","distance":"113.709"},"businessAreas":[{"location":"116.3998109423077,39.90717459615385","name":"天安门","id":"110101"},{"location":"116.39981058278138,39.92383706953642","name":"景山","id":"110101"},{"location":"116.4118112683418,39.91461494422115","name":"王府井","id":"110101"}]}}}
// 这是根据地址名称获取的返回报文
{"status":"1","info":"OK","infocode":"10000","count":"1","geocodes":[{"formatted_address":"北京市东城区天安门","province":"北京市","citycode":"010","city":"北京市","district":"东城区","township":[],"neighborhood":{"name":[],"type":[]},"building":{"name":[],"type":[]},"adcode":"110101","street":[],"number":[],"location":"116.397573,39.908743","level":"兴趣点"}]}

Java调用高德Api获取经纬度

1.第一步使用高德api需要先注册高德账号申请Key

高德开放平台:https://lbs.amap.com/

2.第二步详细阅读高德api开发指南

在这里插入图片描述

指南地址:https://lbs.amap.com/api/webservice/guide/api/georegeo/#geo

3.编写业务代码

在这里插入图片描述

首先这里需要判断成功把值返回失败默认赋值

其次笔者是使用的map形式返回值大家也可以尝试其他方法返回得到的值

对于最终得到的值因为是六位小数这里是用的双精度型存储然后转换为数据库存储值的类型按自己数据库的类型为准

4.编写用作调用经纬度的类

在这里插入图片描述

将调用得到的json格式的数据进行处理得到所需要的经纬度的值封装入定义好的map参数中

好了,以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

Java环境下高德地图Api的使用方式

下载Word文档到电脑,方便收藏和打印~

下载Word文档

编程热搜

  • Python 学习之路 - Python
    一、安装Python34Windows在Python官网(https://www.python.org/downloads/)下载安装包并安装。Python的默认安装路径是:C:\Python34配置环境变量:【右键计算机】--》【属性】-
    Python 学习之路 - Python
  • chatgpt的中文全称是什么
    chatgpt的中文全称是生成型预训练变换模型。ChatGPT是什么ChatGPT是美国人工智能研究实验室OpenAI开发的一种全新聊天机器人模型,它能够通过学习和理解人类的语言来进行对话,还能根据聊天的上下文进行互动,并协助人类完成一系列
    chatgpt的中文全称是什么
  • C/C++中extern函数使用详解
  • C/C++可变参数的使用
    可变参数的使用方法远远不止以下几种,不过在C,C++中使用可变参数时要小心,在使用printf()等函数时传入的参数个数一定不能比前面的格式化字符串中的’%’符号个数少,否则会产生访问越界,运气不好的话还会导致程序崩溃
    C/C++可变参数的使用
  • css样式文件该放在哪里
  • php中数组下标必须是连续的吗
  • Python 3 教程
    Python 3 教程 Python 的 3.0 版本,常被称为 Python 3000,或简称 Py3k。相对于 Python 的早期版本,这是一个较大的升级。为了不带入过多的累赘,Python 3.0 在设计的时候没有考虑向下兼容。 Python
    Python 3 教程
  • Python pip包管理
    一、前言    在Python中, 安装第三方模块是通过 setuptools 这个工具完成的。 Python有两个封装了 setuptools的包管理工具: easy_install  和  pip , 目前官方推荐使用 pip。    
    Python pip包管理
  • ubuntu如何重新编译内核
  • 改善Java代码之慎用java动态编译

目录