最近需要对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) { ListmProviders = 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; }
android:name="android.permission.ACCESS_COARSE_LOCATION" />
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) ; } } @Override public 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地图划分区域的最外层, // 如国家或者特殊城市-香港等,若需要得到具体位置使用0; Log.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); } }
写到这里简单的定位和地址解析已经完成,可以使用得到的地理位置进行相关的开发。
原创文章,如需转载,请注明出去~