上代码
package com.hw8.coingame.util;
import net.sf.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
* 创建人:柳月廷
* 作用域:根据经纬度获取城市名
* @version 1.0
* @return:
* @since 2019/7/31 10:36
*/
public class MapUtil {
/**
* 高德地图的key
* 申请高德地图key
*/
private static final String key = "自己申请的key";
public static String getCoordinate(String lng, String lat) throws IOException {
StringBuilder resultData = new StringBuilder();
StringBuilder https = new StringBuilder("http://restapi.amap.com/v3/geocode/regeo?key=");
//经纬度地址
StringBuilder localhost = new StringBuilder("&location="+lng+","+lat);
StringBuilder httpsTail = new StringBuilder("&poitype=&radius=&extensions=base&batch=true");
String url = https.append(key).append(localhost).append(httpsTail).toString();
//拼接出来的地址
//System.out.println(https1.append(key).append(localhost1).append(httpsTail).toString());
// String url ="http://restapi.amap.com/v3/geocode/regeo?key=自己申请的key&location=116.310003,39.991957&poitype=&radius=&extensions=base&batch=true&roadlevel=";
URL myURL = null;
URLConnection httpsConn = null;
try {
myURL = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
InputStreamReader insr = null;
BufferedReader br = null;
try {
httpsConn = myURL.openConnection();// 不使用代理
if (httpsConn != null) {
insr = new InputStreamReader(httpsConn.getInputStream(), "UTF-8");
br = new BufferedReader(insr);
String data = null;
while ((data = br.readLine()) != null) {
resultData.append(data);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (insr != null) {
insr.close();
}
if (br != null) {
br.close();
}
}
if (resultData.toString().indexOf("regeocodes") == 0) {
return null;
}
String str = JSONObject.fromObject(resultData.toString()).getString("regeocodes");
//城市切割
String[] strr = str.split("\",\"city\":\"");
if (strr.length < 2 && strr.length == 1) {
//直辖市
String[] sr = str.split("\"province\":\"");
String[] srr = sr[1].split("\",\"city");
return srr[0];
}
//非直辖市
String[] strrr = strr[1].split("\",\"citycode\":");
return strrr[0];
}
public static void main(String[] args) {
try {
//测试使用
System.out.println(getCoordinate("107.6493856959542", "35.71521598356201"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
返回的json·
{"status":"1","info":"OK","infocode":"10000","regeocodes":[{"formatted_address":"甘肃省庆阳市西峰区南街街道金江名都B区金江名都","addressComponent":{"country":"中国","province":"甘肃省","city":"庆阳市","citycode":"0934","district":"西峰区","adcode":"621002","township":"南街街道","towncode":"621002002000","neighborhood":{"name":[],"type":[]},"building":{"name":[],"type":[]},"streetNumber":{"street":"顺化东路","number":"5号","location":"107.648919,35.71419","direction":"西南","distance":"121.643"},"businessAreas":[{"location":"107.642376,35.730344","name":"庆阳","id":"621002"}]}}]}