Android获取经纬度:从谷歌源码中提取出来的获取经纬度代码
Android获取经纬度:从谷歌源码中提取出来的获取经纬度代码
经过测试发现,在有的手机上获取经纬度没有问题,在其他的手机上获取经纬度却又问题,因此我查看了谷歌提供的源码,从源码里面提取出了一份新的获取经纬度的代码,以后每次获取基本都获取成功了:
- LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
- Location retLocation = null ;
- LocationProvider gpsProvider =
- lm.getProvider("gps");
- if(gpsProvider == null)
- {
- longitude.setText("0");
- dimensions.setText("0");
- return;
- }
- //下面必须原封不动的照搬,否则就会出错,原因我也不知道。
- lm.requestLocationUpdates(gpsProvider.getName(),
- 0 /*minTime*/, 0 /*minDist*/, this);
- try {
- lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
- 3000 /*minTime*/, 0 /*minDist*/, this);
- } catch (RuntimeException e) {
- // If anything at all goes wrong with getting a cell location do not
- // abort. Cell location is not essential to this app.
- }
- retLocation = lm.getLastKnownLocation("gps");
- if(retLocation==null)
- {
- longitude.setText("0");
- dimensions.setText("0");
- }
- else
- {
- double geoLatitude = retLocation.getLatitude();//获取经度
- double geoLongitude = retLocation.getLongitude();//获取维度
- longitude.setText(""+geoLongitude);
- dimensions.setTag(""+geoLatitude);
- }
- longitude.setEnabled(false);
- Location改变的消息在这个接口方法中获取:
- private void updataGpsWidthLocation(Location location) {
- // TODO Auto-generated method stub
- if(location != null)
- {
- double lit = location.getLongitude();//进度
- double dimen = location.getLatitude();//维度
- longitude.setText(""+lit);
- this.dimensions.setText(""+dimen);
- float accuray=location.getAccuracy();//获取精确度
- Log.e("", "accuray:"+accuray);
- accurText.setText(""+accuray);
- }
- else
- {
- longitude.setText("0");
- dimensions.setText("0");
- }
- }
评论暂时关闭