位置信息的获取,有很多方法。这里只使用了HttpURLConnection中的GET方式访问第三方地图接口,获取实时位置,这里是通过申请百度地图访问接口调试使用。感觉精度一般,但勉强可以使用。
先上效果图
再上主要代码
//获取地理位置
class WxpPositionGetThread extends Thread {
private String lng;
private String lat;
private TextView show_content;
private String url = "";
private Handler handler = new Handler();
public WxpPositionGetThread(String url, String lat, String lng, TextView show_content) {
this.lat = lat;
this.lng = lng;
this.show_content = show_content;
this.url = url;
}
@Override
public void run() {
super.run();
getRun();
}
private void getRun() {
if (TextUtils.isEmpty(url)) {
throw new NullPointerException("please ensure url is not equals null ");
}
BufferedReader bufferedReader = null;
try {
url=url+"output=json&ak=esNPFDwwsXWtsQfw4NMNmur1&location=";
url = url + lat+",";
url = url + lng;
show_content.setText("位置信息");
URL httpUrl = new URL(url);
HttpURLConnection httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
//设置请求头header
httpURLConnection.setRequestMethod("GET");
//设置请求头header
httpURLConnection.setRequestProperty("test-header","get-header-value");
httpURLConnection.setReadTimeout(5000);
//获取内容
InputStream inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
final StringBuffer stringBuffer = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
//
//show_content.setText(stringBuffer.toString());
String msgr = stringBuffer.toString();
int pos=msgr.indexOf("formatted_address")+20;
int pos2=msgr.indexOf("business")-11;
show_content.setText(msgr.substring(pos,pos2));
//
handler.post(new Runnable() {
@Override
public void run() {
//解析json
try {
JSONObject jsonObject = new JSONObject(stringBuffer.toString());
String mykey = "formatted_address";
String jVal = "";
//jVal=jsonObject.getString(mykey);
//show_content.setText(jVal);
} catch (JSONException e) {
e.printStackTrace();
show_content.setText(e.toString());
}
//
// show_content.setText(msgr);
}
});
} catch (Exception e) {
//show_content.setText(e.toString());
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
再上调用代码
// 使用
Location location = getLastKnownLocation();
if(location==null) {
edtReturn.setText("请打开'App测试'的位置信息访问权限");
return ;
}
double lat = location.getLatitude();//获取纬度
double lng = location.getLongitude();//获取经度
edtReturn.setText(String.valueOf(lat)+" "+String.valueOf(lng));
String url = "http://api.map.baidu.com/geocoder?";
new WxpPositionGetThread(url, String.valueOf(lat), String.valueOf(lng), edtPos).start();