ackage com.miot.base.map;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
/**
* @author lqq
* @date 2017年11月23日 上午8:20:06
* 根据地名获取经纬度
*/
public class MapBaiDu {
public static void main(String[] args) {
MapBaiDu getLatAndLngByBaidu = new MapBaiDu();
Map<String,Double> map=getLatAndLngByBaidu.getLngAndLat("。。。。。。。");
System.out.println("经度:"+map.get("lng")+"---纬度:"+map.get("lat"));
// 经度:120.19237042945677---纬度:30.187587607727092
}
public static Map<String,Double> getLngAndLat(String address){
Map<String,Double> map=new HashMap<String, Double>();
String url = "。。。。。。。。。。。。。自己申请。。。。。。。。。。。。。。";
String json = loadJSON(url);
JSONObject obj = JSONObject.fromObject(json);
if(obj.get("status").toString().equals("0")){
double lng=obj.getJSONObject("result").getJSONObject("location").getDouble("lng");
double lat=obj.getJSONObject("result").getJSONObject("location").getDouble("lat");
map.put("lng", lng);
map.put("lat", lat);
}else{
//System.out.println("未找到相匹配的经纬度!");
}
return map;
}
/***
* 处理url并获取jsons数据
* @param url
* @return
*/
private static String loadJSON(String url) {
StringBuffer sb = new StringBuffer();
InputStream ips = getInputStream(url);
InputStreamReader isreader = null;
try {
isreader = new InputStreamReader(ips, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(isreader);
String temp = null;
try {
while ((temp = bufferedReader.readLine()) != null) {
sb.append(temp);
}
bufferedReader.close();
isreader.close();
ips.close();
ips = null;
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
/**
* 从请求的URL中获取返回的流数据
* @param requestUrl
* @return InputStream
*/
private static InputStream getInputStream(String requestUrl) {
URL url = null;
HttpURLConnection conn = null;
InputStream in = null;
try {
url = new URL(requestUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.connect();
in = conn.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
return in;
}
}
根据地名获取经纬度
最新推荐文章于 2024-03-13 11:03:58 发布