您的位置:首页 > 编程语言 > Java开发

百度地图地址经纬度互转,java代码(v2版本)

2017-03-07 00:00 501 查看
摘要: 百度地图web最新版

2个星期前用百度地图做了地址转换后。本来准备写个工具类添加到项目中突然发现不能用了,于是上百度地图api官网,发现接口已经更改了升级为v2,修改后可以使用,于是把工具类进行分享。

工具类:BaiDuMapUnit

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.URLEncoder;

import org.springframework.util.StringUtils;

public class BaiDuMapUnit {
/**
* 输入地址返回经纬度坐标 key lng(经度),lat(纬度)
*/
public static void getGeocoderLatitude(String address) {
BufferedReader in = null;
try {
address = URLEncoder.encode(address, "UTF-8");
URL tirc = new URL("http://api.map.baidu.com/geocoder/v2/?address=" + address + "&output=json&ak="
+ "wws9Qu73jw4QkOL6osEyIsA9Yob2yYgR"+"&callback=showLocation");
in = new BufferedReader(new InputStreamReader(tirc.openStream(), "UTF-8"));
String res;
StringBuilder sb = new StringBuilder("");
while ((res = in.readLine()) != null) {
sb.append(res.trim());
}
String str = sb.toString();
if (!StringUtils.isEmpty(str)) {
int lngStart = str.indexOf("lng\":");
int lngEnd = str.indexOf(",\"lat");
int latEnd = str.indexOf("},\"precise");
if (lngStart > 0 && lngEnd > 0 && latEnd > 0) {
String lng = str.substring(lngStart + 5, lngEnd);
String lat = str.substring(lngEnd + 7, latEnd);
System.out.println("lng:" + lng + "    lat:" + lat);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 输入经纬度返回地址 key lng(经度),lat(纬度)
*/
public static void getPosition(String latitude, String longitude) throws MalformedURLException {
BufferedReader in = null;
URL tirc = new URL("http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=" + latitude + "," + longitude
+ "&output=json&pois=1&ak=" + "wws9Qu73jw4QkOL6osEyIsA9Yob2yYgR");
try {
in = new BufferedReader(new InputStreamReader(tirc.openStream(), "UTF-8"));
String res;
StringBuilder sb = new StringBuilder("");
while ((res = in.readLine()) != null) {
sb.append(res.trim());
}
String str = sb.toString();
System.out.println(str);
if (!StringUtils.isEmpty(str)) {
int lngStart = str.indexOf("formatted_address\":\"");
int lngEnd = str.indexOf("\",\"business");
if (lngStart > 0 && lngEnd > 0 ) {
String ads = str.substring(lngStart + 20, lngEnd);
System.out.println("ads:" + ads);
}
}

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

测试:

import java.net.MalformedURLException;

import com.hy.loong.unit.BaiDuMapUnit;

public class Test1 {

public static void main(String[] args) throws MalformedURLException {
// TODO Auto-generated method stub
BaiDuMapUnit.getGeocoderLatitude("广东省深圳市福田区奥林匹克大厦26");
BaiDuMapUnit.getPosition("22.556585037727996", "114.05420498035405");
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息