【问题标题】:I cannot retrieve my current longitude and latitude in google maps我无法在谷歌地图中检索我当前的经度和纬度
【发布时间】:2016-09-09 04:44:25
【问题描述】:

我正在使用以下代码来获取我当前位置的纬度和纬度,但它在 CameraPosition 中给了我空值。知道为什么吗?

   private void moveMapToMyLocation() {

    LocationManager locMan = (LocationManager) MapsActivity.this.getSystemService(Context.LOCATION_SERVICE);

    Criteria crit = new Criteria();


    Location loc = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    CameraPosition camPos = new CameraPosition.Builder()

            .target(new LatLng(loc.getLatitude(), loc.getLongitude()))

            .zoom(12.8f)

            .build();

    CameraUpdate camUpdate = CameraUpdateFactory.newCameraPosition(camPos);

   mMap.moveCamera(camUpdate);



}

【问题讨论】:

  • 显示您的完整代码。并确保您设备上的 GPS 为 Enable

标签: android google-maps


【解决方案1】:

这里是管理 GPS 相关操作的辅助类。

 public class GPSTracker  extends Service implements LocationListener {

        private final Context mContext;

        // flag for GPS status
        boolean isGPSEnabled = false;

        // flag for network status
        boolean isNetworkEnabled = false;

        // flag for GPS status
        boolean canGetLocation = false;

        Location location; // location
        double latitude; // latitude
        double longitude; // longitude

        // The minimum distance to change Updates in meters
        private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters

        // The minimum time between updates in milliseconds
        private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

        // Declaring a Location Manager
        protected LocationManager locationManager;

        public GPSTracker(Context context) {
            this.mContext = context;
            getLocation();
        }

        public Location getLocation() {
            try {
                locationManager = (LocationManager) mContext
                        .getSystemService(LOCATION_SERVICE);

                // getting GPS status
                isGPSEnabled = locationManager
                        .isProviderEnabled(LocationManager.GPS_PROVIDER);

                // getting network status
                isNetworkEnabled = locationManager
                        .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

                if (!isGPSEnabled && !isNetworkEnabled) {
                    // no network provider is enabled
                } else {
                    this.canGetLocation = true;
                    // First get location from Network Provider
                    if (isNetworkEnabled) {
                        try
                        {
                            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        }
                        catch (SecurityException e)
                        {

                        }
                        Log.d("Network", "Network");
                        if (locationManager != null) {

                            try
                            {
                                location = locationManager
                                        .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                            }
                            catch (SecurityException e)
                            {

                            }

                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                    // if GPS Enabled get lat/long using GPS Services
                    if (isGPSEnabled) {
                        if (location == null) {

                            try
                            {
                                locationManager.requestLocationUpdates(
                                        LocationManager.GPS_PROVIDER,
                                        MIN_TIME_BW_UPDATES,
                                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                                Log.d("GPS Enabled", "GPS Enabled");
                                if (locationManager != null) {
                                    location = locationManager
                                            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                    if (location != null) {
                                        latitude = location.getLatitude();
                                        longitude = location.getLongitude();
                                    }
                                }
                            }
                            catch (SecurityException s)
                            {

                            }

                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            return location;
        }

        /**
         * Stop using GPS listener
         * Calling this function will stop using GPS in your app
         * */
        public void stopUsingGPS(){
            if(locationManager != null){
                try
                {
                    locationManager.removeUpdates(GPSTracker.this);
                }
                catch (SecurityException e)
                {

                }

            }
        }

        /**
         * Function to get latitude
         * */
        public double getLatitude(){
            if(location != null){
                latitude = location.getLatitude();
            }

            // return latitude
            return latitude;
        }

        /**
         * Function to get longitude
         * */
        public double getLongitude(){
            if(location != null){
                longitude = location.getLongitude();
            }

            // return longitude
            return longitude;
        }

        /**
         * Function to check GPS/wifi enabled
         * @return boolean
         * */
        public boolean canGetLocation() {
            return this.canGetLocation;
        }

        /**
         * Function to show settings alert dialog
         * On pressing Settings button will lauch Settings Options
         * */
        public void showSettingsAlert(){
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

            // Setting Dialog Title
            alertDialog.setTitle("GPS Settings");

            // Setting Dialog Message
            alertDialog.setMessage("GPS is not active. Do you want to open?");

            // On pressing Settings button
            alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int which) {
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    mContext.startActivity(intent);
                }
            });

            // on pressing cancel button
            alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

            // Showing Alert Message
            alertDialog.show();
        }

        @Override
        public void onLocationChanged(Location location) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public IBinder onBind(Intent arg0) {
            return null;
        }

    }

成功创建 GPSTracker 类后,您需要在要获取经纬度的 Activity 中调用它。在 onCreate 方法中使用以下代码行。

    GPSTracker gps;
    double latitude;
    double longitude;

    gps = new GPSTracker(getActivity());

    // check if GPS enabled
    if(gps.canGetLocation())
    {
        latitude = gps.getLatitude();
        longitude = gps.getLongitude();
    }
    else
    {
        gps.showSettingsAlert();
    }

我们走到了尽头。请确保已授予所有权限

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

【讨论】:

    【解决方案2】:

    试试这个可能对你有用。

    LocationManager locationManager = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
    Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (loc != null) {
                onLocationChanged(loc);
            } else {
                loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                if (loc != null)
                    onLocationChanged(loc);
            }
    

    onLocationChanged 将在位置更改时被调用。为此,您必须实现 LocationListener(Interface)。 实现 LocationListener 后,您将获得一个名为 onLocationChanged 的​​覆盖方法。 通过这个方法可以得到经纬度。

    @Override
    public void onLocationChanged(Location location) {
        double dLatitude = location.getLatitude();   
        double dLongitude = location.getLongitude();
        LatLng currentLatLng = new LatLng(dLatitude, dLongitude);
    
    }
    

    【讨论】:

      【解决方案3】:

      使用此方法,这将在您的情况下正常工作

      private void initMap() {
      
              try {
                  // Loading map
                  initilizeMap();
      
                  // Changing map type
                  googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                  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;
                  }
                  googleMap.setMyLocationEnabled(true);
                  googleMap.getUiSettings().setZoomControlsEnabled(false);
                  googleMap.getUiSettings().setMyLocationButtonEnabled(true);
                  googleMap.getUiSettings().setCompassEnabled(true);
                  googleMap.getUiSettings().setRotateGesturesEnabled(true);
                  googleMap.getUiSettings().setZoomGesturesEnabled(true);
      
                  if (locationManager == null) {
                      locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
                  }
                  if (locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER)) {
                      isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                      isNetworkProviderEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
                      if (isGPSEnabled) {
                          location = getLastLocationByProvider(locationManager, LocationManager.GPS_PROVIDER, getApplicationContext());
                      } else if (isNetworkProviderEnabled) {
                          location = getLastLocationByProvider(locationManager, LocationManager.NETWORK_PROVIDER, getApplicationContext());
                      }
                      if (location != null) {
                          latitude = location.getLatitude();
                          longitude = location.getLongitude();
                      } else {
                          if (isNetworkProviderEnabled) {
                              locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 100000, 1, this);
                              provider_info = LocationManager.NETWORK_PROVIDER;
                          } else if (isGPSEnabled) {
                              locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100000, 1, this);
                              provider_info = LocationManager.GPS_PROVIDER;
                          } else {
      
                              alertDialog = Util.showOkDialog(new View.OnClickListener() {
                                  @Override
                                  public void onClick(View view) {
                                      if (Env.currentActivity != null) {
                                          if (Env.currentActivity instanceof LocationActivity) {
                                              try {
                                                  gotoSettings();
                                              } catch (Exception e) {
                                                  e.printStackTrace();
                                              }
                                          }
      
                                      }
                                      if (alertDialog != null) {
                                          alertDialog.dismiss();
                                          alertDialog = null;
                                      }
      
                                  }
                              }, this.getResources().getString(R.string.location_service_validation));
      
                          }
      
                          location = locationManager.getLastKnownLocation(provider_info);
                          if (location != null) {
                              latitude = location.getLatitude();
                              longitude = location.getLongitude();
                          }
                      }
      
      
                      MarkerOptions marker = new MarkerOptions().position(
                              new LatLng(latitude, longitude))
                              .title(getFullAddressLine(this));
                      marker.icon(BitmapDescriptorFactory
                              .defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
      
                      googleMap.addMarker(marker);
                      CameraPosition cameraPosition = new CameraPosition.Builder()
                              .target(new LatLng(latitude,
                                      longitude)).zoom(15).build();
                      googleMap.animateCamera(CameraUpdateFactory
                              .newCameraPosition(cameraPosition));
      
      
                  }
      
              } catch (Exception e) {
                  e.printStackTrace();
              }
      
          }
      

      【讨论】:

        【解决方案4】:

        使用下面的代码获取经度和纬度

        LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
            myLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
            double longitude = myLocation.getLongitude();
            double latitude = myLocation.getLatitude();
        
            private final LocationListener locationListener = new LocationListener() {
                public void onLocationChanged(Location location) {
                    longitude = location.getLongitude();
                    latitude = location.getLatitude();
                }
            }
        

        【讨论】:

          猜你喜欢
          • 2013-02-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-10-18
          • 1970-01-01
          相关资源
          最近更新 更多