Skip to content

Instantly share code, notes, and snippets.

@Simarjot-sk
Created July 24, 2021 05:02
Show Gist options
  • Save Simarjot-sk/71c2b5044a6ba6442302ed7a3b2304e9 to your computer and use it in GitHub Desktop.
Save Simarjot-sk/71c2b5044a6ba6442302ed7a3b2304e9 to your computer and use it in GitHub Desktop.
class MapViewFragment : Fragment(), OnMapReadyCallback,
ClusterManager.OnClusterClickListener<MyItemClustering> {
private var mCtx: Context? = null
private val TAG: String? = MapViewFragment::class.java.simpleName
var mapFragment: SupportMapFragment? = null
private var currentLatitude: Double? = 0.0
private var currentLongitude: Double? = 0.0
private var mMap: GoogleMap? = null
private var arrPostCardsList: ArrayList<PostCardsListData?>? = null
private val boundStack = Stack<LatLngBounds>()
private var lastBound: LatLngBounds? = null
private var adultsSelected: Int? = 0
private var kidsSelected: Int? = 0
private var petsSelected: Int? = 0
private var positionData: String? = ""
private var arrCities: ArrayList<City?>? = null
private var arrCitiesSelected: ArrayList<City?>? = null
var arrInterest: ArrayList<Item?>? = null
var arrInterestHosts: ArrayList<Int?>? = null
private var response: JsonObject? = null
private var lastClickedMarker:Marker? = null
/** google clustering */
private var mClusterManager: ClusterManager<MyItemClustering>? = null
override fun onAttach(context: Context) {
super.onAttach(context)
try {
this.mCtx = context
} catch (e: Exception) {
Log.d(TAG, "context exception : $e")
}
}
companion object {
var mapFragment: SupportMapFragment? = null
var cityNameTitle: String? = ""
@JvmStatic
fun getInstance(
arrPostCardsListData: ArrayList<PostCardsListData?>?,
positionTitle: String?,
arrInterestIdsHosts: ArrayList<Int?>?,
) = MapViewFragment().apply {
arguments = Bundle().apply {
arrPostCardsList = ArrayList()
arrPostCardsList = arrPostCardsListData
arrInterestHosts = arrInterestIdsHosts
positionData = positionTitle
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val rootView = inflater.inflate(R.layout.fragment_map_view, container, false)
initMap(rootView)
setFilterExpandableDetails(rootView)
setListeners(rootView)
setFontStyles(rootView)
return rootView
}
private fun setFilterExpandableDetails(rootView: View) {
var textMultiplesSet: String = ""
arrInterest = ArrayList()
var textSet: String = ""
(context as DashBoardActivity).appPreferences?.let {
Log.v("DashBoardActivity MapView - :", " " + it.getFilterWantToExplore(context))
if (it.getFilterWantToExplore(context) == true) {
rootView.partialFilterExpandableData.textviewBookingTime.text =
getString(R.string.now)
} else {
rootView.partialFilterExpandableData.textviewBookingTime.text =
getString(R.string.later)
}
}
petsSelected = (context as DashBoardActivity).appPreferences?.getFilterPetCount(context)
adultsSelected = (context as DashBoardActivity).appPreferences?.getFilterAdultCount(context)
kidsSelected = (context as DashBoardActivity).appPreferences?.getFilterKidCount(context)
var total: Int? =
petsSelected?.let { adultsSelected?.let { kidsSelected?.plus(it) }?.plus(it) }
arrCities = ArrayList()
arrCities = (context?.applicationContext as AppController).getCities() ?: ArrayList()
Log.v("DashBoardActivity arrCities - :", " " + arrCities)
var arrCitiesMenu: ArrayList<City?>? = null
arrCitiesSelected = ArrayList()
arrCitiesMenu = (context?.applicationContext as AppController).getCities() ?: ArrayList()
Log.v("DashBoardActivity arrCitiesMenu - :", " " + arrCitiesMenu)
arrCitiesMenu?.forEachIndexed { index, city ->
Log.v("_____", "" + city?.name)
Log.v("_____", "" + city?.isSelection)
if (city?.isSelection == true) {
arrCitiesSelected?.add(city)
}
}
arrCitiesSelected?.forEachIndexed { index, city ->
Log.v("_____", "" + city?.name)
Log.v("_____", "" + city?.isSelection)
if (arrCitiesSelected?.size!! > 2) {
if (index == 0) {
textMultiplesSet = arrCitiesSelected?.get(index)?.name.toString()
} else if (index == 1) {
textMultiplesSet =
textMultiplesSet + "," + arrCitiesSelected?.get(index)?.name.toString()
} else {
textMultiplesSet =
textMultiplesSet + " & " + arrCitiesSelected?.get(index)?.name.toString()
}
}
if (arrCitiesSelected?.size!! == 2) {
if (index == 0) {
textMultiplesSet = arrCitiesSelected?.get(index)?.name.toString()
} else {
textMultiplesSet =
textMultiplesSet + " & " + arrCitiesSelected?.get(index)?.name.toString()
}
}
if (arrCitiesSelected?.size!! == 1) {
textMultiplesSet = arrCitiesSelected?.get(index)?.name.toString()
}
}
textSet = textMultiplesSet.toString()
rootView.partialFilterExpandableData.textviewDestination.text = textSet
rootView.textviewToolbarTitle.text = textSet
rootView.partialFilterExpandableData.recyclerViewPostInterest
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Interest~~~~~~~~~~~~~~~~~~~~~~~~~*/
val selected: String? =
(context as DashBoardActivity).appPreferences?.getFilterInterest(context)
val json: JsonObject? = JsonParser().parse(selected).asJsonObject
val asd: HashMap<String?, ArrayList<Int?>?>? =
Gson().fromJson(json, object : TypeToken<HashMap<String?, ArrayList<Int?>?>?>() {}.type)
var isEnable: Boolean? = false
val interestsarray: ArrayList<Int?>? = ArrayList()
var mapSectionItems: LinkedHashMap<String?, ArrayList<Item?>?>? = null
asd?.entries?.forEach { mutableEntry: MutableMap.MutableEntry<String?, ArrayList<Int?>?> ->
val key = mutableEntry.key
val value = mutableEntry.value
interestsarray?.addAll(value ?: ArrayList())
if (isEnable == false && value?.isNotEmpty() == true) isEnable = true
}
mapSectionItems = LinkedHashMap(getSubInterestMap(context, asd))
arrInterest?.addAll(getItemsByIds(interestsarray))
val interestVisitAdapter = homeInterestPostVisitAdapter(
context, arrInterest, "filter",
object : homeInterestPostVisitAdapter.OnconInterestClick {
override fun iconInterestClick(position: Int) {
openFilter("what")//what
}
}
)
/*_________________________________________________________________________________*/
val layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
rootView.recyclerViewPostInterest.layoutManager = layoutManager
rootView.recyclerViewPostInterest.adapter = interestVisitAdapter
rootView.recyclerViewPostInterest.setHasFixedSize(true)
rootView.relativelayoutTravellerDetail.setOnClickListener {
openFilter("when")//when
}
rootView.relativelayoutDestination.setOnClickListener {
openFilter("where")//where
}
rootView.textviewTotalPersons.setText(total.toString())
}
private fun openFilter(openType: String) {
(context as DashBoardActivity).appPreferences?.setExploreViewId(
context,
callDashBoardActions.map,
openType
)
startActivity(FilterActivity.getInstance(context))
}
private fun initMap(rootView: View) {
val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
}
private fun setListeners(itemView: View) {
itemView.imageviewBackMapView.setOnClickListener {
getFragmentManager()?.popBackStack()
}
itemView.imagebuttonOptions.setOnClickListener {
getFragmentManager()?.popBackStack()
}
itemView.imagebuttonFilters.setOnClickListener {
if (itemView.partialFilterExpandableData.visibility == View.VISIBLE) {
itemView.partialFilterExpandableData.visibility = View.GONE
} else {
itemView.partialFilterExpandableData.visibility = View.VISIBLE
}
}
itemView.recenter_button.setOnClickListener {
if (boundStack.empty()) {
it.visibility = View.GONE
} else {
//never poping the main bound
if (boundStack.size == 1) {
lastBound = boundStack.peek()
it.visibility = View.GONE
}
val bound = boundStack.pop()
mMap?.animateCamera(CameraUpdateFactory.newLatLngBounds(bound, 50.dp))
}
}
}
override fun onLowMemory() {
super.onLowMemory()
map?.onLowMemory()
}
override fun onDestroy() {
super.onDestroy()
map?.onDestroy()
}
private fun setFontStyles(rootView: View) {
rootView.textviewToolbarTitle.typeface = Typeface.createFromAsset(
(context as DashBoardActivity).assets,
"fonts/AvenirLTStd-Black.otf"
)
}
@SuppressLint("MissingPermission")
override fun onMapReady(googleMap: GoogleMap?) {
mMap = googleMap
mMap?.uiSettings?.apply {
isCompassEnabled = false
isZoomControlsEnabled = false
isZoomGesturesEnabled = true
isMyLocationButtonEnabled = false
isTiltGesturesEnabled = true
}
mClusterManager = ClusterManager(requireContext(), googleMap)
mMap?.apply {
isMyLocationEnabled = true
setOnMarkerClickListener(mClusterManager)
setOnCameraIdleListener(mClusterManager)
setOnMapClickListener {
lastClickedMarker?.alpha = 1f
}
}
mClusterManager?.apply {
renderer = CustomMapClusterRenderer(requireActivity(), mMap, mClusterManager)
setOnClusterClickListener(this@MapViewFragment)
setOnClusterItemClickListener { myItemClustering ->
val clickedMarker = markerCollection.markers.find { marker ->
myItemClustering.title == marker.title
}
lastClickedMarker?.alpha = 1f
clickedMarker?.alpha = 0f
lastClickedMarker = clickedMarker
clickedMarker?.setInfoWindowAnchor(.5f, .5f)
false
}
}
mMap?.setOnInfoWindowClickListener { marker ->
print("marker : -" + marker?.position?.latitude)
response =
((context?.applicationContext as AppController).getresponseData() ?: JsonObject())
val result = response?.get(ApiParams.result)?.asJsonArray
for (i in 0 until result?.size()!!) {
val resultData = result.get(i).asJsonObject
if (resultData.has(ApiParams.latitude)) {
var latitude = resultData.get(ApiParams.latitude).asString
if (latitude.equals(marker?.position?.latitude.toString())) {
val resultData = result.get(i).asJsonObject
val transaction = fragmentManager?.beginTransaction()
transaction?.replace(
R.id.fragmentMap, ExploreDetailFragment.getInstance(
resultData.toString(),
callDashBoardActions.favorite.toString(),
"refreshPage"
)
)
transaction?.addToBackStack(null)
transaction?.commit()
}
}
}
}
setMarker()
}
private fun setMarker() {
val boundBuilder = LatLngBounds.Builder()
val gpsTracker = GPSTracker(context as DashBoardActivity)
currentLatitude = gpsTracker.latitude
currentLongitude = gpsTracker.longitude
arrPostCardsList?.forEach { experience ->
experience ?: return@forEach
val googleMarkerData =
GoogleMarkerData(
experience.experienceid ?: "",
experience.placeTitle ?: "",
experience.thumbnail_url ?: "",
experience.latitude?.toDouble() ?: 0.0,
experience.longitude?.toDouble() ?: 0.0,
experience.arrInterestHosts,
(experience.duration_in_hours ?: "0") + "H",
getFormattedPrice(experience.price)
)
val myItemClustering = MyItemClustering(
experience.latitude?.toDouble() ?: 0.0,
experience.longitude?.toDouble() ?: 0.0,
experience.experienceid,
experience.placeTitle,
experience.thumbnail_url,
Gson().toJson(googleMarkerData)
)
mClusterManager?.addItem(myItemClustering)
boundBuilder.include(myItemClustering.position)
}
val bounds = boundBuilder.build()
lastBound = bounds
mClusterManager?.cluster()
val width = resources.displayMetrics.widthPixels
val height = resources.displayMetrics.heightPixels
val padding =
(width * 0.10).toInt() // offset from edges of the map 10% of screen
val cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding)
mMap!!.animateCamera(cu)
val infoWindowAdapter = ClusterInfoWindowAdapter(requireContext())
mMap?.setInfoWindowAdapter(infoWindowAdapter)
}
override fun onClusterClick(cluster: Cluster<MyItemClustering>): Boolean {
recenter_button.visibility = View.VISIBLE
val boundBuilder = LatLngBounds.Builder()
cluster.items.forEach {
boundBuilder.include(it.position)
}
val currentBound = boundBuilder.build()
boundStack.push(lastBound)
lastBound = currentBound
val cameraUpdate = CameraUpdateFactory.newLatLngBounds(
currentBound,
50.dp
)
mMap?.animateCamera(cameraUpdate)
return true
}
private inner class CustomMapClusterRenderer(
private val context: Activity,
private val map: GoogleMap?,
clusterManager: ClusterManager<MyItemClustering>?
) : DefaultClusterRenderer<MyItemClustering>(context, map, clusterManager) {
override fun onBeforeClusterItemRendered(
item: MyItemClustering,
markerOptions: MarkerOptions
) {
val image = item.imgUrl
image?.let {
val bitmap = BitmapDescriptorFactory.fromBitmap(
createCustomMarker(
it
)
)
markerOptions.icon(bitmap)
}
}
override fun shouldRenderAsCluster(cluster: Cluster<MyItemClustering>?): Boolean {
val clusterSize = cluster?.size ?: 0
var canZoomMore = false
context.runOnUiThread {
val currentZoom = map?.cameraPosition?.zoom
val maxZoom = map?.maxZoomLevel
canZoomMore = currentZoom != null && maxZoom != null && currentZoom < maxZoom
}
return clusterSize >= 2 && canZoomMore
}
}
/** custom marker with bg circle */
private fun createCustomMarker(resource: String): Bitmap {
val markerLayout: View = layoutInflater.inflate(R.layout.partial_custom_marker, null)
val markerImage: CircleImageView =
markerLayout.findViewById<View>(R.id.user_dp) as CircleImageView
Picasso.get().load(resource).into(markerImage)
markerLayout.measure(
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
)
markerLayout.layout(0, 0, markerLayout.measuredWidth, markerLayout.measuredHeight)
val bitmap = Bitmap.createBitmap(
markerLayout.measuredWidth,
markerLayout.measuredHeight,
Bitmap.Config.ARGB_8888
)
val canvas = Canvas(bitmap)
markerLayout.draw(canvas)
return bitmap
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment