static String AK = "********"; // 百度地图密钥
public void getAddress() {
ArrayList<String> columnList = new ArrayList<String>();
File file = new File("H:\\data.xls");
try {
FileInputStream in = new FileInputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(in); //xls读取
//XSSFWorkbook wb = new XSSFWorkbook(in); //xlsx读取
Sheet sheet = wb.getSheetAt(0);//Excel 数量
int firstRowNum = sheet.getFirstRowNum();//初始行 0
int lastRowNum = sheet.getLastRowNum(); //总数行
Row row = null; //行
Cell cell_a = null; //列
String [] sum;
FileOutputStream out=new FileOutputStream(file);
for (int i = 0; i <= lastRowNum; i++) {
row = sheet.getRow(i); //取得第i行
cell_a = row.getCell(0); //取得i行的第一列
String cellValue = cell_a.getStringCellValue().trim();
//System.out.println(cellValue);
columnList.add(cellValue);
String dom = "贵州省黔东南苗族侗族自治州"+cellValue;
String coordinate = getCoordinate(dom);
System.out.println("'" + dom + "'的经纬度为:" + coordinate);
String a;
String b;
if(coordinate==null){
a="0000000000";
b="0000000000";
}else{
sum = coordinate.split(",");
a=sum[0];
b=sum[1];
}
row=sheet.createRow((short)(i));
row.createCell(0).setCellValue(cellValue);
row.createCell(1).setCellValue(a);
row.createCell(2).setCellValue(b);
}
out.flush();
wb.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 调用百度地图API根据地址,获取坐标
public static String getCoordinate(String address) {
if (address != null && !"".equals(address)) {
//address = address.replaceAll("\\s*", "").replace("#", "栋");
String url = "http://api.map.baidu.com/geocoder/v2/?address=" + address + "&output=json&ak=" + AK;
String json = loadJSON(url);
if (json != null && !"".equals(json)) {
JSONObject obj = JSONObject.fromObject(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"); // 纬度
coordCovert pCoordCovert = new coordCovert();
double[] coords = pCoordCovert.bd09toWgs1984(lng, lat);//百度转wgs1984
DecimalFormat df = new DecimalFormat("#.######");
return df.format(coords[0]) + "," + df.format(coords[1]);
}
}
}
return null;
}
public 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();
}
技术交流联系qq:875782548