编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

jave根据经纬度获得地址,根据地址获得经纬度

wxchong 2024-09-02 03:34:31 开源技术 10 ℃ 0 评论

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="

+ "你的百度ak"+"&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 String 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=" + "你的百度ak");

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);

return ads;

//System.out.println("ads:" + ads);

}

}

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return null;

}

}

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表