百度地图Geocoding API 用法,返回json解析

看了好久,犯了很多错,看的我自己都烦了,还是基础太差,要努力呀。

Mainactivity.java

public class MainActivity extends Activity {

	public static final int SHOW_LOCATION = 0;

	private TextView positionTextView;

	private LocationManager locationManager;

	private String provider;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		positionTextView = (TextView) findViewById(R.id.position_text_view);
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		// 获取所有可用的位置提供器
		List<String> providerList = locationManager.getProviders(true);
		if (providerList.contains(LocationManager.GPS_PROVIDER)) {
			provider = LocationManager.GPS_PROVIDER;
		} else if (providerList.contains(LocationManager.NETWORK_PROVIDER)) {
			provider = LocationManager.NETWORK_PROVIDER;
		} else {
			// 当没有可用的位置提供器时,弹出Toast提示用户
			Toast.makeText(this, "No location provider to use",
					Toast.LENGTH_SHORT).show();
			return;
		}
		Location location = locationManager.getLastKnownLocation(provider);
		if (location != null) {
			// 显示当前设备的位置信息
			showLocation(location);
		}
		locationManager.requestLocationUpdates(provider, 5000, 1,
				locationListener);
	}

	protected void onDestroy() {
		super.onDestroy();
		if (locationManager != null) {
			// 关闭程序时将监听器移除
			locationManager.removeUpdates(locationListener);
		}
	}

	LocationListener locationListener = new LocationListener() {

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
		}

		@Override
		public void onProviderEnabled(String provider) {
		}

		@Override
		public void onProviderDisabled(String provider) {
		}

		@Override
		public void onLocationChanged(Location location) {
			// 更新当前设备的位置信息
			showLocation(location);
		}
	};

	private void showLocation(final Location location) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					// 组装反向地理编码的接口地址
					StringBuilder url = new StringBuilder();
					url.append("http://api.map.baidu.com/geocoder/v2/?ak=nUvlnh8wk6cDupYs5foacyXz&location=");
					url.append(location.getLatitude()).append(",")
							.append(location.getLongitude());
					url.append("&output=json&pois=1");
					HttpClient httpClient = new DefaultHttpClient();
					HttpGet httpGet = new HttpGet(url.toString());
					// 在请求消息头中指定语言,保证服务器会返回中文数据
					httpGet.addHeader("Accept-Language", "zh-CN");
					HttpResponse httpResponse = httpClient.execute(httpGet);
					if (httpResponse.getStatusLine().getStatusCode() == 200) {
						HttpEntity entity = httpResponse.getEntity();
						String response = EntityUtils.toString(entity, "utf-8");
						JSONObject jsonObject = new JSONObject(response);
						if(jsonObject.get("status").toString().equals("0")){
							StringBuilder address =new StringBuilder();
							address.append(jsonObject.getJSONObject("result").getString("formatted_address"));
							address.append("\r\n").append("纬度:").append(location.getLatitude()).append("\r\n")
							.append("经度").append(location.getLongitude());
							String aString =address.toString();
							Log.d("Mainactivity",aString);
							Message message = new Message();
							message.what = SHOW_LOCATION;
							message.obj = aString;
							handler.sendMessage(message);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	private Handler handler = new Handler() {

		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SHOW_LOCATION:
				String currentPosition = (String) msg.obj;
				positionTextView.setText(currentPosition);
				break;
			default:
				break;
			}
		}

	};
	}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这里给出一个Java的示例代码,同样是使用地理编码服务API来根据地址查询经纬度: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; public class BaiduMapDemo { public static void main(String[] args) { String address = "北京市海淀区上地十街10号"; // 要查询的地址 String output = "json"; // 输出格式 String ak = "Your_AK"; // 替换成你的Access Key try { address = URLEncoder.encode(address, "UTF-8"); // URL编码 String url = "http://api.map.baidu.com/geocoding/v3/?address=" + address + "&output=" + output + "&ak=" + ak; String result = sendGet(url); // 发送HTTP请求并获取响应结果 JSONObject json = JSON.parseObject(result); int status = json.getIntValue("status"); if (status == 0) { JSONObject location = json.getJSONObject("result").getJSONObject("location"); double lng = location.getDoubleValue("lng"); // 经度 double lat = location.getDoubleValue("lat"); // 纬度 System.out.println("经度:" + lng + ",纬度:" + lat); } else { System.out.println("查询失败"); } } catch (Exception e) { e.printStackTrace(); } } public static String sendGet(String url) throws IOException { URL realUrl = new URL(url); URLConnection conn = realUrl.openConnection(); conn.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; StringBuilder result = new StringBuilder(); while ((line = in.readLine()) != null) { result.append(line); } in.close(); return result.toString(); } } ``` 同样需要替换掉AK为你自己的Access Key。这里使用了FastJSON解析JSON响应结果,需要在项目中引入FastJSON的依赖。 另外,由于Java中的URL编码和解码方法不同于Python,所以需要使用`URLEncoder.encode()`方法将地址进行编码。同时,还需要注意请求频率和配额的问题,以免超过限制。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值