Android projekt
java
public class Welcome extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleMap mMap;
private static final int MY_PERMISSION_REQUEST_CODE = 7000;
private static final int PLAY_SERVICE_RES_REQUEST = 7001;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private static int UPDATE_INTERVAL = 1000;
private static int FASTEST_INTERVAL = 1000;
private static int DISPLACEMENT = 10;
DatabaseReference drivers;
GeoFire geoFire;
Marker mCurrent;
Button btnPridatKontejner;
SupportMapFragment mapFragment;
private DatabaseReference mRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
mRef = FirebaseDatabase.getInstance().getReference();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
drivers = FirebaseDatabase.getInstance().getReference("Řidiči");
geoFire = new GeoFire(drivers);
setUpLocation();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case MY_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if (checkPlayServices()){
buildGoogleApiClient();
createLocationRequest();
displayLocation();
}
}
}
}
private void setUpLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED )
{
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION
}, MY_PERMISSION_REQUEST_CODE);
}
else{
if (checkPlayServices()){
buildGoogleApiClient();
createLocationRequest();
displayLocation();
}
}
}
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
private void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
mGoogleApiClient.connect();
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS){
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICE_RES_REQUEST).show();
else{
Toast.makeText(this, "Toto zařízení není podporováno", Toast.LENGTH_SHORT).show();
finish();
}
return false;
}
return true;
}
private void stopLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED )
{
return;
}
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED )
{
return;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null)
{
final double latitude = mLastLocation.getLatitude();
final double longitude = mLastLocation.getLongitude();
geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() {
@Override
public void onComplete(String key, DatabaseError error) {
if (mCurrent != null)
mCurrent.remove();
mCurrent = mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.car)).position(new LatLng(latitude, longitude)).title("Vy"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude),15.0f));
rotateMarker(mCurrent, -360, mMap);
}
});
btnPridatKontejner = (Button)findViewById(R.id.btn_pridat_kontejner);
btnPridatKontejner.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final AlertDialog.Builder dialog = new AlertDialog.Builder(Welcome.this);
dialog.setTitle("Přidat kontejner");
dialog.setMessage("Prosím, zadejte typ kontejneru pro přidání");
LayoutInflater inflater = LayoutInflater.from(Welcome.this);
View info_layout = inflater.inflate(R.layout.layout_info_map, null);
final MaterialEditText edtTypKontejneru = info_layout.findViewById(R.id.edtTypKontejneru);
dialog.setView(info_layout);
dialog.setPositiveButton("Přidat kontejner", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
final double latitude = mLastLocation.getLatitude();
final double longitude = mLastLocation.getLongitude();
MarkerOptions mp = new MarkerOptions();
long date = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("dd. MM. yyyy, k:mm");
String dateString = sdf.format(date);
mp.position(new LatLng(latitude, longitude));
mp.title(edtTypKontejneru.getText().toString());
mp.snippet(dateString);
mMap.addMarker(mp);
DatabaseReference markerRef = FirebaseDatabase.getInstance().getReference("markers");
String key = markerRef.push().getKey();
markerRef.child(key).child("long").setValue(longitude);
markerRef.child(key).child("lat").setValue(latitude);
markerRef.child(key).child("title").setValue(mp.getTitle());
markerRef.child(key).child("snippet").setValue(mp.getSnippet());
DatabaseReference newPost = markerRef.push();
if (TextUtils.isEmpty(edtTypKontejneru.getText().toString())){
return;
}
}
});
dialog.setNegativeButton("Zavřít", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
dialog.show();
}
});}
else{
Log.d("ERROR", "Nemůžeme získat vaši pozici");
}
}
private void rotateMarker(final Marker mCurrent, final float i, GoogleMap mMap) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final float startRotation = mCurrent.getRotation();
final long duration = 1500;
final android.view.animation.Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
@Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float)elapsed/duration);
float rot = t*i+(1-t)*startRotation;
mCurrent.setRotation(-rot > 180?rot/2:rot);
if (t<1.0)
{
handler.postDelayed(this, 16);
}
}
});
}
private void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED )
{
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Disable Map Toolbar:
//map.getUiSettings().setMapToolbarEnabled(false);
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef
.child("markers");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
//Toast.makeText(L_Location_Activity.this,"for",Toast.LENGTH_LONG).show();
String latitude_Display = ds
.child("lat")
.getValue().toString();
String longitude_Display = ds
.child("long")
.getValue().toString();
String title_Display = ds
.child("title")
.getValue().toString();
String info_Display = ds
.child("snippet")
.getValue().toString();
String latLng = latitude_Display;
String latLng1 = longitude_Display;
String title = title_Display;
String info = info_Display;
double latitude = Double.parseDouble(latLng);
double longitude = Double.parseDouble(latLng1);
String titleInfo = title;
String infoInfo = info;
LatLng currentLocation = new LatLng( latitude, longitude );
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position( currentLocation );
mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title(titleInfo).snippet(infoInfo));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(eventListener);
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
DatabaseReference markerRef = FirebaseDatabase.getInstance().getReference("markers");
marker.getId();
return true;
}
});}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
displayLocation();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
displayLocation();
startLocationUpdates();
}
@Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
}
Neformátovaný
Přidáno: 11.9.2018
Expirace: Neuvedeno