1 高德开放平台注册账号
登录高德开放平台:首页 | 高德控制台
注册成功后,创建应用和key
2 服务调用
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringEscapeUtils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
/**
* @program:
* @description: 高德查询经纬度
* @author:
* @create:
**/
public class AddressLocationUtil {
/**
* Key
*/
private static String KEY="你的key";
public static String GD_URL="https://restapi.amap.com/v3/geocode/geo?address=%s&key=%s";
/**
* 成功标识
*/
private static String SUCCESS_FLAG="1";
/**
* 根据地址获取对应的经纬度信息
* @param address
* @return
*/
public static String getLonAndLatByAddress(String address){
System.out.println(address);
GD_URL = String.format(GD_URL, address, KEY);
//高德接口返回的是JSON格式的字符串
String queryResult = getResponse(GD_URL);
JSONObject obj = JSONObject.parseObject(queryResult);
System.out.println(obj.toString());
if(String.valueOf(obj.get("status")).equals(SUCCESS_FLAG)){
String escapedJsonStr = StringEscapeUtils.unescapeJava(obj.get("geocodes").toString());
JSONArray jsonArray = JSONArray.parseArray(escapedJsonStr);
for (Object o : jsonArray) {
JSONObject jsonObject = JSONObject.parseObject(o.toString());
return jsonObject.get("location").toString();
}
}
return "";
}
/**
* 发送请求
*
* @param serverUrl 请求地址
*/
private static String getResponse(String serverUrl) {
// 用JAVA发起http请求,并返回json格式的结果
StringBuffer result = new StringBuffer();
try {
URL url = new URL(serverUrl);
URLConnection conn = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return result.toString();
}
public static void main(String[] args) {
String location = getLonAndLatByAddress("河南省郑州市管城回族区*****");
System.out.println(location);
}
}
测试下吧
返回的经纬度格式是逗号分隔的字符串