【问题标题】:How to see other markers in google map moving android studio google maps如何在谷歌地图中看到其他标记移动android工作室谷歌地图
【发布时间】:2017-02-26 08:45:37
【问题描述】:

我已经成功创建了一个活动,用户可以在其中发布他的状态并将他的当前位置放在谷歌地图中,​​在 android studio 中创建。我还尝试在地图中查看所有其他用户,我成功地做到了。然而,随着它们位置的变化,markers 不断增加。我想实现这样一种情况,即用户在移动时可以在地图上看到彼此,而markers 也会随之移动。我使用 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();
}

}

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

【问题讨论】:

  • 你需要刷新你的createMarker() 假设每 1sc,干得好!
  • 先生,请问您该怎么做?

标签: android google-maps google-maps-api-3


【解决方案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

或尝试在您的onResume() 中刷新createMarker()

【讨论】:

  • 希望对你有所帮助:)
  • 它解决了我的问题,先生!!!如果我能给你+1000,我会给你帮助!多谢!!! :D
猜你喜欢
  • 2017-09-21
  • 2013-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-14
  • 1970-01-01
  • 2014-08-28
  • 2013-04-08
相关资源
最近更新 更多