package com.lbnet.lzx.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.MessageFormat;
public class GetLatLng {
String ret = "";
public static void main(String[] args) {
GetLatLng t = new GetLatLng();
System.out.println(t.getLatlng("上海市虹橋路333號慧谷科技園606"));
System.out.println("經度:"+t.getlng());
System.out.println("緯度:"+t.getlat());
}
/**
* 利用googlemap api 通過 HTTP 進行位址解析
* @param address 位址
* @return HTTP狀態碼,精確度(請參見精確度常數),緯度,經度
*/
public String getLatlng(String address){
if(address != null && !address.equals("")){
try {
address = URLEncoder.encode(address,"UTF-8");//進行這一步是為了避免亂碼
} catch (UnsupportedEncodingException e1) {
}
//q 是查詢的目標位址,output 是回應格式,key 是要使用此 Web 服務的關鍵字字串
//在此回應內,200 是 HTTP 狀態碼,表明解析成功;4 是精度常量;41.879535 是經度;-87.624333 是緯度。
//String dituUrl = "HTTP://ditu.google.cn/maps/geo?q=gz&key=ABQIAAAAE7SAS10g-ATpf14mvmoY3RQnYy5xmakd5i22O2aWTK8_BJDSThTClyozg_yWXE5JwJ2I5FHxvu1BFw&sensor=true&output=json";
String[] arr = new String[4];
arr[0] = address;
arr[1] = "csv";
arr[2] = "true";
arr[3]="ABQIAAAAE7SAS10g-ATpf14mvmoY3RQnYy5xmakd5i22O2aWTK8_BJDSThTClyozg_yWXE5JwJ2I5FHxvu1BFw";
// arr[3] = "ABQIAAAAzr2EBOXUKnm_jVnk0OJI7xSosDVG8KKPE1-m51RBrvYughuyMxQ-i1QfUnH94QxWIa6N4U6MouMmBA";
//HTTP://maps.google.com/maps/geo?q=Chicago&output=cvs&key=ABQIAAAAzr2EBOXUKnm_jVnk0OJI7xSosDVG8KKPE1-m51RBrvYughuyMxQ-i1QfUnH94QxWIa6N4U6MouMmBA
String url = MessageFormat.format("HTTP://ditu.google.cn/maps/geo?q={0}&output={1}&sensor={2}&key={3}",arr);
URL urlmy = null;
try {
urlmy = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlmy.openConnection();
con.setFollowRedirects (true );
con.setInstanceFollowRedirects(false );
con.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
String s = "";
StringBuffer sb = new StringBuffer("");
while ((s = br.readLine()) != null ) {
sb.append(s+"\r\n");
}
ret = ""+sb;
} catch (MalformedURLException e) {
} catch (IOException e) {
}
}
return ret;
}
public String getlng(){
String[] str=ret.split(",");
//for(int i=0;i<str.length;i++){
// System.out.println(str[i]);
// }
return str[3];
}
public String getlat(){
String[] str=ret.split(",");
return str[2];
}
}
全站熱搜
留言列表