经过整理后的代码
package a;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class Demo01 {
public static void getCoordinate(String addr) {
String addrs = "";
String address = null;
try {
address = java.net.URLEncoder.encode(addr, "UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
;
String output = "csv";
String key = "abc";
String url = String.format(
"http://maps.google.com/maps/geo?q=%s&output=%s&key=%s",
address, output, key);
URL myURL = null;
URLConnection httpsConn = null;
// 进行转码
try {
myURL = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
httpsConn = (URLConnection) myURL.openConnection();
if (httpsConn != null) {
InputStreamReader insr = new InputStreamReader(
httpsConn.getInputStream(), "UTF-8");
BufferedReader br = new BufferedReader(insr);
String data = null;
if ((data = br.readLine()) != null) {
System.out.println(data);
String[] retList = data.split(",");
if (retList.length > 2 && ("200".equals(retList[0]))) {
addrs = retList[2];
addrs = addr.replace("", "");
} else {
addrs = "";
}
}
insr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(addrs);
}
public static void main(String[] args) {
getCoordinate("中国北京市");
}
}
本文介绍了一种使用Java编程语言从Google Maps API获取地址对应地理坐标的实现方法。该方法首先对输入地址进行编码处理,然后通过构造特定的URL请求来获取地理坐标,并解析返回的数据以提取坐标信息。
2277

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



