double latitude = co.getLatitude(); //纬度
double longitude = co.getLongitude(); //经度
String city = null;
try {
city = LocationUtils.getCity(latitude, longitude);
serviceItemDao.insertData(s,city);
} catch (IOException e) {
e.printStackTrace();
}
封装的工具类
public class LocationUtils {
public static String getCity(double lat, double lng) throws IOException {
JSONObject jsonObject = getLocationInfo(lat, lng).getJSONObject("result").getJSONObject("addressComponent");
String city = jsonObject.getString("city");
String s = jsonObject.toString();
// System.out.println(city);
return city;
}
public static JSONObject getLocationInfo(double lat, double lng) throws IOException {
String urlString = "http://api.map.baidu.com/reverse_geocoding/v3/?ak=0HRZaqhUGXeSzxMYZQF1xvdhvl8XRUby&output=json&coordtype=wgs84ll&location="+lat+","+lng;
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setRequestMethod("POST");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
String line;
String res = "";
while((line = in.readLine())!= null) {
res += line+"\n";
}
in.close();
JSONObject jsonObject = JSONObject.parseObject(res);
return jsonObject;
}
public static void main(String[] args) throws IOException {
String address = getCity(31.845716,117.14134);
System.out.println(address);
}
}
本文分享了一个内部封装好的Java工具类,能够简单易用地根据经纬度查询到对应的城市名称,实现傻瓜式操作。适用于需要地理位置信息处理的场景。
3437

被折叠的 条评论
为什么被折叠?



