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

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

2017-02-24 00:00 525 查看
摘要: 百度地图

/**
* 输入地址返回经纬度坐标
* key lng(经度),lat(纬度)
*/

public  void getGeocoderLatitude(String address){
BufferedReader in = null;
try {
address = URLEncoder.encode(address, "UTF-8");
URL tirc = new URL("http://api.map.baidu.com/geocoder?address="+ address +"&output=json&key="+"7d9fbeb43e975cd1e9477a7e5d5e192a");
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.isNotEmpty(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 void getposition(String latitude,String longitude) throws MalformedURLException{
BufferedReader in = null;
URL tirc = new URL("http://api.map.baidu.com/geocoder?location="+ latitude+","+longitude+"&output=json&key="+"E4805d16520de693a3fe707cdc962045");
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);
ObjectMapper mapper = new ObjectMapper();
if(StringUtils.isNotEmpty(str)){
JsonNode jsonNode = mapper.readTree(str);
jsonNode.findValue("status").toString();
JsonNode resultNode = jsonNode.findValue("result");
JsonNode locationNode = resultNode.findValue("formatted_address");
System.out.println(locationNode);
}

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