我已經成功地創建了一個活動,用戶可以發佈他的狀態,並將他的當前位置放置在谷歌地圖,在android studio創建。我也嘗試查看地圖中的所有其他用戶,這是我成功完成的。但是,隨着他們的位置變化,markers
繼續增加。我想要實現一種情況,用戶在移動時可以在地圖上看到彼此,並且這些markers
也會相應地移動。我已使用Firebase作爲我的後端來存儲它們的位置和狀態。這是我提出的代碼。如何看到谷歌地圖中的其他標記移動android工作室谷歌地圖
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
private DatabaseReference mDatabase;
private DatabaseReference mAllUserLocation;
private DatabaseReference mUserLocation;
private FirebaseAuth mAuth;
private FirebaseUser mCurrentUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser();
mDatabase = FirebaseDatabase.getInstance().getReference();
mAllUserLocation = mDatabase.child("Location");
//userlocation dapat mCurrentUser.getUid yung ipapalit sa child
mUserLocation = mDatabase.child("Location").child(mCurrentUser.getUid());
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);
}
@Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
@Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient != null &&
ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//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);
}
}//onMapReady
//create markers for all users
protected Marker createMarker(double latitude, double longitude, String title, String snippet) {
return mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.anchor(0.5f, 0.5f)
.title(title)
.snippet(snippet).icon(BitmapDescriptorFactory.fromResource(R.drawable.placeholder)));
}
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_HIGH_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;
try {
mUserLocation.child("latitude").setValue(mLastLocation.getLatitude());
mUserLocation.child("longitude").setValue(mLastLocation.getLongitude());
}
catch(Exception e){}
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
LatLng latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
mAllUserLocation.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<UserLocationInMap> usersList = new ArrayList<>();
usersList.clear();
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
UserLocationInMap userLocationInMap = postSnapshot.getValue(UserLocationInMap.class);
usersList.add(userLocationInMap);
}
for(int i = 0 ; i < usersList.size() ; i++) {
createMarker(usersList.get(i).getLatitude(), usersList.get(i).getLongitude(), usersList.get(i).getTitle(), usersList.get(i).getSnippet());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//mMap.animateCamera(CameraUpdateFactory.zoomTo(16));
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder().target(latLng).tilt(30)
.zoom(18)
.build()));
}
@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.
}
}
@Override
protected void onStop() {
mUserLocation.child("title").setValue(null);
mUserLocation.child("latitude").setValue(null);
mUserLocation.child("longitude").setValue(null);
mUserLocation.child("snippet").setValue(null);
super.onStop();
}
}
請幫幫我!提前致謝! :)
你需要刷新你的'createMarker()'假設每個1sc,很棒的工作! – Ibrahim
先生,請問你該怎麼做? –