Android GPS 定位 2 详细地址

android中有自带的GeoCoder类,但是里面之多只能查询到XX市,详细的地址信息还是要通过调用google的GeoCoding Api来获取

首先通过定位获取当前经纬度,和1中基本一样
之后当获取到当前经纬度后开启异步任务

private LocationListener listener = new LocationListener() {

		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub

		}

		// 定位设备启用是时
		public void onProviderEnabled(String provider) {
			Log.d(TAG, "onProviderEnabled");

		}

		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub

		}

		// 定位获得信息改变时
		public void onLocationChanged(Location location) {
			Log.d(TAG, "onLocationChanged");
			latitudeTxt.setText("latitude:" + location.getLatitude());
			longitudeTxt.setText("longitude:" + location.getLongitude());
			MainActivity.location = location;
			locationTask.execute();//向google请求数据
		}
	};

请求直接通过url拼接,注意经纬度之间不能有空格,以及最后的sensor不能少,否则返回会被拒绝。这里选择的是返回json数据。
 
private AsyncTask<Integer, Integer, String> locationTask = new AsyncTask<Integer, Integer, String>() {

		@Override
		protected void onPostExecute(String result) {
			addressTxt.setText(result);
		}

		@Override
		protected String doInBackground(Integer... params) {
			String sURL = "http://maps.googleapis.com/maps/api/geocode/json?latlng="
					+ location.getLatitude()
					+ ","
					+ location.getLongitude()
					+ "&sensor=true";
			try {
				URL url = new URL(sURL);
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();

				BufferedReader reader = new BufferedReader(
						new InputStreamReader(conn.getInputStream()));

				String line = "";
				StringBuffer buff = new StringBuffer();
				while ((line = reader.readLine()) != null) {
					buff.append(line);
				}

				Log.d(TAG, buff.toString());
				return jsonParams(buff.toString());//数据json解析
			} catch (IOException e) {
				e.printStackTrace();
			}

			return null;
		}

	};


json解析没什么,不过数据很多,可以参考API给的出格式来解析https://developers.google.com/maps/documentation/geocoding/?hl=zh-cn#ReverseGeocoding。这里只解析出了详细的地址,还有地址周边的一些数据都没做解析。

private String jsonParams(String buff) {
		try {
			JSONObject mainObject = new JSONObject(buff);
			JSONArray resultArray = mainObject.getJSONArray("results");

			JSONObject resultObject = resultArray.getJSONObject(0);
			String address = resultObject.getString("formatted_address");
			return address;
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值