0

我已經實現了這個代碼,以獲得當前位置更新每移動10步,但我沒有獲得當前的經緯度,因爲我移動10步或更多,我有問題是現實的設置最小距離10步?如何獲得當前位置更新每移動10步,我就會得到當前位置更新

此外,每次我的代碼運行時,我都會得到不同的經緯度數字,如果我比較這些經緯度,我每次運行應用程序時都會在Google地圖網站上顯示當前位置,其大約400米遠離我目前的位置,爲什麼會發生。

private FusedLocationProviderClient mFusedLocationClient; 
private GoogleApiClient mGoogleApiClient; 
private GoogleMap mMap; 
private TextView tvLat; 
private TextView tvLng; 
Map<String, Double> latlng = new HashMap<>(); 
DatabaseReference data; 
private double lat; 
private double lng; 

CameraPosition CurrentLocation; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    SingletonConnectClass instence = SingletonConnectClass.getInstance(); 
    data = instence.firebaseSetup(); 
    setContentView(R.layout.activity_maps); 
    initView(); 
    setUpMapIfNeeded(); 
} 

private void setUpMapIfNeeded() { 

mFusedLocationClient 
= LocationServices.getFusedLocationProviderClient(this); 

    mapFragment.getMapAsync(this); 
} 

@Override 
public void onMapReady(GoogleMap googleMap) { 

    mMap = googleMap; 
    mMap.setMyLocationEnabled(true); 
    mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN); 
    getCurrentLocation(); 
    buildClient(); 
} 

private void getCurrentLocation(){ 
    mFusedLocationClient.getLastLocation() 
      .addOnSuccessListener(this, new OnSuccessListener<Location>() { 
    @Override 
    public void onSuccess(final Location location) { 
    CurrentLocation = new CameraPosition.Builder().target(new 
          LatLng(location.getLatitude(), 
           location.getLongitude())) 
           .zoom(15.5f) 
           .bearing(0) 
           .tilt(25) 
           .build(); 
     //changed camera position to current location and added marker there 
    } 

這裏是獲取當前位置更新,如果我在連接回調onConnected

public void onConnected(Bundle bundle) { 

    mFusedLocationClient.requestLocationUpdates(requestLocation(), 
    new LocationCallback() { 
     @Override 
     public void onLocationResult(LocationResult locationResult) { 
      for (final Location location : locationResult.getLocations()) { 

       //not getting changing current lat lng if i move 10 steps 
       tvLat.setText(Double.toString(location.getLatitude())); 
       tvLng.setText(Double.toString(location.getLongitude())); 

       lat = location.getLatitude(); 
       lng = location.getLongitude(); 

       //as result not camera position is not changed 
       changeCameraPosition(CameraUpdateFactory.newLatLngZoom(
         new LatLng(location.getLatitude(), location.getLong) 

        }}, Looper.myLooper()); 

回答

0
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, 
     GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener, 
     LocationListener { 

    private GoogleMap mMap; 
    GoogleApiClient mGoogleApiClient; 
    Location mLastLocation; 
    Marker mCurrLocationMarker; 
    LocationRequest mLocationRequest; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_maps); 

     if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
      checkLocationPermission(); 
     } 
     // Obtain the SupportMapFragment and get notified when the map is ready to be used. 
     SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
       .findFragmentById(R.id.map); 
     mapFragment.getMapAsync(this); 
    } 


    /** 
    * Manipulates the map once available. 
    * This callback is triggered when the map is ready to be used. 
    * This is where we can add markers or lines, add listeners or move the camera. In this case, 
    * we just add a marker near Sydney, Australia. 
    * If Google Play services is not installed on the device, the user will be prompted to install 
    * it inside the SupportMapFragment. This method will only be triggered once the user has 
    * installed Google Play services and returned to the app. 
    */ 
    @Override 
    public void onMapReady(GoogleMap googleMap) { 
     mMap = googleMap; 
     mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); 

     //Initialize Google Play Services 
     if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
      if (ContextCompat.checkSelfPermission(this, 
        Manifest.permission.ACCESS_FINE_LOCATION) 
        == PackageManager.PERMISSION_GRANTED) { 
       buildGoogleApiClient(); 
       mMap.setMyLocationEnabled(true); 
      } 
     } 
     else { 
      buildGoogleApiClient(); 
      mMap.setMyLocationEnabled(true); 
     } 
    } 

    protected synchronized void buildGoogleApiClient() { 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
     mGoogleApiClient.connect(); 
    } 

    @Override 
    public void onConnected(Bundle bundle) { 

     mLocationRequest = new LocationRequest(); 
     mLocationRequest.setInterval(1000); 
     mLocationRequest.setFastestInterval(1000); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 
     if (ContextCompat.checkSelfPermission(this, 
       Manifest.permission.ACCESS_FINE_LOCATION) 
       == PackageManager.PERMISSION_GRANTED) { 
      LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 
     } 

    } 

    @Override 
    public void onConnectionSuspended(int i) { 

    } 

    @Override 
    public void onLocationChanged(Location location) { 

      mLastLocation = location; 
      if (mCurrLocationMarker != null) { 
       mCurrLocationMarker.remove(); 
      } 

      //Place current location marker 
      LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); 
      MarkerOptions markerOptions = new MarkerOptions(); 
      markerOptions.position(latLng); 
      markerOptions.title("Current Position"); 
      markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)); 
      mCurrLocationMarker = mMap.addMarker(markerOptions); 

      //move map camera 
      mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
      mMap.animateCamera(CameraUpdateFactory.zoomTo(11)); 

      //stop location updates 
      if (mGoogleApiClient != null) { 
       LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 
      } 

    } 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 

    } 

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; 
    public boolean checkLocationPermission(){ 
     if (ContextCompat.checkSelfPermission(this, 
       Manifest.permission.ACCESS_FINE_LOCATION) 
       != PackageManager.PERMISSION_GRANTED) { 

      // Asking user if explanation is needed 
      if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
        Manifest.permission.ACCESS_FINE_LOCATION)) { 

       // Show an explanation to the user *asynchronously* -- don't block 
       // this thread waiting for the user's response! After the user 
       // sees the explanation, try again to request the permission. 

       //Prompt the user once explanation has been shown 
       ActivityCompat.requestPermissions(this, 
         new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
         MY_PERMISSIONS_REQUEST_LOCATION); 


      } else { 
       // No explanation needed, we can request the permission. 
       ActivityCompat.requestPermissions(this, 
         new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
         MY_PERMISSIONS_REQUEST_LOCATION); 
      } 
      return false; 
     } else { 
      return true; 
     } 
    } 

    @Override 
    public void onRequestPermissionsResult(int requestCode, 
              String permissions[], int[] grantResults) { 
     switch (requestCode) { 
      case MY_PERMISSIONS_REQUEST_LOCATION: { 
       // If request is cancelled, the result arrays are empty. 
       if (grantResults.length > 0 
         && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

        // permission was granted. Do the 
        // contacts-related task you need to do. 
        if (ContextCompat.checkSelfPermission(this, 
          Manifest.permission.ACCESS_FINE_LOCATION) 
          == PackageManager.PERMISSION_GRANTED) { 

         if (mGoogleApiClient == null) { 
          buildGoogleApiClient(); 
         } 
         mMap.setMyLocationEnabled(true); 
        } 

       } else { 

        // Permission denied, Disable the functionality that depends on this permission. 
        Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show(); 
       } 
       return; 
      } 

      // other 'case' lines to check for other permissions this app might request. 
      // You can add here other case statements according to your requirement. 
     } 
    } 
} 
+0

玩什麼服務我在我的代碼後失蹤移動10步的代碼? onLocationChanged?我必須手動實現onLocationChanged嗎? – blackHawk

+0

然後requestLocationUpdates做什麼? – blackHawk