GPS或NewWork获取当前位置经纬度

  1. double latitude,longitude =0.0;
  2. //获取经纬度
  3. LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
  4. if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
  5. Location location = locationManager
  6. .getLastKnownLocation(LocationManager.GPS_PROVIDER);
  7. if(location != null){
  8. latitude = location.getLatitude(); //经度
  9. longitude = location.getLongitude(); //纬度
  10. }
  11. }else{
  12. LocationListener locationListener = new LocationListener() {
  13. public void onLocationChanged(Location location) { //当坐标改变时触发此函数,如果Provider传进相同的坐标,它就不会被触发
  14. if (location != null) {
  15. Log.i("SuperMap", "Location changed : Lat: "
  16. + location.getLatitude() + " Lng: "
  17. + location.getLongitude());
  18. }
  19. }
  20. public void onProviderDisabled(String provider) {
  21. // Provider被disable时触发此函数,比如GPS被关闭
  22. }
  23. public void onProviderEnabled(String provider) {
  24. // Provider被enable时触发此函数,比如GPS被打开
  25. }
  26. public void onStatusChanged(String provider, int status, Bundle extras) {
  27. // Provider的转态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
  28. }
  29. };
  30. locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000, 0,locationListener);
  31. Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
  32. if(location != null){
  33. latitude = location.getLatitude(); //经度
  34. longitude = location.getLongitude(); //纬度
  35. }
  36. }

  37. 加入权限:
  38. <!-- 连接互联网权限 -->
  39. <uses-permission android:name="android.permission.INTERNET" />
  40. <!-- gps定位权限 -->
  41. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  42. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
复制代码

GPS定位更精确一点

你可能感兴趣的:(new)