GPS 定义获取经纬度

权限添加

< uses-permission android:name = "android.permission.ACCESS_FINE_LOCATION" ></ uses-permission >
判断GPS开启
private void openGPSSettings() {
     LocationManager alm = (LocationManager) this
         .getSystemService(Context.LOCATION_SERVICE);
     if (alm
         .isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
       Toast.makeText( this , "GPS模块正常" , Toast.LENGTH_SHORT)
           .show();
       return ;
     }
 
     Toast.makeText( this , "请开启GPS!" , Toast.LENGTH_SHORT).show();
     Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
     startActivityForResult(intent, 0 ); //此为设置完成后返回到获取界面
 
   }
获取地理位置
private void getLocation()
   {
     // 获取位置管理服务
     LocationManager locationManager;
     String serviceName = Context.LOCATION_SERVICE;
     locationManager = (LocationManager) this .getSystemService(serviceName);
     // 查找到服务信息
     Criteria criteria = new Criteria();
     criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度
     criteria.setAltitudeRequired( false );
     criteria.setBearingRequired( false );
     criteria.setCostAllowed( true );
     criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗
 
     String provider = locationManager.getBestProvider(criteria, true ); // 获取GPS信息
     Location location = locationManager.getLastKnownLocation(provider); // 通过GPS获取位置
     updateToNewLocation(location);
     // 设置监听器,自动更新的最小时间为间隔N秒(1秒为1*1000,这样写主要为了方便)或最小位移变化超过N米
     locationManager.requestLocationUpdates(provider, 100 * 1000 , 500 ,
         locationListener);  }
获取经纬度
private void updateToNewLocation(Location location) {
 
     TextView tv1;
     tv1 = (TextView) this .findViewById(R.id.tv1);
     if (location != null ) {
       double latitude = location.getLatitude();
       double longitude= location.getLongitude();
       tv1.setText( "纬度:" + latitude+ "\n经度" + longitude);
     } else {
       tv1.setText( "无法获取地理信息" );
     }
 
   }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值