Android 實現定位及地理位置解析

        昨兒折騰了一天,把Android 手機定位、獲取手機當前位置的功能給搞掂了。此次記下來,否則又忘~~
        思路很簡單,第一步,獲取經緯度,第二步,把經緯度轉換爲地址。看起來簡單,可是實現起來比較鬱悶~~
        
        獲取經緯度能夠有不少選擇。我剛開始作時,想着Google最好用,可是寫完代碼測試下,悲催的逆解析地址老是爲空。。
    代碼以下:
    


      
   
/**
* 
* 由街道信息轉換爲經緯度
* @param address 街道信息
* @return 包含經緯度的一個double 數組,{longtitude,latitude}
*/
public static double[] getLocationInfoByGoogle(String address){
//定義一個HttpClient,用於向指定地址發送請求
HttpClient client = new DefaultHttpClient();

//向指定地址發送Get請求
HttpGet hhtpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?address="+address+"ka&sensor=false");

StringBuilder sb = new StringBuilder();


try {
//獲取服務器響應
HttpResponse response = client.execute(hhtpGet);

HttpEntity entity = response.getEntity();

//獲取服務器響應的輸入流
InputStream stream = entity.getContent();

int b;
//循環讀取服務器響應
while((b = stream.read()) != -1){
sb.append((char)b);
}

//將服務器返回的字符串轉換爲JSONObject  對象
JSONObject jsonObject = new JSONObject(sb.toString());

//從JSONObject 中取出location 屬性
JSONObject location = jsonObject.getJSONObject("results").getJSONObject("0").getJSONObject("geometry").getJSONObject("location");
 
//獲取經度信息
double longtitude = location.getDouble("lng");
double latitude = location.getDouble("lat");

return new double[]{longtitude,latitude};

} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) { 
e.printStackTrace();
}


return null;
}



/**
* 根據經緯度獲取對應地址,此處的經緯度須使用Google或者高德地圖的經緯度;<br>
* 若使用百度地圖經緯度,須通過百度API接口(BMap.Convertor.transMore(points,2,callback))的轉換;
* @param longitude 經度
* @param latitude 緯度
* @return 詳細街道地址
*/
public static String getAddressByGoogle(double longitude,double latitude){
//定義一個HttpClient,用於向指定地址發送請求
HttpClient client = new DefaultHttpClient();

//向指定地址發送Get請求
HttpGet hhtpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?latlng="+latitude+","+longitude+"&sensor=false&region=cn");

StringBuilder sb = new StringBuilder();


try {
//獲取服務器響應
HttpResponse response = client.execute(hhtpGet);

HttpEntity entity = response.getEntity();

//獲取服務器響應的輸入流
InputStream stream = entity.getContent();

int b;
//循環讀取服務器響應
while((b = stream.read()) != -1){
sb.append((char)b);
}

//將服務器返回的字符串轉換爲JSONObject  對象
JSONObject jsonObject = new JSONObject(sb.toString());

//從JSONObject 中取出location 屬性
JSONObject location = jsonObject.getJSONObject("results").getJSONObject("0").getJSONObject("formatted_address");
 
 

return  location.toString();

} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) { 
e.printStackTrace();
}
return null;


}




        這件事的慘痛經歷告訴我:必定要有政治覺悟,否則編代碼丫多的都不成。閒話少扯,後來想,百度定位,高德定位均可以嘛。百度的忒鬱悶,看了半天文檔,被攪得暈頭轉向。看太高德文檔後,發現高德相對百度實現起來比較簡單,與原來Android自己的定位、地址解析代碼、邏輯相差無幾。So,用高德!
    如今看下實現邏輯,點擊按鈕,觸發監聽事件,在監聽事件裏,先判斷是否開啓GPS,沒開啓的話轉到設置界面,讓用戶開啓去。固然,若是手機沒GPS硬件支持,就調用網絡的定位。接着經過GPS或網絡獲取手機當前經緯度,將經緯度解析爲地址信息,再將地址信息顯示到界面。OK,完事兒。


     再看對應實現代碼,第一步,檢測GPS是否開啓:
    
/**
	 * 
	 * 判斷GPS是否開啓,若未開啓,則進入GPS設置頁面;設置完成後需用戶手動回界面
	 * @param  currentActivity 
	 * @return
	 */
	public static void openGPSSettings(Context context){
		//獲取位置服務
		LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		//若GPS未開啓
		if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
			 Toast.makeText(context, "請開啓GPS!", Toast.LENGTH_SHORT).show();
			 Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
			 context.startActivity(intent);  
		}
	}
	
	
	/**
	 * 
	 * 判斷GPS是否開啓,若未開啓,則進入GPS設置頁面;設置完成後仍回原界面
	 * @param  currentActivity 
	 * @return
	 */
	public static void openGPSSettings(Activity currentActivity){
		//獲取位置服務
		LocationManager lm = (LocationManager) currentActivity.getSystemService(Context.LOCATION_SERVICE);
		//若GPS未開啓
		if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
			 Toast.makeText(currentActivity, "請開啓GPS!", Toast.LENGTH_SHORT).show();
			 Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
			 currentActivity.startActivityForResult(intent,0); //此爲設置完成後返回到獲取界面
		}
	}






第二步,獲取手機當前經緯度:

/**
	 * 使用高德定位獲取經緯度,包括GPS獲取,網絡獲取;
	 * 
	 * @param context 上下文環境
	 * @param locationListener 位置監聽實例
	 * @return HashMap<String,Location> 返回Location實例的HashMap,其中,GPS對應的Location實例對應的Key值爲"gps",網絡爲"network";
	 */
	public static Map<String,Location> getLocationObject(Context context,LocationListener locationListener){
		Map<String,Location> lMap = new HashMap<String, Location>();
		
		LocationManagerProxy	locationManager = LocationManagerProxy.getInstance(context); 
		for(final String provider : locationManager.getProviders(true)){
			
			//GPS 
			if(LocationManagerProxy.GPS_PROVIDER.equals(provider) )  {  
				
				Location l =locationManager.getLastKnownLocation(provider);
				if(null != l){
					 lMap.put(GPS, l);
				}
				locationManager.requestLocationUpdates(provider,  mLocationUpdateMinTime, mLocationUpdateMinDistance,locationListener);
				break;
			}
			
			//網絡 定位服務開啓
		if(LocationManagerProxy.NETWORK_PROVIDER.equals(provider))  {  
				
				Location l =locationManager.getLastKnownLocation(provider);
				if(null != l){
					 lMap.put(NETWORK, l);
				}
				locationManager.requestLocationUpdates(provider,  mLocationUpdateMinTime, mLocationUpdateMinDistance,locationListener);
				break;
			}
			
		}
		return lMap;
	}

     


第三步,解析地址: java


/**
	 * 使用高德地理解析,根據經緯度獲取對應地址,;<br>
	 * 若使用百度地圖經緯度,須通過百度API接口(BMap.Convertor.transMore(points,2,callback))的轉換;
	 * @param context 
	 * @param longitude 經度
	 * @param latitude 緯度
	 * @return 詳細街道地址
	 */
	public static String getAddress(Context context,double longitude,double latitude){
		String address= null;
		 
		GeoPoint geo = new GeoPoint((int)(latitude*1E6),(int)(longitude*1E6));
		 
		 Geocoder mGeocoder = new Geocoder(context);
		 
		 int x = geo.getLatitudeE6();//獲得geo 緯度,單位微度(度* 1E6) 
		 double x1 = ((double)x)/1000000;  
		 int y = geo.getLongitudeE6();//獲得geo 經度,單位微度(度* 1E6)  
		 double y1 = ((double) y) / 1000000;  
		 
		//獲得逆理編碼,參數分別爲:緯度,經度,最大結果集  
		 try {
			 //高德根據政府規定,在由GPS獲取經緯度顯示時,使用getFromRawGpsLocation()方法;
			List<Address> listAddress = mGeocoder.getFromRawGpsLocation(x1, y1, 3);
			if(listAddress.size()!=0){
				Address a = listAddress.get(0);
				
/*				sb.append("getAddressLine(0)"+a.getAddressLine(0)+"\n");
				sb.append("a.getAdminArea()"+a.getAdminArea()+"\n");
				sb.append("a.getCountryName()"+a.getCountryName()+"\n");
				
				sb.append("getFeatureName()"+a.getFeatureName()+"\n");
				sb.append("a.getLocality()"+a.getLocality()+"\n");
				sb.append("a.getMaxAddressLineIndex()"+a.getMaxAddressLineIndex()+"\n");
				sb.append("getPhone()"+a.getPhone()+"\n");
				sb.append("a.getPremises()"+a.getPremises()+"\n");
				sb.append("a.getSubAdminArea()"+a.getSubAdminArea()+"\n");
				
				
				sb.append("a.getSubLocality()"+a.getSubLocality()+"\n");
				sb.append("getSubThoroughfare()"+a.getSubThoroughfare()+"\n");
				sb.append("a.getThoroughfare()"+a.getThoroughfare()+"\n");
				sb.append("a.getUrl()"+a.getUrl()+"\n");
				*/
				address = a.getCountryName()+a.getLocality()+(a.getSubLocality()==null?"":a.getSubLocality())+(a.getThoroughfare()==null?"":a.getThoroughfare())
						+(a.getSubThoroughfare()==null?"":a.getSubThoroughfare())+a.getFeatureName();
			}
		} catch (AMapException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
				return address;
				
				
	}
Ok,打完收工!     
相關文章
相關標籤/搜索