Java如何在项目中调用高德地图API

登录高德开放平台http://lbs.amap.com/,点击登录,成为开发者,这个过程需要绑定邮箱。

成功后点击控制台。点击应用管理。并创建新应用。应用名称都可以自己看着填。

成功后就可以添加key了,当然,也要有名称等信息。

------------------到这里完成了第一步,你可以通过高德给你的key来调用地图API了。

接下来,如何调用呢?

在高德官网的开发文档中有详细的教程,但是我献上我项目的调用经验代码给新手:

1:创建一个工具类MapUtil,导入一些需要的包:

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

2:定义你在高德官网获取的key

private static String key = "xxxxxxxxxxxxxxxxxxxxxxxxx";

3:接下来,是主角了,api如下:

/**
 * 阿里云api 根据经纬度获取地址
 *
 * @param log
 * @param lat
 * @return
 */
public static String getAdd(String log, String lat) {
    StringBuffer s = new StringBuffer();
    s.append("key=").append(key).append("&location=").append(log).append(",").append(lat);
    String res = sendPost("http://restapi.amap.com/v3/geocode/regeo", s.toString());
    logger.info(res);
    JSONObject jsonObject = JSONObject.fromObject(res);
    JSONObject jsonObject1 = JSONObject.fromObject(jsonObject.get("regeocode"));
    String add = jsonObject1.get("formatted_address").toString();
    return add;
}
 
/**
 * 阿里云api 根据经纬度获取所在城市
 *
 * @param log
 * @param lat
 * @return
 */
public static String getCity(String log, String lat) {
    // log 大 lat 小
    // 参数解释: 纬度,经度 type 001 (100代表道路,010代表POI,001代表门址,111可以同时显示前三项)
    String urlString = "http://gc.ditu.aliyun.com/regeocoding?l=" + lat + "," + log + "&type=010";
    String res = "";
    try {
        URL url = new URL(urlString);
        java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream
                (), "UTF-8"));
        String line;
        while ((line = in.readLine()) != null) {
            res += line + "\n";
        }
        in.close();
        JSONObject jsonObject = JSONObject.fromObject(res);
        JSONArray jsonArray = JSONArray.fromObject(jsonObject.getString("addrList"));
        JSONObject j_2 = JSONObject.fromObject(jsonArray.get(0));
        String allAdd = j_2.getString("admName");
        String arr[] = allAdd.split(",");
        res = arr[1];
    } catch (Exception e) {
        logger.info("error in wapaction,and e is " + e.getMessage());
    }
    logger.info(res);
    return res;
}
 
/**
 * 高德api 根据地址获取经纬度
 *
 * @param name
 * @return
 */
public static String getLatAndLogByName(String name) {
    StringBuffer s = new StringBuffer();
    s.append("key=" + key + "&address=" + name);
    String res = sendPost("http://restapi.amap.com/v3/geocode/geo", s.toString());
    logger.info(res);
    JSONObject jsonObject = JSONObject.fromObject(res);
    JSONArray jsonArray = JSONArray.fromObject(jsonObject.getString("geocodes"));
    JSONObject location = (JSONObject) jsonArray.get(0);
    String add = location.get("location").toString();
    return add;
}
 
/**
 * 高德api 根据地址获取经纬度
 *
 * @param name
 * @return
 */
public static String getAddByAMAP(String log, String lat) {
    StringBuffer s = new StringBuffer();
    s.append("key=").append(key).append("&location=").append(log).append(",").append(lat);
    String res = sendPost("http://restapi.amap.com/v3/geocode/regeo", s.toString());
    logger.info(res);
    JSONObject jsonObject = JSONObject.fromObject(res);
    JSONObject jsonObject1 = JSONObject.fromObject(jsonObject.get("regeocode"));
    String add = jsonObject1.get("formatted_address").toString();
    return add;
}
 
 
/**
 * 高德api 坐标转换---转换至高德经纬度
 *
 * @param name
 * @return
 */
public static String convertLocations(String log, String lat, String type) {
    StringBuffer s = new StringBuffer();
    s.append("key=").append(key).append("&locations=").append(log).append(",").append(lat).append("&coordsys=");
    if (type == null) {
        s.append("gps");
    } else {
        s.append(type);
    }
    String res = sendPost("http://restapi.amap.com/v3/assistant/coordinate/convert", s.toString());
    logger.info(res);
    JSONObject jsonObject = JSONObject.fromObject(res);
    String add = jsonObject.get("locations").toString();
    return add;
}
 
 
public static String getAddByName(String name) {
    // log 大 lat 小
    // 参数解释: 纬度,经度 type 001 (100代表道路,010代表POI,001代表门址,111可以同时显示前三项)
    String urlString = "http://gc.ditu.aliyun.com/geocoding?a=" + name;
    String res = "";
    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        String line;
        while ((line = in.readLine()) != null) {
            res += line + "\n";
        }
        in.close();
        JSONObject jsonObject = JSONObject.fromObject(res);
        String lon = jsonObject.getString("lon");
        String lat = jsonObject.getString("lat");
        System.err.println(jsonObject);
        res = getNearbyAdd(lon, lat);
    } catch (Exception e) {
        logger.info("error in wapaction,and e is " + e.getMessage());
        e.printStackTrace();
    }
    return res;
}
 
public static String getNearbyAdd(String log, String lat) {
 
    String add = sendGet("http://ditu.amap.com/service/regeo", "longitude=" + log + "&latitude=" + lat +
            "&type=010");
 
    logger.info(add);
 
    return add;
}
 
/**
 * 高德api 关键字模糊查询
 *
 * @param keyWord
 * @param city
 * @return
 */
public static String getKeywordsAddByLbs(String keyWord, String city) {
    StringBuffer s = new StringBuffer();
    s.append("key=" + key + "&keywords=");
    if (keyWord.contains(" ")) {
        String[] str = keyWord.split(" ");
        for (int i = 0; i < str.length; i++) {
            if (i == 0) {
                s.append(str[i]);
            } else {
                s.append("+" + str[i]);
            }
        }
    } else {
        s.append(keyWord);
    }
    s.append("&city=" + city);
    s.append("offset=10&page=1");
    String around = sendPost("http://restapi.amap.com/v3/place/text", s.toString());
    logger.info(around);
    return around;
}
/**
 * 高德api 经纬度/关键字 附近地标建筑及地点查询
 *
 * @param log
 * @param lat
 * @param keyWord
 * @return
 */
public static String getAroundAddByLbs(String log, String lat, String keyWord) {
    String around = sendPost("http://restapi.amap.com/v3/place/around",
            "key=" + key + "&location=" + log + "," + lat + "&keywords=" + keyWord +
                    "&radius=2000&offset=10&page=1");
    logger.info(around);
    return around;
}

4:到了这里,你还需要一些调用所需的工具方法,我页直接帮你整合在下面:

public static String sendGet(String url, String param) {
    String result = "";
    BufferedReader in = null;
    try {
        String urlNameString = url + "?" + param;
        URL realUrl = new URL(urlNameString);
        // 打开和URL之间的连接
        URLConnection connection = realUrl.openConnection();
        // 设置通用的请求属性
        connection.setRequestProperty("accept", "*/*");
        connection.setRequestProperty("connection", "Keep-Alive");
        connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        // 建立实际的连接
        connection.connect();
        // 获取所有响应头字段
        Map<String, List<String>> map = connection.getHeaderFields();
        // 遍历所有的响应头字段
        for (String key : map.keySet()) {
            logger.info(key + "--->" + map.get(key));
        }
        // 定义 BufferedReader输入流来读取URL的响应
        in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        logger.info("发送GET请求出现异常!" + e);
        e.printStackTrace();
    }
    // 使用finally块来关闭输入流
    finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }
    return result;
}
 
/**
 * 向指定 URL 发送POST方法的请求
 *
 * @param url   发送请求的 URL
 * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
 * @return 所代表远程资源的响应结果
 */
public static String sendPost(String url, String param) {
    PrintWriter out = null;
    BufferedReader in = null;
    String result = "";
    try {
        URL realUrl = new URL(url);
        // 打开和URL之间的连接
        URLConnection conn = realUrl.openConnection();
        // 设置通用的请求属性
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        // 发送POST请求必须设置如下两行
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // 获取URLConnection对象对应的输出流
        out = new PrintWriter(conn.getOutputStream());
        // 发送请求参数
        out.print(param);
        // flush输出流的缓冲
        out.flush();
        // 定义BufferedReader输入流来读取URL的响应
        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        logger.info("发送 POST 请求出现异常!" + e);
        e.printStackTrace();
    }
    // 使用finally块来关闭输出流、输入流
    finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return result;
}
 
/**
 * GET请求数据
 *
 * @param get_url url地址
 * @param content key=value形式
 * @return 返回结果
 * @throws Exception
 */
public static String sendGetData(String get_url, String content) throws Exception {
    String result = "";
    URL getUrl = null;
    BufferedReader reader = null;
    String lines = "";
    HttpURLConnection connection = null;
    try {
        if (content != null && !content.equals(""))
            get_url = get_url + "?" + content;
        // get_url = get_url + "?" + URLEncoder.encode(content, "utf-8");
        getUrl = new URL(get_url);
        connection = (HttpURLConnection) getUrl.openConnection();
        connection.connect();
        // 取得输入流,并使用Reader读取
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));// 设置编码
        while ((lines = reader.readLine()) != null) {
            result = result + lines;
        }
        return result;
    } catch (Exception e) {
        throw e;
    } finally {
        if (reader != null) {
            reader.close();
            reader = null;
        }
        connection.disconnect();
    }
}
 
/**
 * @param POST_URL url地址
 * @param content  key=value形式
 * @return 返回结果
 * @throws Exception
 */
public static String sendPostData(String POST_URL, String content) throws Exception {
    HttpURLConnection connection = null;
    DataOutputStream out = null;
    BufferedReader reader = null;
    String line = "";
    String result = "";
    try {
        URL postUrl = new URL(POST_URL);
        connection = (HttpURLConnection) postUrl.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        // Post 请求不能使用缓存
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.connect();
 
        out = new DataOutputStream(connection.getOutputStream());
        // content = URLEncoder.encode(content, "utf-8");
        // DataOutputStream.writeBytes将字符串中的16位的unicode字符�?8位的字符形式写道流里�?
        out.writeBytes(content);
        out.flush();
        out.close();
        // 获取结果
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));// 设置编码
        while ((line = reader.readLine()) != null) {
            result = result + line;
        }
        return result;
    } catch (Exception e) {
        throw e;
    } finally {
        if (out != null) {
            out.close();
            out = null;
        }
        if (reader != null) {
            reader.close();
            reader = null;
        }
        connection.disconnect();
    }
}
 
/*
 * 过滤掉html里不安全的标签,不允许用户输入这些标�?
 */
public static String htmlFilter(String inputString) {
    // return inputString;
    String htmlStr = inputString; // 含html标签的字符串
    String textStr = "";
    java.util.regex.Pattern p_script;
    java.util.regex.Matcher m_script;
 
    try {
        String regEx_script = "<[\\s]*?(script|style)[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?(script|style)[\\s]*?>";
        String regEx_onevent = "on[^\\s]+=\\s*";
        String regEx_hrefjs = "href=javascript:";
        String regEx_iframe = "<[\\s]*?(iframe|frameset)[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?(iframe|frameset)" +
                "[\\s]*?>";
        String regEx_link = "<[\\s]*?link[^>]*?/>";
 
        htmlStr = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
        htmlStr = Pattern.compile(regEx_onevent, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
        htmlStr = Pattern.compile(regEx_hrefjs, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
        htmlStr = Pattern.compile(regEx_iframe, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
        htmlStr = Pattern.compile(regEx_link, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
 
        textStr = htmlStr;
 
    } catch (Exception e) {
        System.err.println("Html2Text: " + e.getMessage());
    }
 
    return textStr;
}

 

要在Java调用高德地图API,你可以按照以下步骤进行操作: 1. 创建一个工具类MapUtil,并导入所需的包,例如net.sf.json、org.apache.commons.collections等。 2. 在工具类中定义你在高德官网获取的key,例如private static String key = "xxxxxxxxxxxxxxxxxxxxxxxxx"; 3. 在工具类中编写方法来调用高德地图API。你可以使用Java的URL和HttpURLConnection类来发送HTTP请求,并通过API的URL和参数生成请求URL。 4. 发送HTTP请求并获取响应。可以使用URLConnection的getInputStream()方法来获取API的响应数据。 5. 解析API的响应数据。根据API文档中的返回数据格式,你可以使用JSON库解析响应数据,例如使用JSONObject和JSONArray类来解析JSON格式的数据。 6. 处理解析后的数据。你可以根据需要提取所需的信息,例如获取地理坐标、距离、路线等。 下面是一个示例代码来调用高德地图API: ```java import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.commons.collections.MapUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; import java.util.regex.Pattern; public class MapUtil { private static final Logger LOGGER = LoggerFactory.getLogger(MapUtil.class); private static String key = "xxxxxxxxxxxxxxxxxxxxxxxxx"; public static String getResponse(String urlString) throws IOException { StringBuilder result = new StringBuilder(); URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) { result.append(line); } reader.close(); connection.disconnect(); return result.toString(); } public static JSONObject getJson(String urlString) throws IOException { String response = getResponse(urlString); return JSONObject.fromObject(response); } public static void main(String[] args) { try { String apiUrl = "https://restapi.amap.com/v3/place/text?keywords=北京&key=" + key; JSONObject result = getJson(apiUrl); // 解析结果 JSONArray pois = result.getJSONArray("pois"); for (int i = 0; i < pois.size(); i++) { JSONObject poi = pois.getJSONObject(i); String name = poi.getString("name"); String location = poi.getString("location"); System.out.println(name + ": " + location); } } catch (IOException e) { LOGGER.error("Failed to call AMap API: " + e.getMessage()); } } } ``` 请注意,这只是一个示例代码,你可以根据具体需求进行修改和扩展。你可以根据高德地图API文档提供的接口和参数来调用不同的功能和服务。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [SpringCloud之如何在项目调用高德地图API](https://blog.csdn.net/qq_31122833/article/details/80653419)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值