谷歌地图更新的位置

时间:2017-10-13 00:35:57

标签: android google-maps

这是我的代码。它只会在大多数时间内显示没有更新位置的地图,但令人惊讶的是它确实会显示更新的位置地图

public class CarteClient extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {

     private GoogleMap mMap;
     GoogleApiClient Gac;
     Location Local;
     LocationRequest demLocal;

     private Button déco, demT;
     private LatLng positionClient;


     //Gac=Google Api Client
     //demLocal=demande de localisation
     //déco=déconnexion
     //demT=demande Toleka

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_carte_client);
         // 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);

         déco=(Button)findViewById(R.id.déconnexion);
         demT=(Button)findViewById(R.id.demtoleka);
         déco.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 FirebaseAuth.getInstance().signOut();
                 Intent i= new Intent(CarteClient.this,SecondActivity.class);
                 startActivity(i);
                 finish();
                 return;
             }
         });
         demT.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {

                 String IdUtil= FirebaseAuth.getInstance().getCurrentUser().getUid();
                 DatabaseReference réfbd= FirebaseDatabase.getInstance().getReference("DemandeClient");

                 GeoFire geoFire= new GeoFire(réfbd);
                 geoFire.setLocation(IdUtil, new GeoLocation(Local.getLatitude(), Local.getLongitude()));

                 positionClient=new LatLng(Local.getLatitude(), Local.getLongitude());
                 mMap.addMarker(new MarkerOptions().position(positionClient).title("Client par Ici"));

                 demT.setText("Contact avec le chauffeur en cours...");

                 //réfbd=référence base de données
                 //IdUtil= Identité Utilisateur


             }
         });
     }


     @Override
     public void onMapReady(GoogleMap googleMap) {
         mMap = googleMap;

         // Add a marker in Sydney and move the camera
         buildGoogleApiClient();
         if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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;
         }
         mMap.setMyLocationEnabled(true);
     }

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

     @Override
     public void onLocationChanged(Location location) {
         Local=location;

         LatLng latlon= new LatLng(location.getLatitude(), location.getLongitude());

         mMap.moveCamera(CameraUpdateFactory.newLatLng(latlon));
         mMap.animateCamera(CameraUpdateFactory.zoomTo(11));


     }


     @Override
     public void onConnected(@Nullable Bundle bundle) {
         demLocal = new LocationRequest();
         demLocal.setInterval(1000);
         demLocal.setFastestInterval(1000);
         demLocal.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

         if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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;
         }
         LocationServices.FusedLocationApi.requestLocationUpdates(Gac, demLocal, this);

     }

     @Override
     public void onConnectionSuspended(int i) {

     }

     @Override
     public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

     }

     @Override
     protected void onStop(){
         super.onStop();

     }

}

1 个答案:

答案 0 :(得分:0)

public class MainActivity1 extends Activity 
implements ConnectionCallbacks,OnConnectionFailedListener {

private static final String TAG = MainActivity.class.getSimpleName();

private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;

private Location mLastLocation;

// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;

// boolean flag to toggle periodic location updates
private boolean mRequestingLocationUpdates = false;

private LocationRequest mLocationRequest;

// Location updates intervals in sec
private static int UPDATE_INTERVAL = 10000; // 10 sec
private static int FATEST_INTERVAL = 5000; // 5 sec
private static int DISPLACEMENT = 10; // 10 meters

// UI elements
private TextView lblLocation;
private Button btnShowLocation, btnStartLocationUpdates;

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

    lblLocation = (TextView) findViewById(R.id.lblLocation);
    btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
    btnStartLocationUpdates = (Button) findViewById(R.id.btnLocationUpdates);

    // First we need to check availability of play services
    if (checkPlayServices()) {

        // Building the GoogleApi client
        buildGoogleApiClient();
    }

    // Show location button click listener
    btnShowLocation.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            displayLocation();
        }
    });
}

/**
 * Method to display the location on UI
 * */
private void displayLocation() {

    mLastLocation = LocationServices.FusedLocationApi
            .getLastLocation(mGoogleApiClient);

    if (mLastLocation != null) {
        double latitude = mLastLocation.getLatitude();
        double longitude = mLastLocation.getLongitude();

        lblLocation.setText(latitude + ", " + longitude);

    } else {

        lblLocation
                .setText("(Couldn't get the location. Make sure location is enabled on the device)");
    }
}

/**
 * Creating google api client object
 * */
protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API).build();
}

/**
 * Method to verify google play services on the device
 * */
private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil
            .isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                    PLAY_SERVICES_RESOLUTION_REQUEST).show();
        } else {
            Toast.makeText(getApplicationContext(),
                    "This device is not supported.", Toast.LENGTH_LONG)
                    .show();
            finish();
        }
        return false;
    }
    return true;
}

@Override
protected void onStart() {
    super.onStart();
    if (mGoogleApiClient != null) {
        mGoogleApiClient.connect();
    }
}

@Override
protected void onResume() {
    super.onResume();

    checkPlayServices();
}

/**
 * Google api callback methods
 */
@Override
public void onConnectionFailed(ConnectionResult result) {
    Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
            + result.getErrorCode());
}

@Override
public void onConnected(Bundle arg0) {

    // Once connected with google api, get the location
    displayLocation();
}

@Override
public void onConnectionSuspended(int arg0) {
    mGoogleApiClient.connect();
}

}

进行参考点击此处click