利用cellID获取经纬度,地址信息

package GoogleJson;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

public class LocationUtil {
	private JSONObject getAreaObj(LocationUtil test,int cellID){
		URL url = null;
		HttpURLConnection conn = null;
		JSONObject result = null;
		try {
			url = new URL("http://www.google.com/loc/json");
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");

			String json = test.getJson(cellID);
//			System.out.println(json);
			
			conn.getOutputStream().write(json.getBytes());
			conn.getOutputStream().flush();
			conn.getOutputStream().close();
			
			int responseCode = conn.getResponseCode();
			System.out.println("code :" + responseCode);
			BufferedReader in = new BufferedReader(new InputStreamReader(conn
					.getInputStream()));
			String inputLine;
			inputLine = in.readLine();
			in.close();
			result = new JSONObject(inputLine);
//			location = result.getJSONObject("location");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (conn != null)
				conn.disconnect();
		}
		return result;
	}
	
	private String getJson(int cellID){
		String json = "{ "
			+ "\"version\": \"1.1.0\", "
			+ "\"host\": \"maps.google.com\", "
			// +
			+ "\"home_mobile_country_code\": 460, "
			+ "\"home_mobile_network_code\": 00, "
			+ "\"radio_type\": \"gsm\", "
			+ "\"carrier\": \"Vodafone\", "
			+ "\"request_address\": true, "
			+ "\"address_language\": \"zh_CN\", "
			+ "\"cell_towers\": [ "
			+ "{ "
			+ "\"cell_id\": "+cellID+", "
			+ "\"location_area_code\": 20516, "
			+ "\"mobile_country_code\": 460, "
			+ "\"mobile_network_code\": 00, "
			+ "\"age\": 0, "
			+ "\"signal_strength\": -60, "
			+ "\"timing_advance\": 5555 "
			+ "}" + "]" + "}";
		return json;
	}
	
	public static void main(String args[]) throws JSONException {

		int cellID = 4913;
		LocationUtil test = new LocationUtil();
		// 解析结果
		JSONObject result = test.getAreaObj(test, cellID);
		JSONObject location = result.getJSONObject("location");
		JSONObject address = location.getJSONObject("address");
		
		double latitude = location.getDouble("latitude");
		double longitude = location.getDouble("longitude");
		
		System.out.println("longitude = " + longitude);
		System.out.println("latitude = " + latitude);
		System.out.println(address.getString("country") + address.getString("region") + 
				address.getString("city") + address.getString("street"));
	
	}
}

QQ截图20120807142345

这个例子里用的是org.json.jar包,今天把这小例子放到项目中发现项目的json包是json-lib.,此时更换jar包对项目影响比较大,改下代码:

首先修改import net.sf.json.*;

再修改result = new JSONObject(inputLine) 为 result = JSONObject.fromObject(inputLine)。

这样就不用更新项目里的jar包了。

你可能感兴趣的:(利用cellID获取经纬度,地址信息)