我成功创建了一个活动,用户可以在其中发布他的状态并将他的当前位置放置在android工作室中创建的google map中。我还尝试在map中查看所有其他用户,我成功地做到了。但是,随着他们的位置发生变化,标记
不断增加。我想实现这样一种情况,即用户在移动时可以在地图上看到彼此,并且这些标记
也会相应地移动。我使用Firebase作为我的后端来存储他们的位置和状态。这是我想出的代码。
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();
}
}
请帮帮我!提前感谢!:)
您可以尝试改用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) {
}
});
来源
或者尝试在您的恢复中刷新createMarker()。
所以我正在准备一个页面,其中有一个谷歌地图,有两个形式,即纬度和经度,和一个提交按钮。
我想更改Google Maps上选定的标记图标,因此我有以下代码: 在这一行,我从下面得到错误: 例外情况如下:
我需要一些帮助来绘制我正在绘制的地图。地图并不特别复杂,因为我是一个初学者,我有一堆带有信息窗口的标记(完成后还会有更多标记),单击标记或选择页面HTML端下拉菜单的相应项时可以打开这些标记。 当信息窗口打开时(在HTML菜单中单击或选择),我想做但自己找不到的是在地图上自动居中标记。我假设有某种函数可以分配给click或infowindow打开事件,但无法确定是哪种函数以及如何实现它。 我的代码
我知道周围也有类似的问题,但我无法找到一个可靠的答案,这是我的问题:有没有什么方法可以在没有谷歌地图引用的情况下将标记存储在ArrayList(或任何其他存储)中,然后简单地将它们添加到我的地图中? 背景:我有一个应用程序,目前有大约3500个标记。每个标记还有一个与之相关联的数据(布尔数组存储每个标记的数据,用于根据用户交互使它们可见/不可见)。目前,我使用扩展AsyncTask的类来获取这些标
我已经尝试在这里和谷歌地图API留档上查看了大量的代码块,但仍然无法找出如何隐藏标记。 这是我正在使用的当前代码,它在一个实例中有效。有一次,我在带有标记的函数中添加了“for”循环。setMap(null)Firefox显示以下错误: markers.set地图不是一个函数 附加信息:校园地图和完整代码(不包括地图API)
}; 这是在displayRoute()函数之前使用的