Java 没有';t在另一台设备中显示geofense圆圈,圆圈仅在一台设备中显示
在这个应用程序中,我将为当前用户生成geofense圈,如果一个设备在latlong A,B,那么这将在A,B中心生成geofense圈,而另一个设备在latlong C,D,那么这将在另一个设备中在C,D生成geofense圈,在这个应用程序中,一个设备只有一个geofense圈,在设备当前位置生成 但在此应用程序中,圆圈仅在一台设备中显示 这是我的地图活动Java 没有';t在另一台设备中显示geofense圆圈,圆圈仅在一台设备中显示,java,android,google-maps,google-cloud-firestore,geofencing,Java,Android,Google Maps,Google Cloud Firestore,Geofencing,在这个应用程序中,我将为当前用户生成geofense圈,如果一个设备在latlong A,B,那么这将在A,B中心生成geofense圈,而另一个设备在latlong C,D,那么这将在另一个设备中在C,D生成geofense圈,在这个应用程序中,一个设备只有一个geofense圈,在设备当前位置生成 但在此应用程序中,圆圈仅在一台设备中显示 这是我的地图活动 public class MapsActivity extends FragmentActivity implements G
public class MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener,
OnMapReadyCallback,
ResultCallback<Status> {
private static final String TAG = "MapsActivity";
private Integer j=0;
private Marker mark;
private LatLng location,l1;
private GoogleMap map;
private Toolbar mTopToolbar;
private List<String> ids = new ArrayList<>();
private FirebaseAuth mAuth;
private Double current_lat, current_long, current_geoloc, lat, lon, geoloc;
private String current_name,current_names, name, currentuserid;
private BitmapDescriptor vnrPoint, banPoint;
private LocationRequest locationRequest;
private final int UPDATE_INTERVAL = 6000;
private final int FASTEST_INTERVAL = 3000;
private User users,user,n;
private Marker geoFenceMarker;
private Circle circle,circle2;
private List<MarkerOptions> markerList;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference myCollection = db.collection("users");
private GeoFire geoFire = new GeoFire(myCollection);
private GoogleApiClient googleApiClient;
private Location lastLocation;
private TextView textLat, textLong;
private MapFragment mapFragment;
private String idd;
private SeekBar volumeControl = null;
private PendingIntent geoFencePendingIntent;
private static final float GEOFENCE_RADIUS = 100.0f; // in meter
private final int REQ_PERMISSION = 999;
private final int GEOFENCE_REQ_CODE = 0;
private final String KEY_GEOFENCE_LAT = "GEOFENCE LATITUDE";
private final String KEY_GEOFENCE_LON = "GEOFENCE LONGITUDE";
private static final String NOTIFICATION_MSG = "NOTIFICATION MSG";
// Create a Intent send by the notification
public static Intent makeNotificationIntent(Context context, String msg) {
Intent intent = new Intent( context, MapsActivity.class );
intent.putExtra( NOTIFICATION_MSG, msg );
return intent;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
volumeControl = (SeekBar) findViewById(R.id.verticalseekbar);
volumeControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
Toast.makeText(getApplicationContext(), "seek bar progress:" + progressChanged,
Toast.LENGTH_SHORT).show();
}
});
textLat = (TextView) findViewById(R.id.lat);
textLong = (TextView) findViewById(R.id.lon);
mAuth = FirebaseAuth.getInstance();
getdata();
mTopToolbar = findViewById(R.id.my_toolbar);
setActionBar(mTopToolbar);
// 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);
createGoogleApi();
}
@Override
protected void onStart() {
super.onStart();
// Call GoogleApiClient connection when starting the Activity
googleApiClient.connect();
}
@Override
protected void onStop() {
super.onStop();
// Disconnect GoogleApiClient when stopping Activity
googleApiClient.disconnect();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.option_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.main_logout_option) {
mAuth.signOut();
LoginManager.getInstance().logOut();
gotologinactivity();
}
if (item.getItemId() == R.id.clear) {
clearGeofence();
return true;
}
if (item.getItemId() == R.id.geofence) {
startGeofence();
return true;
}
if (item.getItemId() == R.id.Refresh) {
finish();
startActivity(getIntent());
return true;
}
return true;
}
private void createGoogleApi()
{
Log.d(TAG, "createGoogleApi()");
if ( googleApiClient == null ) {
googleApiClient = new GoogleApiClient.Builder( this )
.addConnectionCallbacks(this)
.addOnConnectionFailedListener( this )
.addApi( LocationServices.API )
.build();
}
}
// Check for permission to access Location
private boolean checkPermission() {
Log.d(TAG, "checkPermission()");
// Ask for permission if it wasn't granted yet
return (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED );
}
// Asks for permission
private void askPermission() {
Log.d(TAG, "askPermission()");
ActivityCompat.requestPermissions(
this,
new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
REQ_PERMISSION
);
}
// Verify user's response of the permission requested
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult()");
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch ( requestCode ) {
case REQ_PERMISSION: {
if ( grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED ){
// Permission granted
getLastKnownLocation();
} else {
// Permission denied
permissionsDenied();
}
break;
}
}
}
// App cannot work without the permissions
private void permissionsDenied() {
Log.w(TAG, "permissionsDenied()");
// TODO close app and warn user
}
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
}
// Start location Updates
private void startLocationUpdates(){
Log.i(TAG, "startLocationUpdates()");
locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL)
.setSmallestDisplacement(30);
//movement in meter
if ( checkPermission() )
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
@Override
public void onLocationChanged(Location location) {
Log.d(TAG, "onLocationChanged ["+location+"]");
lastLocation = location;
clearGeofence();
startGeofence();
writeActualLocation(location);
}
@Override
public void onConnected(@Nullable Bundle bundle) {
Log.i(TAG, "onConnected()");
getLastKnownLocation();
recoverGeofenceMarker();
}
// GoogleApiClient.ConnectionCallbacks suspended
@Override
public void onConnectionSuspended(int i) {
Log.w(TAG, "onConnectionSuspended()");
}
// GoogleApiClient.OnConnectionFailedListener fail
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.w(TAG, "onConnectionFailed()");
}
// Get last known location
private void getLastKnownLocation() {
Log.d(TAG, "getLastKnownLocation()");
if ( checkPermission() ) {
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if ( lastLocation != null ) {
Log.i(TAG, "LasKnown location. " +
"Long: " + lastLocation.getLongitude() +
" | Lat: " + lastLocation.getLatitude());
writeLastLocation();
startLocationUpdates();
} else {
Log.w(TAG, "No location retrieved yet");
startLocationUpdates();
}
}
else askPermission();
}
private void writeActualLocation(Location location) {
textLat.setText( "Lat: " + location.getLatitude() );
textLong.setText( "Long: " + location.getLongitude() );
geoloc = (location.getLatitude() + 90) * 180 + location.getLongitude();
markerLocation(new LatLng(location.getLatitude(), location.getLongitude()));
markerForGeofence(new LatLng(location.getLatitude(), location.getLongitude()));
HashMap<String, Object> profileMap = new HashMap<>();
profileMap.put("latitude",location.getLatitude());
profileMap.put("longtitude", location.getLongitude());
profileMap.put("geoFireLocation", geoloc);
idd = mAuth.getCurrentUser().getUid();
db.collection("users").document(idd)
.update(profileMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid)
{
Log.d(TAG,"save");
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.d(TAG,"not save");
}
});
}
private void writeLastLocation() {
writeActualLocation(lastLocation);
}
private Marker locationMarker;
private void markerLocation(LatLng latLng) {
Log.i(TAG, "markerLocation("+latLng+")");
String title = latLng.latitude + ", " + latLng.longitude;
MarkerOptions markerOptions = new MarkerOptions()
.position(latLng)
.title(title);
if ( map!=null ) {
if ( locationMarker != null )
locationMarker.remove();
locationMarker = map.addMarker(markerOptions);
float zoom = 14f;
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, zoom);
//map.animateCamera(cameraUpdate);
}
}
private void markerForGeofence(LatLng latLng) {
Log.i(TAG, "markerForGeofence("+latLng+")");
String title = latLng.latitude + ", " + latLng.longitude;
// Define marker options
MarkerOptions markerOptions = new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE))
.title(title);
Log.e("marker",name+""+latLng.toString());
if ( map!=null ) {
// Remove last geoFenceMarker
if (geoFenceMarker != null)
geoFenceMarker.remove();
geoFenceMarker = map.addMarker(markerOptions);
Log.e("geomarker",title+""+geoFenceMarker);
}
}
// Start Geofence creation process
private void startGeofence() {
Log.i(TAG, "startGeofence()");
if( geoFenceMarker != null ) {
a( );
} else {
Log.e(TAG, "Geofence marker is null");
}
}
private void a()
{
for (int i=0;i<j;i++)
{
Geofence geofence = createGeofence( geoFenceMarker.getPosition(), GEOFENCE_RADIUS,ids.get(i));
GeofencingRequest geofenceRequest = createGeofenceRequest( geofence );
addGeofence( geofenceRequest );
}
}
private Geofence createGeofence( LatLng latLng, float radius,String id) {
Log.d(TAG, "createGeofence");
return new Geofence.Builder()
.setRequestId(id)
.setCircularRegion( latLng.latitude,latLng.longitude, radius)
.setTransitionTypes( Geofence.GEOFENCE_TRANSITION_ENTER
| Geofence.GEOFENCE_TRANSITION_EXIT )
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setNotificationResponsiveness(1000)
.build();
}
// Create a Geofence Request
private GeofencingRequest createGeofenceRequest( Geofence geofence ) {
Log.d(TAG, "createGeofenceRequest");
return new GeofencingRequest.Builder()
.setInitialTrigger( GeofencingRequest.INITIAL_TRIGGER_ENTER | GeofencingRequest.INITIAL_TRIGGER_EXIT )
.addGeofence( geofence )
.build();
}
private PendingIntent createGeofencePendingIntent() {
Log.d(TAG, "createGeofencePendingIntent");
if ( geoFencePendingIntent != null )
return geoFencePendingIntent;
Intent intent = new Intent( this, GeofenseTrasitionService.class);
return PendingIntent.getService(
this, GEOFENCE_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT );
}
// Add the created GeofenceRequest to the device's monitoring list
private void addGeofence(GeofencingRequest request) {
Log.d(TAG, "addGeofence");
if (checkPermission())
LocationServices.GeofencingApi.addGeofences(
googleApiClient,
request,
createGeofencePendingIntent()
).setResultCallback(this);
}
@Override
public void onResult(@NonNull Status status) {
Log.i(TAG, "onResult: " + status);
if ( status.isSuccess() ) {
saveGeofence();
drawGeofence();
} else {
// inform about fail
}
}
private Circle geoFenceLimits;
private void drawGeofence() {
Log.e("circle", "draw");
if ( circle2 != null )
circle2.remove();
// LatLng last = new LatLng(22.28,73.19);
circle2 = map.addCircle(new CircleOptions()
.center(geoFenceMarker.getPosition())
.radius(GEOFENCE_RADIUS)
.strokeColor(Color.argb(50, 70,70,70))
.fillColor(Color.argb(100, 150,150,150))
.strokeWidth(5.0f));
// map.moveCamera(CameraUpdateFactory.newLatLng(geoFenceMarker.getPosition()));
}
// Saving GeoFence marker with prefs mng
private void saveGeofence() {
Log.d(TAG, "saveGeofence()");
SharedPreferences sharedPref = getPreferences( Context.MODE_PRIVATE );
SharedPreferences.Editor editor = sharedPref.edit();
editor.putLong( KEY_GEOFENCE_LAT, Double.doubleToRawLongBits( geoFenceMarker.getPosition().latitude ));
editor.putLong( KEY_GEOFENCE_LON, Double.doubleToRawLongBits( geoFenceMarker.getPosition().longitude ));
editor.apply();
}
// Recovering last Geofence marker
private void recoverGeofenceMarker() {
Log.d(TAG, "recoverGeofenceMarker");
SharedPreferences sharedPref = getPreferences( Context.MODE_PRIVATE );
if ( sharedPref.contains( KEY_GEOFENCE_LAT ) && sharedPref.contains( KEY_GEOFENCE_LON )) {
double lat = Double.longBitsToDouble( sharedPref.getLong( KEY_GEOFENCE_LAT, -1 ));
double lon = Double.longBitsToDouble( sharedPref.getLong( KEY_GEOFENCE_LON, -1 ));
LatLng latLng = new LatLng( lat, lon );
markerForGeofence(latLng);
drawGeofence();
}
}
// Clear Geofence
private void clearGeofence() {
Log.d(TAG, "clearGeofence()");
LocationServices.GeofencingApi.removeGeofences(
googleApiClient,
createGeofencePendingIntent()
).setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(@NonNull Status status) {
if ( status.isSuccess() ) {
// remove drawing
removeGeofenceDraw();
}
}
});
}
private void removeGeofenceDraw() {
Log.d(TAG, "removeGeofenceDraw()");
if ( geoFenceMarker != null)
geoFenceMarker.remove();
if ( circle2 != null )
circle2.remove();
}
private void getdata() {
currentuserid = FirebaseAuth.getInstance().getCurrentUser().getUid();
db.collection("users").document(currentuserid).addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
if(documentSnapshot.exists())
{
current_name = documentSnapshot.getString("name");
current_lat = documentSnapshot.getDouble("latitude");
Log.e("lat",current_lat.toString());
current_long = documentSnapshot.getDouble("longtitude");
Log.e("lat",current_long.toString());
location = new LatLng(current_lat, current_long);
if(circle!=null){
circle.remove();
}
try {
circle = map.addCircle(new CircleOptions()
.center(location)
.radius(3000)
.strokeColor(Color.BLUE)
.fillColor(0x220000FF)
.strokeWidth(5.0f)
);
}
catch (Exception e1)
{
Log.e("ex",e1.getMessage());
}
// map.addMarker(new MarkerOptions().position(location).title(current_name));
// map.moveCamera(CameraUpdateFactory.newLatLng(location));
Log.d(TAG,"data"+current_lat+" "+current_long+" "+current_name);
j=0;
getalluser();
}
}
});
}
private void getalluser()
{
QueryLocation queryLocation = QueryLocation.fromDegrees(current_lat, current_long);
Distance searchDistance = new Distance(3, DistanceUnit.KILOMETERS);
geoFire.query()
.whereNearTo(queryLocation, searchDistance)
.build()
.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
if(mark != null)
{
mark.remove();
}
for(final QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots)
{
user = documentSnapshot.toObject(User.class);
current_names = user.getName();
LatLng all = new LatLng(user.getLatitude(),user.getLongtitude());
showmark(all,current_names,documentSnapshot.getId());
}
}
});
}
private void showmark(LatLng all, String current_n,String id)
{
if(!id.equals(currentuserid))
{
j++;
ids.add(id);
Log.d(TAG, "location"+" "+id+" "+currentuserid+" "+ all + " " + current_n);
vnrPoint = BitmapDescriptorFactory.fromResource(R.drawable.marker_a);
mark = map.addMarker(new MarkerOptions().position(all).icon(vnrPoint).title(current_n));
// map.moveCamera(CameraUpdateFactory.newLatLng(all));
//getnotification();
}
}
private void gotologinactivity() {
Intent intent = new Intent(MapsActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}
公共类映射活动扩展了FragmentActivity实现
GoogleAppClient.ConnectionCallbacks,
GoogleAppClient.OnConnectionFailedListener,
LocationListener,
四月一日,
结果回拨{
私有静态最终字符串TAG=“MapsActivity”;
私有整数j=0;
专用标记;
私人停车场,l1;
私人谷歌地图;
专用工具栏;
私有列表ID=new ArrayList();
私人消防队;
专用双电流_-lat、电流_-long、电流_-geoloc、lat、lon、geoloc;
私有字符串current_name、current_name、name、currentuserid;
专用位图描述符vnpoint,banPoint;
私人位置请求位置请求;
私有最终整数更新间隔=6000;
私人最终int\U间隔=3000;
私有用户,用户,n;
专用标记;
私人圈子圈子,圈子2;
私有列表标记列表;
私有FirebaseFirestore db=FirebaseFirestore.getInstance();
private CollectionReference myCollection=db.collection(“用户”);
私人GeoFire GeoFire=新GeoFire(myCollection);
私人GoogleapClient GoogleapClient;
私人场所;
私有TextView textLat,textLong;
私有MapFragment-MapFragment;
专用字符串idd;
私有SeekBar volumeControl=null;
私人吊挂帐篷土工围栏吊挂帐篷;
专用静态最终浮式土工围栏_半径=100.0f;//以米为单位
私人最终int REQ_权限=999;
专用最终国际地理围栏要求代码=0;
专用最终字符串密钥\u geof围栏\u LAT=“geof围栏纬度”;
专用最终字符串密钥_geofinence_LON=“geofinence经度”;
私有静态最终字符串通知\u MSG=“NOTIFICATION MSG”;
//创建由通知发送的意图
公共静态意图makeNotificationIntent(上下文,字符串消息){
意向意向=新意向(上下文,MapsActivity.class);
意向。额外通知(通知信息,信息);
返回意图;
}
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_映射);
volumeControl=(SeekBar)findViewById(R.id.verticalseekbar);
volumeControl.setOnSeekbarchaneListener(新的SeekBar.OnSeekbarchaneListener(){
int=0;
public void onProgressChanged(SeekBar-SeekBar、int-progress、boolean-fromUser){
progressChanged=进度;
}
开始跟踪触摸时的公共无效(SeekBar SeekBar){
//TODO自动生成的方法存根
}
TopTrackingTouch(SeekBar SeekBar)上的公共无效{
Toast.makeText(getApplicationContext(),“搜索栏进度:”+progressChanged,
吐司。长度(短)。show();
}
});
textLat=(TextView)findViewById(R.id.lat);
textLong=(TextView)findViewById(R.id.lon);
mAuth=FirebaseAuth.getInstance();
getdata();
mTopToolbar=findviewbyd(R.id.my_工具栏);
setActionBar(mTopToolbar);
//获取SupportMapFragment,并在地图准备好使用时收到通知。
SupportMapFragment mapFragment=(SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map);
getMapAsync(这个);
createGoogleApi();
}
@凌驾
受保护的void onStart(){
super.onStart();
//启动活动时调用GoogleAppClient连接
googleApiClient.connect();
}
@凌驾
受保护的void onStop(){
super.onStop();
//停止活动时断开GoogleAppClient
googleApiClient.disconnect();
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
super.onCreateOptions菜单(菜单);
getMenuInflater().充气(R.menu.option\u菜单,菜单);
返回true;
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
super.onOptionsItemSelected(项目);
if(item.getItemId()==R.id.main\u注销\u选项){
mAuth.signOut();
LoginManager.getInstance().logOut();
Gotologianctivity();
}
if(item.getItemId()==R.id.clear){
clearGeofence();
返回true;
}
if(item.getItemId()==R.id.geofance){
startGeofence();
返回true;
}
if(item.getItemId()==R.id.Refresh){
完成();
startActivity(getIntent());
返回true;
}
返回true;
}
私有void createGoogleApi()
{
d(标记“createGoogleApi()”);
if(googleApiClient==null){
GoogleapClient=新的GoogleapClient.Builder(此)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.addApi(LocationServices.API)
.build();
}
}
//检查访问位置的权限
私有布尔检查权限(){
Log.d(标记“checkPermission()”);
//如果还没有获得许可,请请求许可
return(ContextCompat.checkSelfPermission(这个,Manifest.permission.ACCESS\u FINE\u位置)
==PackageManager.PERMISSION(已授予的权限);
}
//请求许可
私有无效askPermission(){
Log.d(标记“askPermission()”);
ActivityCompat.requestPermissions(
这
新字符串[]{Manifest.permission.ACCESS\u FINE\u LOCATION},
请求许可
);
}
//验证用户对请求的权限的响应
@凌驾
public void onRequestPermissionsResult(int-requestCode,@NonNull-String[]permissions,@NonNull-int[]grantResults){
Log.d(标记“onRequestPermissionsResult()”);
super.onRequestPermissionsResult(requestC