1. 程式人生 > >Android利用谷歌地圖獲取並解析經緯度對應的地理位置

Android利用谷歌地圖獲取並解析經緯度對應的地理位置

    最近需要對GPS定位資訊進行地理位置解析,看到一些文章裡面建議使用百度地圖API來做,不過考慮到百度地圖在國外的使用體驗,還是想試試通過Google地圖來進行地理位置獲取,閒話不多說,上程式碼。

首先當然需要檢查GPS功能模組以及GPS開啟狀態,同時在使用GPS時需要考慮到GPS許可權請求:

/**
 * check if it has any gps provider
 * @return boolean
 */
public boolean isHasGPSModule(){
    // TODO Auto-generated method stub
LocationManager lmManager = (LocationManager) getSystemService(LOCATION_SERVICE
); if (lmManager != null) { List<String> mProviders = lmManager.getAllProviders(); if (mProviders != null && mProviders.contains(LocationManager.GPS_PROVIDER)) { return true; } } return false; }
/**
 * Check if GPS opened
 *
 * @return boolean
*/
private boolean checkGPSIsOpen() { boolean isOpen; LocationManager locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE); isOpen = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); return isOpen; }
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" 
/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

確認GPS處於開啟使用後,註冊位置監聽:

if (isHasGPSModule()) {
    lmManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_LOW);
criteria.setAltitudeRequired(true);
criteria.setBearingRequired(true);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = lmManager.getBestProvider(criteria, true);
Log.i("GPS", "bestprovider=" + provider);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
//    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
return;
}
    Location location = lmManager.getLastKnownLocation(provider);
    if (location != null) {
        updateWithNewLocation(location);
} else {
        lmManager.requestLocationUpdates(provider, 5000L, 20f, locationListener);showProgressDialog("search location ...");
}
}
等待位置更新onLocationChanged:
LocationListener locationListener = new LocationListener() {
    @Override
public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
Log.i("GPS", "Locationchanged");dismissProgressDialog();lmManager.removeUpdates(locationListener);
updateWithNewLocation(location);
}

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

    @Override
public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
}

    @Override
public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
}
};
接下來,重點來了,使用得到的location資訊去請求位置:
private void updateWithNewLocation(Location location) {
    Log.i("GPS", "updateLocation");
String latitude = String.valueOf(location.getLatitude());
String longitude = String.valueOf(location.getLongitude());
Log.i("GPS", "updateLocation" + "latitude=" + latitude + "longitude=" + longitude);
String url = String.format(
            "http://maps.google.cn/maps/api/geocode/json?latlng=%s,%s&sensor=false&language=en_us",
latitude, longitude); //請求的連結是重點,嘗試了很多次,預設語言中文,這裡由於需要設定成美國英語
sendLocationAdressRequest(url);
}
進行網路請求並得到位置資訊:
private void sendLocationAdressRequest(String address) {
    HttpUtil.sendOkHttpRequest(address, new okhttp3.Callback() {
        @Override
public void onResponse(Call call, Response response) throws IOException {
            if (response != null && !isResponse) {
                isResponse = true;
String responseData = response.body().string();
// get address
showResponse(responseData);
Log.i("GPS", "responseData=" + responseData);} } @Overridepublic void onFailure(Call call, IOException e) { Log.i("GPS", "request address form Google map failure");} });}
private String showResponse(String response) {
    JSONObject jsonObj = null;
String result = "";
    try {
        // 把伺服器相應的字串轉換為JSONObject
jsonObj = new JSONObject(response);
// 解析出響應結果中的地址資料
JSONArray jsonArray = jsonObj.getJSONArray("results");
Log.i("GPS", "lenth = " + jsonArray.length());
result = jsonArray.getJSONObject(jsonArray.length() - 1).getString("formatted_address");
/*result =  jsonObj.getJSONArray(0).getString("formatted_address");*/
        // 此處jsonArray.length()-1得到的位置資訊是最後一列,得到的是Google地圖劃分區域的最外層,
// 如國家或者特殊城市-香港等,若需要得到具體位置使用0Log.i("GPS", "address json result = " + result);
} catch (JSONException e) {
        e.printStackTrace();
Log.i("GPS", "address json result error");
}
    return result;
}

在這裡主要感謝這兩篇文章:http://blog.csdn.net/fulianwu/article/details/6540890 和 http://blog.sina.com.cn/s/blog_4b20ae2e0101b2eo.html

以及郭臨大神的《Android第一行程式碼》中對於okhttp3的工具類的使用:

public class HttpUtil {
    public static void sendOkHttpRequest(String url, okhttp3.Callback callback){
        OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
                .url(ur)
                .build();
client.newCall(request).enqueue(callback);
}
}

寫到這裡簡單的定位和地址解析已經完成,可以使用得到的地理位置進行相關的開發。

原創文章,如需轉載,請註明出去~