com.github.xiaoyuge5201.other.GetLatAndLngByBaidu Maven / Gradle / Ivy
package com.github.xiaoyuge5201.other;
import com.alibaba.fastjson.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;
import java.text.DecimalFormat;
/**
* 获取经纬度通过
* @author xiaoyuge
*/
public class GetLatAndLngByBaidu {
/**
* 根据地址查询经纬度信息
* @param addr 详细地址
* @param mapUrl 百度查询经纬度的地址:http://api.map.baidu.com/geocoding/v3/?ak=uuRmFWjDFGWE9gZrb9OIbmui0MREiRad&output=json&address=%s
* @return 经纬度数组
* @throws IOException
*/
public static String[] getCoordinate(String mapUrl, String addr) {
String address = "";
try {
address = java.net.URLEncoder.encode(addr,"UTF-8");
String url = String.format(mapUrl,address);
String json = loadJSON(url);
if (json != null && !"".equals(json)) {
JSONObject obj = JSONObject.parseObject(json);
if ("0".equals(obj.getString("status"))) {
// 经度
double lng = obj.getJSONObject("result").getJSONObject("location").getDouble("lng");
// 纬度
double lat = obj.getJSONObject("result").getJSONObject("location").getDouble("lat");
DecimalFormat df = new DecimalFormat("#.######");
return new String[]{df.format(lng),df.format(lat)};
}
}
} catch (Exception e1) {
e1.printStackTrace();
}
return null;
}
private static String loadJSON(String url) {
StringBuilder json = new StringBuilder();
try {
URL oracle = new URL(url);
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "UTF-8"));
String inputLine = null;
while ((inputLine = in.readLine()) != null) {
json.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
return json.toString();
}
}