package cn.com.xinchantou.light.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class AddressLngLatExchanger {
/**
* 高德地图通过地址获取经纬度
*/
public static Map<String,Double> addressToLngAndLag(String address) {
Map<String,Double> map=new HashMap<String, Double>();
String geturl = "http://restapi.amap.com/v3/geocode/geo?key=xxxxxxxxxxxxx&address="+address;
String location = "";
try {
URL url = new URL(geturl); // 把字符串转换为URL请求地址
HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
connection.connect();// 连接会话
// 获取输入流
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {// 循环读取流
sb.append(line);
}
br.close();// 关闭流
connection.disconnect();// 断开连接
JSONObject a = JSON.parseObject(sb.toString());
JSONArray sddressArr = JSON.parseArray(a.get("geocodes").toString());
if(sddressArr.size() == 0) return null;
JSONObject c = JSON.parseObject(sddressArr.get(0).toString());
location = c.get("location").toString();
} catch (Exception e) {
e.printStackTrace();
System.out.println("失败!");
}
return stringToMap(location);
}
//逗号截取经度 纬度
public static Map<String,Double> stringToMap(String LngLat){
Map<String,Double> map=new HashMap<String, Double>();
String[] strArr = LngLat.split("\\,");
map.put("lng", Double.parseDouble(strArr[0]));
map.put("lat", Double.parseDouble(strArr[1]));
return map;
}
测试1
/* public static void main(String[] args) {
String address="东方明珠";
Map<String, Double> map = addressToLngAndLag(address);
for(Map.Entry<String, Double> entry : map.entrySet()){
String mapKey = entry.getKey();
Double mapValue = entry.getValue();
System.out.println(mapKey+":"+mapValue);
} }
*/
}
测试2
public static List<Map<String, Double>> LngLat(String address){ List<Map<String, Double>> list=new ArrayList<Map<String, Double>>(); Map<String, Double> map =addressToLngAndLag(address); for(Map.Entry<String, Double> entry : map.entrySet()){ String mapKey = entry.getKey(); Double mapValue = entry.getValue(); map.put(mapKey,mapValue); list.add(map); } return list; }
public static void main(String[] args) {
List<Map<String, Double>> lngLatList=LngLat(address); Double lng= lngLatList.get(0).get("lng"); Double lat= lngLatList.get(1).get("lat"); System.out.println(lng+""+lat);
}
key:高德开放平台注册申请