2016-05-13 40 views
0

我使用下面的代码来获取当前位置的lat和lang,但它给了我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); 



} 
+0

显示您的完整代码。并确保您的设备上的GPS为“启用”。 –

回答

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类后,您需要在要采取纬度和经度的活动中调用它。在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"/> 
+0

感谢这对我工作:) – bhaskar

+0

很高兴听到;) –

0

使用获得的经度和纬度

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(); 
     } 
    } 
0

使用此方法,这将是做工精细,你的情况

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(); 
     } 

    } 
0

试试这可能这应该为你工作。

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); 
     } 

当位置有changed.And为此,你将必须实现LocationListener的(接口)onLocationChanged将被调用。 一旦你实现了LocationListener,你将会得到一个名为onLocationChanged的覆盖方法。 通过此方法,您将获得经度和纬度。

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

}