I want to search for locations in a searchview and display the location on a map with a marker. When the marker is clicked, I want to show a infowindow with the location name, etc. I use OSMDROID and the OSMBONUSPACK.
The Problem:
The marker is shown as intented and its onClickListener does fire, but the infowindow is not shown if I call my searchLocationOnMap
from onQueryTextSubmit
. How to fix that?
Does not work(no info window shown if marker is clicked):
searchViewMap?.setOnQueryTextListener(object : androidx.appcompat.widget.SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
val location = searchViewMap?.query.toString()
if (location != null && location != "") {
try {
searchLocationOnMap("Moosach Bhf")
} catch (e: java.lang.Exception) {
Timber.d("Error while searching for location on map")
}
}
return true
}
override fun onQueryTextChange(newText: String?): Boolean {
return true
}
})
For some reason it is shown if I call searchLocationOnMap
from onViewCreated
or from a regular button.setOnClickListener{}
.
Does work(infowindow shown if marker is clicked):
btn.setOnClickListener { searchLocationOnMap("Moosach Bhf") }
This is searchLocationOnMap():
private fun searchLocationOnMap(keyword: String) = GlobalScope.launch(Dispatchers.Main) {
removeOldLocationsFromMap()
val locationAddress = withContext(Dispatchers.Default) { obtainAddressFromKeyword(keyword) }
if (locationAddress == null) {
Toast.makeText(context, "No address found for keyword $keyword", Toast.LENGTH_SHORT).show()
} else {
val marker = createMarkerFromAddress(locationAddress)
mPOIOverlayFolder.add(marker)
map.controller.animateTo(marker.position)
map.invalidate()
}
This is obtainAdressFromKeyword:
private fun obtainAddressFromKeyword(keyword: String): Address? {
val result = GeocoderNominatim("TestUserAgent").getFromLocationName(keyword, 1).firstOrNull()
Timber.d("result: $result")
return result
}
This is createMarkerFromAddress:
private fun createMarkerFromAddress(address: Address): Marker {
val poiMarker = Marker(map)
poiMarker.title = address.getAddressLine(0)
poiMarker.snippet = "Lat : ${address.latitude},\n Long ${address.longitude}"
poiMarker.position = GeoPoint(address.latitude, address.longitude)
poiMarker.icon = ContextCompat.getDrawable(applicationContext, R.drawable.poi_black)
poiMarker.infoWindow = MarkerInfoWindow(R.layout.marker_info_bubble, map)
poiMarker.setOnMarkerClickListener { marker, map -> onMarkerClick(marker) }
return poiMarker
}
This is onMarkerClick:
private fun onMarkerClick(marker: Marker) : Boolean {
marker.showInfoWindow()
marker.infoWindow.view.bringToFront()
Timber.d("Clicked Marker ${marker.title}, infowindowshown: ${marker.isInfoWindowShown}")
return true
Timber result (in both cases):
Clicked Marker Memminger Platz, infowindowshown: true
The map.parent view has to be invalidated.