mapFragment.getMapAsync { GoogleMap ->
gMap = GoogleMap
val sensor = "false"
val mode = "driving"
val routeList = ArrayList<LatLng>()
var distance : String? = null
gMap.setOnMarkerClickListener { marker ->
val title = marker.title
if (title.equals(resources.getString(R.string.your_location))){
Toast.makeText(requireContext(), resources.getString(R.string.your_location), Toast.LENGTH_SHORT).show()
} else {
try {
val originLatitude = latitude
val originalLongitude = longitude
val destinationLatitude = marker.position.latitude
val destinationLongitude = marker.position.longitude
val retrofitClient = RetrofitClient.apiInterface.getJson("$originLatitude,$originalLongitude",
"$destinationLatitude,$destinationLongitude",sensor, mode, "Api_KEY")
retrofitClient.enqueue(object : Callback<DirectionResults>{
override fun onResponse(
call: Call<DirectionResults>,
response: Response<DirectionResults>
) {
if (response.body()!!.routes.isNotEmpty()){
var decodeList = ArrayList<LatLng>()
val route = response.body()!!.routes[0]
if (route.legs.isNotEmpty()){
distance = route.legs[0].distance.text
val steps = route.legs[0].steps
var step : Steps
var polyLine : String
var location : com.example.parkingapp.model.marker.Location
for (element in steps){
step = element
location = step.start_location
routeList.add(LatLng(location.lat, location.lng))
polyLine = step.polyLine.points
decodeList = RouteDecode.decodePoly(polyLine)
routeList.addAll(decodeList)
location = step.end_location
routeList.add(LatLng(location.lat, location.lng))
}
}
}
if (routeList.size > 0){
val rectLine = PolylineOptions().width(6f).color(Color.RED)
for (i in 0 until routeList.size){
rectLine.add(routeList[i])
}
gMap.addPolyline(rectLine)
MarkerOptions().position(LatLng(destinationLatitude, destinationLongitude))
}
Toast.makeText(requireContext(), distance, Toast.LENGTH_LONG).show()
}
override fun onFailure(call: Call<DirectionResults>, t: Throwable) {
Toast.makeText(requireContext(), t.localizedMessage, Toast.LENGTH_LONG).show()
}
})
}catch (e : NullPointerException){
e.printStackTrace()
}
}
false
}
}
I have list of marker in my map. When I clicked any marker it draw a route between that marker with my current location. My problem is when I click another marker previous route polyline remains in map. I want to remove it. Note : Not to use GoogleMap.clear() because when GoogleMap get cleared list of marker also get cleared
Thanks in advance