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

整理一些關於地圖的資料,方便以後查閱:

/**
* 
* 由街道信息轉換爲經緯度
* @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是否開啓:
    
01/**
02     *
03     * 判斷GPS是否開啓,若未開啓,則進入GPS設置頁面;設置完成後需用戶手動回界面
04     * @param  currentActivity
05     * @return
06     */
07    public static void openGPSSettings(Context context){
08        //獲取位置服務
09        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
10        //若GPS未開啓
11        if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
12             Toast.makeText(context, "請開啓GPS!", Toast.LENGTH_SHORT).show();
13             Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
14             context.startActivity(intent); 
15        }
16    }
17     
18     
19    /**
20     *
21     * 判斷GPS是否開啓,若未開啓,則進入GPS設置頁面;設置完成後仍回原界面
22     * @param  currentActivity
23     * @return
24     */
25    public static void openGPSSettings(Activity currentActivity){
26        //獲取位置服務
27        LocationManager lm = (LocationManager) currentActivity.getSystemService(Context.LOCATION_SERVICE);
28        //若GPS未開啓
29        if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
30             Toast.makeText(currentActivity, "請開啓GPS!", Toast.LENGTH_SHORT).show();
31             Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
32             currentActivity.startActivity(intent); //此爲設置完成後返回到獲取界面
33        }
34    }






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

01/**
02     * 使用高德定位獲取經緯度,包括GPS獲取,網絡獲取;
03     *
04     * @param context 上下文環境
05     * @param locationListener 位置監聽實例
06     * @return HashMap<String,Location> 返回Location實例的HashMap,其中,GPS對應的Location實例對應的Key值爲"gps",網絡爲"network";
07     */
08    public static Map<String,Location> getLocationObject(Context context,LocationListener locationListener){
09        Map<String,Location> lMap = new HashMap<String, Location>();
10         
11        LocationManagerProxy    locationManager = LocationManagerProxy.getInstance(context);
12        for(final String provider : locationManager.getProviders(true)){
13             
14            //GPS
15            if(LocationManagerProxy.GPS_PROVIDER.equals(provider) )  { 
16                 
17                Location l =locationManager.getLastKnownLocation(provider);
18                if(null != l){
19                     lMap.put(GPS, l);
20                }
21                locationManager.requestLocationUpdates(provider,  mLocationUpdateMinTime, mLocationUpdateMinDistance,locationListener);
22                break;
23            }
24             
25            //網絡 定位服務開啓
26        if(LocationManagerProxy.NETWORK_PROVIDER.equals(provider))  { 
27                 
28                Location l =locationManager.getLastKnownLocation(provider);
29                if(null != l){
30                     lMap.put(NETWORK, l);
31                }
32                locationManager.requestLocationUpdates(provider,  mLocationUpdateMinTime, mLocationUpdateMinDistance,locationListener);
33                break;
34            }
35             
36        }
37        return lMap;
38    }

     


第三步,解析地址:


01/**
02     * 使用高德地理解析,根據經緯度獲取對應地址,;<br>
03     * 若使用百度地圖經緯度,須經過百度API接口(BMap.Convertor.transMore(points,2,callback))的轉換;
04     * @param context
05     * @param longitude 經度
06     * @param latitude 緯度
07     * @return 詳細街道地址
08     */
09    public static String getAddress(Context context,double longitude,double latitude){
10        String address= null;
11          
12        GeoPoint geo = new GeoPoint((int)(latitude*1E6),(int)(longitude*1E6));
13          
14         Geocoder mGeocoder = new Geocoder(context);
15          
16         int x = geo.getLatitudeE6();//得到geo 緯度,單位微度(度* 1E6)
17         double x1 = ((double)x)/1000000
18         int y = geo.getLongitudeE6();//得到geo 經度,單位微度(度* 1E6) 
19         double y1 = ((double) y) / 1000000
20          
21        //得到逆理編碼,參數分別爲:緯度,經度,最大結果集 
22         try {
23             //高德根據政府規定,在由GPS獲取經緯度顯示時,使用getFromRawGpsLocation()方法;
24            List<Address> listAddress = mGeocoder.getFromRawGpsLocation(x1, y1, 3);
25            if(listAddress.size()!=0){
26                Address a = listAddress.get(0);
27                 
28/*              sb.append("getAddressLine(0)"+a.getAddressLine(0)+"\n");
29                sb.append("a.getAdminArea()"+a.getAdminArea()+"\n");
30                sb.append("a.getCountryName()"+a.getCountryName()+"\n");
31                 
32                sb.append("getFeatureName()"+a.getFeatureName()+"\n");
33                sb.append("a.getLocality()"+a.getLocality()+"\n");
34                sb.append("a.getMaxAddressLineIndex()"+a.getMaxAddressLineIndex()+"\n");
35                sb.append("getPhone()"+a.getPhone()+"\n");
36                sb.append("a.getPremises()"+a.getPremises()+"\n");
37                sb.append("a.getSubAdminArea()"+a.getSubAdminArea()+"\n");
38                 
39                 
40                sb.append("a.getSubLocality()"+a.getSubLocality()+"\n");
41                sb.append("getSubThoroughfare()"+a.getSubThoroughfare()+"\n");
42                sb.append("a.getThoroughfare()"+a.getThoroughfare()+"\n");
43                sb.append("a.getUrl()"+a.getUrl()+"\n");
44                */
45                address = a.getCountryName()+a.getLocality()+(a.getSubLocality()==null?"":a.getSubLocality())+(a.getThoroughfare()==null?"":a.getThoroughfare())
46                        +(a.getSubThoroughfare()==null?"":a.getSubThoroughfare())+a.getFeatureName();
47            }
48        } catch (AMapException e) {
49            // TODO Auto-generated catch block
50            e.printStackTrace();
51        }
52          
53                return address;
54                 
55                 
56    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章