2017-02-26 49 views
1

我已经成功地创建了一个活动,用户可以发布他的状态,并将他的当前位置放置在谷歌地图,在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(); 
} 

} 

请帮帮我!提前致谢! :)

+0

你需要刷新你的'createMarker()'假设每个1sc,很棒的工作! – Ibrahim

+0

先生,请问你该怎么做? –

回答

1

您可以尝试使用addChildEventListner代替

Map<String, Marker> markers = new HashMap(); 

ref.addChildEventListener(new ChildEventListener() { 
    @Override 
    public void onChildAdded(DataSnapshot dataSnapshot, String s) { 
     UsersActive uA = dataSnapshot.getValue(UsersActive.class); 

     // ... 

    Marker uAmarker = mMap.addMarker(markerOptions); 
    markers.put(dataSnapshot.getKey(), uAmarker); 
} 

@Override 
public void onChildChanged(DataSnapshot dataSnapshot, String s) { 
    UsersActive uA = dataSnapshot.getValue(UsersActive.class); 

    // ... 

    if (markers.contains(dataSnapshot.getKey())) { 
     Marker marker = markers.get(dataSnapshot.getKey()); 

     marker.remove(); 
     // or 
     // marker.setPosition(newPosition); 
    } 

    Marker uAmarker = mMap.addMarker(markerOptions); 
    markers.put(dataSnapshot.getKey(), uAmarker); 
} 

@Override 
public void onChildRemoved(DataSnapshot dataSnapshot) { 
    if (markers.contains(dataSnapshot.getKey())) { 
     Marker marker = markers.get(dataSnapshot.getKey()); 
     marker.remove(); 
    } 
} 

@Override 
public void onChildMoved(DataSnapshot dataSnapshot, String s) { 

} 

@Override 
public void onCancelled(DatabaseError databaseError) { 

} 
}); 

source

或尝试刷新createMarker()onResume()

+0

感谢您阐述您的答案先生! :) –

+0

希望它帮助你:) – Ibrahim

+0

它解决了我的问题SIR!如果我能给你+1000我会给你的帮助!非常感谢!!! :d –