Skip to content

Instantly share code, notes, and snippets.

@AlaaZarifa
Last active April 7, 2022 10:40
Show Gist options
  • Save AlaaZarifa/ee5d97111aaf710ac10b35df68dc1f3e to your computer and use it in GitHub Desktop.
Save AlaaZarifa/ee5d97111aaf710ac10b35df68dc1f3e to your computer and use it in GitHub Desktop.
val placeHolderImage = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/de/Google_Map_Marker.svg/1024px-Google_Map_Marker.svg.png"
private var isMapLoaded = false
private var offers: MutableList<Product> = mutableListOf()
private var markers: MutableList<Marker> = mutableListOf()
// Your API success response
Status.SUCCESS -> {
it.data?.apply {
offers = products as MutableList<Product>
// Check if map is isInitialized & loaded
if (this@MapNavFragment::mMap.isInitialized && isMapLoaded) {
// Clear previous markers
markers.forEach { marker -> marker.remove() }
markers.clear()
// Set the new markers
setupOffersMarkers(products)
}
}
}
// Create custom marker per object
private fun setupOffersMarkers(offers: List<Product>) {
val offersList = offers.filter { it.lat != null }
offersList.forEach {
val url = if (it.images.isNullOrEmpty().not())
it.images.first().image else placeHolderImage
val bitmap = getBitmapFromView(it.title, url)
val icon = BitmapDescriptorFactory.fromBitmap(bitmap)
val marker: Marker = mMap.addMarker(
MarkerOptions()
.position(LatLng(it.lat!!, it.lan!!))
.icon(icon)
)!!
marker.tag = it.id
markers.add(marker)
}
areMarkersShown = true
}
private fun getBitmapFromView(title: String, image: String): Bitmap? {
val inflater = LayoutInflater.from(requireActivity())
// Use your custom layout
val view: View = inflater.inflate(R.layout.layout_marker, null, false)
val spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
view.measure(spec, spec);
view.layout(0, 0, view.measuredWidth, view.measuredHeight);
val bitmap = Bitmap.createBitmap(
view.measuredWidth,
view.measuredHeight,
Bitmap.Config.ARGB_8888
)
val canvas = Canvas(bitmap)
// Handle your UI here as you like
val titleTxv: TextView = view.findViewById(R.id.marker_title)
val iconImg: RoundedImageView = view.findViewById(R.id.marker_image)
titleTxv.text = title
iconImg.setPhotoSimple(image, requireContext())
view.draw(canvas)
return bitmap
}
// Glide extention function
fun ImageView.setPhotoSimple(url: String, context: Context) {
Glide.with(context)
.load(url)
.fitCenter()
.transition(DrawableTransitionOptions.withCrossFade())
.into(this)
}
// Add this line inside onMapReady
mMap.setOnMapLoadedCallback { isMapLoaded = true }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment