Skip to content

Instantly share code, notes, and snippets.

@adrielAd
Created August 9, 2018 07:24
Show Gist options
  • Save adrielAd/5ef1603c9f0d4a0f42ae3cbf19c6abcc to your computer and use it in GitHub Desktop.
Save adrielAd/5ef1603c9f0d4a0f42ae3cbf19c6abcc to your computer and use it in GitHub Desktop.
around me with circle radius
package in.bazzme.fragments;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;
import android.widget.TextView;
import com.firebase.geofire.GeoFire;
import com.firebase.geofire.GeoLocation;
import com.firebase.geofire.GeoQuery;
import com.firebase.geofire.GeoQueryEventListener;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.places.ui.PlaceAutocomplete;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.maps.android.clustering.Cluster;
import com.google.maps.android.clustering.ClusterManager;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.List;
import in.bazzme.R;
import in.bazzme.activities.AddPropertyActivity;
import in.bazzme.activities.MyPropertiesActivity;
import in.bazzme.activities.PropertyDetailsActivity;
import in.bazzme.model.GooglePlaces;
import in.bazzme.model.Place;
import in.bazzme.model.Property;
import in.bazzme.utils.Constants;
import in.bazzme.utils.PermissionUtility;
import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
import static in.bazzme.utils.Constants.ADDRESS;
import static in.bazzme.utils.Constants.DESCRIPTION;
import static in.bazzme.utils.Constants.EMAIl;
import static in.bazzme.utils.Constants.FIREBASE_GEOFIRE_KEY;
import static in.bazzme.utils.Constants.FIREBASE_PROPERTIES_KEY;
import static in.bazzme.utils.Constants.IMAGES;
import static in.bazzme.utils.Constants.KILOMETER;
import static in.bazzme.utils.Constants.LAT;
import static in.bazzme.utils.Constants.LOCATION;
import static in.bazzme.utils.Constants.LON;
import static in.bazzme.utils.Constants.PLACE_AUTOCOMPLETE_REQUEST_CODE;
import static in.bazzme.utils.Constants.PLACE_PICKER_REQUEST;
import static in.bazzme.utils.Constants.SHOW_PHONE;
import static in.bazzme.utils.Constants.TITLE;
import static in.bazzme.utils.Constants.TYPE;
import static in.bazzme.utils.Constants.UID;
import static in.bazzme.utils.Constants.USER;
import static in.bazzme.utils.PermissionUtility.checkPermissionLocation;
public class AroundMeFragment extends BaseFragment implements OnMapReadyCallback, GoogleMap.OnInfoWindowClickListener, View.OnClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ClusterManager.OnClusterItemClickListener<Property>,ClusterManager.OnClusterClickListener<Property>,ClusterManager.OnClusterInfoWindowClickListener<Property>,ClusterManager.OnClusterItemInfoWindowClickListener<Property> {
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10 * 1000;
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
UPDATE_INTERVAL_IN_MILLISECONDS / 2;
public static final int REQUEST_CHECK_SETTINGS = 0x1;
public static String TAG = "AroundMeFragment";
public GoogleApiClient mGoogleApiClient;
protected LocationRequest mLocationRequest;
protected LocationSettingsRequest mLocationSettingsRequest;
protected Location mCurrentLocation;
protected Boolean mRequestingLocationUpdates = false;
Double lat = 0.0, lng = 0.0;
ArrayList<String> listPropertyKeys;
int iscommercialOrResident = -1;
String typeFiltering = "";
Marker centerMarker;
private Circle circle;
private GoogleMap mMap;
private Marker mMarker;
private float mapCameraZoom = 15;
private ArrayList<Marker> propertyMarkers = new ArrayList<>();
private ArrayList<Marker> placeMarkers = new ArrayList<>();
private ArrayList<MarkerOptions> placeMarkerOptions = new ArrayList<>();
private Context context;
private SeekBar seekBar;
LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
lat = location.getLatitude();
lng = location.getLongitude();
Log.i(TAG, "onLocationChanged: " + lat);
Log.i(TAG, "onLocationChanged: " + lng);
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
stopLocationUpdates(locationListener);
}
setMapCamera(new LatLng(lat, lng));
drawCircle(getCurrentRadius());
}
};
private TextView tvSeekBarValue;
private GeoFire geoFire;
private GeoQuery geoQuery;
private String[] types;
private boolean isPlacesSelected;
private ClusterManager<Property> mClusterManager;
public AroundMeFragment() {
// Required empty public constructor
}
public static AroundMeFragment newInstance() {
AroundMeFragment fragment = new AroundMeFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
/*MenuItem menuItemSelectPropertyType;
MenuItem menuItemResidential;
MenuItem menuItemCommercial;
MenuItem menuItemHospitals;
MenuItem menuItemShoppingMalls;
MenuItem menuItemRestaurants;*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_around_me, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
context = getActivity();
tvSeekBarValue = (TextView) view.findViewById(R.id.textViewSeekBarValue);
seekBar = (SeekBar) view.findViewById(R.id.seekBar);
seekBar.setProgress(getReadPref().getIntValueDefault1(KILOMETER));
tvSeekBarValue.setText((seekBar.getProgress() + 1) + " Km");
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
tvSeekBarValue.setText((progress + 1) + " Km");
drawCircle(getCurrentRadius());
setMapCamera(mMap.getCameraPosition().target);
getSavePref().saveInt(KILOMETER, progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
if(iscommercialOrResident != -1){
getPlaces(types);
}
}
});
view.findViewById(R.id.fab).setOnClickListener(this);
}
@Override
public void onCreateOptionsMenu(final Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_around_me, menu);
/*menuItemSelectPropertyType = menu.findItem(R.id.menu_item_select_property_type);
menuItemResidential = menu.findItem(R.id.action_residential);
menuItemCommercial = menu.findItem(R.id.action_commercial);
menuItemHospitals = menu.findItem(R.id.action_hospitals);
menuItemShoppingMalls = menu.findItem(R.id.action_shopping_mall);
menuItemRestaurants = menu.findItem(R.id.action_restaurant);*/
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_my_properties:
startActivity(new Intent(getActivity(), MyPropertiesActivity.class));
break;
case R.id.action_add_property:
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(getActivity()), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
break;
/*case R.id.action_residential:
menuItemSelectPropertyType.setTitle(getString(R.string.residential) + " ▼");
menuItemResidential.setChecked(true);
menuItemCommercial.setChecked(false);
menuItemHospitals.setChecked(false);
menuItemShoppingMalls.setChecked(false);
menuItemRestaurants.setChecked(false);
break;
case R.id.action_commercial:
menuItemSelectPropertyType.setTitle(getString(R.string.commercial) + " ▼");
menuItemResidential.setChecked(false);
menuItemCommercial.setChecked(true);
menuItemHospitals.setChecked(false);
menuItemShoppingMalls.setChecked(false);
menuItemRestaurants.setChecked(false);
break;
case R.id.action_hospitals:
menuItemSelectPropertyType.setTitle(getString(R.string.hospitals) + " ▼");
menuItemResidential.setChecked(false);
menuItemCommercial.setChecked(false);
menuItemHospitals.setChecked(true);
menuItemShoppingMalls.setChecked(false);
menuItemRestaurants.setChecked(false);
break;
case R.id.action_shopping_mall:
menuItemSelectPropertyType.setTitle(getString(R.string.shopping_malls) + " ▼");
menuItemResidential.setChecked(false);
menuItemCommercial.setChecked(false);
menuItemHospitals.setChecked(false);
menuItemShoppingMalls.setChecked(true);
menuItemRestaurants.setChecked(false);
break;
case R.id.action_restaurant:
menuItemSelectPropertyType.setTitle(getString(R.string.restaurants) + " ▼");
menuItemResidential.setChecked(false);
menuItemCommercial.setChecked(false);
menuItemHospitals.setChecked(false);
menuItemShoppingMalls.setChecked(false);
menuItemRestaurants.setChecked(true);
break;*/
}
return false;
}
public void filterPlaces(int option){
typeFiltering = getResources().getStringArray(R.array.spinner_list_item_array)[option];
switch (option){
case 0:
iscommercialOrResident = -1;
if(mMap!= null)
mMap.clear();
break;
case 1:
isPlacesSelected = false;
iscommercialOrResident = 1;
showProperties();
break;
case 2:
isPlacesSelected = false;
iscommercialOrResident = 2;
showProperties();
break;
case 4:
isPlacesSelected = true;
iscommercialOrResident = 0;
types = new String[]{"hospital"};
getPlaces(types);
break;
case 5:
iscommercialOrResident = 0;
isPlacesSelected = true;
types = new String[]{"mall", "market"};
getPlaces(types);
break;
case 3:
iscommercialOrResident = 0;
isPlacesSelected = true;
types = new String[]{"restaurant", "hotel"};
getPlaces(types);
break;
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
checkCurrentLocation();
}
@SuppressLint("MissingPermission")
public void checkCurrentLocation(){
if(checkPermissionLocation(getActivity())) {
//mMap.setOnInfoWindowClickListener(this);
drawCircle(getCurrentRadius());
mMap.setPadding(3, 140, 3, 3);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
mMap.setMyLocationEnabled(true);
mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition cameraPosition) {
drawCircle(getCurrentRadius());
evaluateMarkers();
}
});
mapCameraZoom = 15;
// setMapCamera(mMap.getCameraPosition().target);
if (mCurrentLocation != null) {
setMapCamera(new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()));
drawCircle(getCurrentRadius());
}
mClusterManager = new ClusterManager<>(getActivity(), mMap);
mMap.setOnCameraIdleListener(mClusterManager);
mMap.setOnInfoWindowClickListener(mClusterManager);
mMap.setOnMarkerClickListener(mClusterManager);
mClusterManager.setOnClusterClickListener(this);
mClusterManager.setOnClusterItemClickListener(this);
mClusterManager.setOnClusterInfoWindowClickListener(this);
mClusterManager.setOnClusterItemInfoWindowClickListener(this);
mMap.setInfoWindowAdapter(mClusterManager.getMarkerManager());
/*mClusterManager.setOnClusterInfoWindowClickListener(new ClusterManager.OnClusterInfoWindowClickListener<Property>() {
@Override
public void onClusterInfoWindowClick(Cluster<Property> cluster) {
context.startActivity(new Intent(context, PropertyDetailsActivity.class).putExtra("property", cluster.));
}
});*/
setCustomInfoWindow();
if (checkPlayServices()) {
try {
buildGoogleApiClient();
createLocationRequest();
buildLocationSettingsRequest();
mGoogleApiClient.connect();
} catch (Exception e) {
Log.e(TAG, "Exception : " + e.getMessage());
}
}
if(iscommercialOrResident != -1){
getPlaces(types);
}
}
}
public boolean checkPlayServices() {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(context);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(getString(R.string.updatePlayServicesMessage, getString(R.string.app_name)))
.setTitle(getString(R.string.updatePlayServices));
builder.setPositiveButton(getString(R.string.update), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
final String appPackageName = "com.google.android.gms";
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
dialog.dismiss();
}
});
builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.setCancelable(false);
dialog.show();
} else {
Log.i(TAG, "This device is not supported.");
getActivity().finish();
}
return false;
}
return true;
}
protected synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
protected void buildLocationSettingsRequest() {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
mLocationSettingsRequest = builder.build();
}
protected void checkLocationSettings() {
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(
mGoogleApiClient,
mLocationSettingsRequest
);
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
Log.i(TAG, "All location settings are satisfied.");
startLocationUpdates(locationListener);
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
Log.i(TAG, "Location settings are not satisfied. Show the agent a dialog to" +
"upgrade location settings ");
try {
// Show the dialog by calling startResolutionForResult(), and check the result
// in onActivityResult().
status.startResolutionForResult(getActivity(), REQUEST_CHECK_SETTINGS);
} catch (Exception e) {
Log.i(TAG, "PendingIntent unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog " +
"not created.");
break;
}
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_CHECK_SETTINGS) {
if(resultCode == Activity.RESULT_OK) {
if (mGoogleApiClient.isConnected()) {
startLocationUpdates(locationListener);
} else {
mGoogleApiClient.connect();
}
}
} else if(requestCode == PLACE_PICKER_REQUEST) {
if(resultCode == Activity.RESULT_OK) {
com.google.android.gms.location.places.Place place = PlacePicker.getPlace(getActivity(), data);
String placeName = String.format("Place: %s", place.getName());
Log.i(TAG, "onActivityResult: " + placeName);
if(place != null){
AddPropertyActivity.place = place;
startActivity(new Intent(getActivity(), AddPropertyActivity.class));
}
}
}else if(requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE){
if(resultCode == Activity.RESULT_OK){
com.google.android.gms.location.places.Place place = PlaceAutocomplete.getPlace(getActivity(), data);
/*CameraPosition cameraPosition = new CameraPosition.Builder()
.target(place.getLatLng())
.zoom(15)
.bearing(0)
.tilt(45)
.build();*/
setMapCamera(place.getLatLng());
getPlaces(types);
//mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
}
@SuppressLint("MissingPermission")
protected void startLocationUpdates(LocationListener locationListener) {
try {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient,
mLocationRequest,
locationListener
).setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
mRequestingLocationUpdates = true;
}
});
} catch (Exception e) {
Log.e(TAG, "StartLocation Exception --- > " + e.getMessage());
}
}
protected void stopLocationUpdates(LocationListener locationListener) {
try {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient,
locationListener
).setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
mRequestingLocationUpdates = false;
}
});
} catch (Exception e) {
}
}
public void searchLocation() {
try {
Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY).build(getActivity());
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (Exception e) {
e.printStackTrace();
}
}
private void drawCircle(double radius) {
try {
if (circle != null) {
circle.remove();
}
if(centerMarker!=null)
centerMarker.remove();
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.aroundme_orange);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(mMap.getCameraPosition().target);
markerOptions.draggable(true);
centerMarker = mMap.addMarker(markerOptions);
centerMarker.setIcon(bitmapDescriptor);
circle = mMap.addCircle(new CircleOptions()
.center(mMap.getCameraPosition().target)
.radius(radius)
.strokeWidth(4)
.strokeColor(ContextCompat.getColor(context, R.color.colorPrimary))
.fillColor(ContextCompat.getColor(context, R.color.colorCircle)));
double radius2 = circle.getRadius();
double scale = radius2 / 500;
mapCameraZoom = (int) (16 - Math.log(scale) / Math.log(2));
}catch (Exception e){
e.printStackTrace();
}
}
private void updateMarkerWithCircle(LatLng position) {
circle.setCenter(position);
mMarker.setPosition(position);
}
private void drawMarkerWithCircle(LatLng position){
double radiusInMeters = 100.0;
int strokeColor = 0xffff0000; //red outline
int shadeColor = 0x44ff0000; //opaque red fill
CircleOptions circleOptions = new CircleOptions().center(position).radius(radiusInMeters).fillColor(shadeColor).strokeColor(strokeColor).strokeWidth(8);
circle = mMap.addCircle(circleOptions);
MarkerOptions markerOptions = new MarkerOptions().position(position);
mMarker = mMap.addMarker(markerOptions);
}
private void setMapCamera(LatLng latLng) {
try {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, mapCameraZoom));
} catch (Exception e) {
e.printStackTrace();
}
}
private int getCurrentRadius() {
return (seekBar.getProgress() + 1) * 1000;
}
private void evaluateMarkers() {
final double lat = mMap.getCameraPosition().target.latitude, lng = mMap.getCameraPosition().target.longitude;
{
if (isPlacesSelected) {
for (Marker placeMarker : placeMarkers) {
if (!isUnderRadius(placeMarker, lat, lng)) {
placeMarker.setVisible(false);
} else {
placeMarker.setVisible(true);
}
}
} else {
for (Marker propertyMarker : propertyMarkers) {
if (!isUnderRadius(propertyMarker, lat, lng)) {
propertyMarker.setVisible(false);
} else
propertyMarker.setVisible(true);
}
}
}
}
private void setCustomInfoWindow() {
/*mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
// Use default InfoWindow frame
@Override
public View getInfoWindow(Marker marker) {
return null;
}
// Defines the contents of the InfoWindow
@Override
public View getInfoContents(Marker marker) {
View view = getActivity().getLayoutInflater().inflate(R.layout.adapter_property_info_window, null);
((TextView) view.findViewById(R.id.textViewTitle)).setText(marker.getTitle());
((TextView) view.findViewById(R.id.textViewSubtitle)).setText(marker.getSnippet());
((TextView) view.findViewById(R.id.textViewContent)).setVisibility(View.GONE);
final LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.linearLayout);
final int desiredWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 240, getActivity().getResources().getDisplayMetrics());
linearLayout.post(new Runnable() {
@Override
public void run() {
if (linearLayout.getWidth() > desiredWidth) {
linearLayout.setLayoutParams(new LinearLayout.LayoutParams(desiredWidth,
LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout.requestLayout();
}
}
});
return view;
}
});*/
}
private boolean isUnderRadius(Marker placeMarker, double lat, double lng) {
try {
if (((int) distanceBetweenLatLng(placeMarker.getPosition().latitude, placeMarker.getPosition().longitude,
lat, lng)) > getCurrentRadius()) {
return false;
} else
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
@Override
public void onInfoWindowClick(Marker marker) {
context.startActivity(new Intent(context, PropertyDetailsActivity.class).putExtra("property", (Property)marker.getTag()));
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case PermissionUtility.MY_PERMISSIONS_REQUEST_ACCESS_LOCATION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
checkCurrentLocation();
} else {
askPermissionSettings("You need to give permission to access Location to this app");
//showToast(getString(R.string.locationPermissionDenied));
}
break;
}
}
public void askPermissionSettings(String message){
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(getActivity());
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permissions needed");
alertBuilder.setCancelable(false);
alertBuilder.setMessage(message);
alertBuilder.setPositiveButton("Open Settings", new DialogInterface.OnClickListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | FLAG_ACTIVITY_CLEAR_TOP);
Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, 9001);
}
});
alertBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.fab:
checkCurrentLocation();
break;
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
if (mCurrentLocation == null) {
checkLocationSettings();
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
private void showProperties() {
try {
mMap.clear();
drawCircle(getCurrentRadius());
listenerOfProperty();
}catch (Exception e){
e.printStackTrace();
}
}
public void listenerOfProperty(){
listPropertyKeys = new ArrayList<>();
GeoLocation INITIAL_CENTER = new GeoLocation(mMap.getCameraPosition().target.latitude, mMap.getCameraPosition().target.longitude);
geoFire = new GeoFire(getmDatabase().child(FIREBASE_GEOFIRE_KEY));
geoQuery = geoFire.queryAtLocation(INITIAL_CENTER, seekBar.getProgress()+1);
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
@Override
public void onKeyEntered(String key, GeoLocation location) {
Log.i(TAG, "onKeyEntered: " + key.toString());
listPropertyKeys.add(key.toString());
}
@Override
public void onKeyExited(String key) {
// System.out.println("////method getasdfsafsadfasf called===" );
}
@Override
public void onKeyMoved(String key, GeoLocation location) {
}
@Override
public void onGeoQueryReady() {
if (listPropertyKeys != null && !listPropertyKeys.isEmpty()) {
try {
mMap.clear();
} catch (Exception e) {
e.printStackTrace();
}
drawCircle(getCurrentRadius());
showProgressDialog(getString(R.string.please_wait));
if(mClusterManager != null)
mClusterManager.clearItems();
for(String key : listPropertyKeys) {
Query queryRef = getmDatabase().child(FIREBASE_PROPERTIES_KEY).orderByChild(UID).equalTo(key);
queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
for (DataSnapshot child : dataSnapshot.getChildren()) {
if ((iscommercialOrResident == 1 && child.child(TYPE).getValue().toString().equals(Constants.PROPERTY_TYPE.residential.name()))
|| (iscommercialOrResident == 2 && child.child(TYPE).getValue().toString().equals(Constants.PROPERTY_TYPE.commercial.name()))) {
//Property property = child.getValue(Property.class);
Property property = new Property(child.child(UID).getValue().toString(),
child.child(ADDRESS).getValue().toString(),
child.child(DESCRIPTION).getValue().toString(),
(boolean)child.child(SHOW_PHONE).getValue(),
child.child(TITLE).getValue().toString(),
child.child(TYPE).getValue().toString(),
new LatLng(Double.parseDouble(child.child(LOCATION).child(LAT).getValue().toString()),
Double.parseDouble(child.child(LOCATION).child(LON).getValue().toString())),
child.child(USER).getValue().toString(),
"");
if(child.hasChild(EMAIl)){
property.setEmail((String) child.child(EMAIl).getValue());
}
if(child.hasChild(IMAGES)){
property.setImages((ArrayList<String>) child.child(IMAGES).getValue());
}
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(property.getLocation());
markerOptions.title(property.getTitle());
markerOptions.snippet(property.getType());
placeMarkerOptions.add(markerOptions);
//Marker marker = mMap.addMarker(markerOptions);
//marker.setTag(property);
//marker.setIcon(bitmapDescriptor);
//placeMarkers.add(marker);
if(mClusterManager != null)
mClusterManager.addItem(property);
}
}
if(mClusterManager != null)
mClusterManager.cluster();
zoomCameraToMarkers();
hideProgressDialog();
} catch (Exception e) {
e.printStackTrace();
hideProgressDialog();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
@Override
public void onGeoQueryError(DatabaseError error) {
}
});
}
public void zoomCameraToMarkers(){
try {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Marker marker : mClusterManager.getMarkerCollection().getMarkers()) {
builder.include(marker.getPosition());
}
LatLngBounds bounds = builder.build();
int padding = 10;
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
mMap.animateCamera(cu);
}catch (Exception e){
e.printStackTrace();
}
}
private void getPlaces(String[] types) {
if (!isPlacesSelected) {
showProperties();
return;
}
if(types == null)
return;
try {
mMap.clear();
} catch (Exception e) {
e.printStackTrace();
}
if(mClusterManager != null)
mClusterManager.clearItems();
drawCircle(getCurrentRadius());
showProgressDialog(getString(R.string.please_wait));
for (String type : types) {
try {
StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=" + mMap.getCameraPosition().target.latitude + "," + mMap.getCameraPosition().target.longitude);
googlePlacesUrl.append("&radius=" + getCurrentRadius());
googlePlacesUrl.append("&keyword=" + type);
googlePlacesUrl.append("&key=" + getString(R.string.google_map_api_key));
Log.i(TAG, "getPlaces: " + googlePlacesUrl);
GooglePlaces.getPlaces(googlePlacesUrl.toString(), new GooglePlaces.OnComplete() {
@Override
public void onResult(List<Place> places) {
if (places != null)
for (Place place : places) {
String type = "";
if(place.type != null) {
for (int i = 0; i < place.type.length(); i++)
try {
type = new StringBuilder().append(place.type.getString(i)).toString();
} catch (JSONException e) {
e.printStackTrace();
}
if(type.length()>0)
type = type.substring(0, type.length()-1);
}
Property property = new Property(place.id, place.vicinity, "", false, place.name, typeFiltering,
new LatLng(Double.parseDouble(place.latitude),
Double.parseDouble(place.longitude)),
"", place.rating);
property.setImages(place.images);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(property.getLocation());
markerOptions.title(property.getTitle());
markerOptions.snippet(property.getType());
placeMarkerOptions.add(markerOptions);
//Marker marker = mMap.addMarker(markerOptions);
//marker.setTag(property);
//marker.setIcon(bitmapDescriptor);
//placeMarkers.add(marker);
if(mClusterManager != null)
mClusterManager.addItem(property);
}
if(mClusterManager != null)
mClusterManager.cluster();
zoomCameraToMarkers();
hideProgressDialog();
}
});
} catch (Exception e) {
e.printStackTrace();
hideProgressDialog();
showToast(getString(R.string.unable_to_find_data));
}
}
}
@Override
public boolean onClusterItemClick(Property item) {
return false;
}
@Override
public boolean onClusterClick(Cluster<Property> cluster) {
return false;
}
@Override
public void onClusterInfoWindowClick(Cluster<Property> cluster) {
}
@Override
public void onClusterItemInfoWindowClick(Property item) {
context.startActivity(new Intent(context, PropertyDetailsActivity.class).putExtra("property", item));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment