Skip to content

Instantly share code, notes, and snippets.

@serhatleventyavas
Created December 21, 2020 11:37
Show Gist options
  • Save serhatleventyavas/d9ee1e8633d53e37813d2b3a4388d974 to your computer and use it in GitHub Desktop.
Save serhatleventyavas/d9ee1e8633d53e37813d2b3a4388d974 to your computer and use it in GitHub Desktop.
fun requestTaskDirection(requestedUrl: String) {
viewModelScope.launch {
var routes: List<List<HashMap<String, String>>> = listOf()
withContext(Dispatchers.IO) {
// background io thread
val responseString = getDirectionFromPlaceApi(requestedUrl)
routes = parseDirection(responseString)
}
var points: ArrayList<LatLng>? = null
var polylineOptions: PolylineOptions? = null
for (path in routes)
{
points = ArrayList()
polylineOptions = PolylineOptions()
for (point in path)
{
val lat = java.lang.Double.parseDouble(point["lat"]!!)
val lon = java.lang.Double.parseDouble(point["lng"]!!)
points.add(LatLng(lat, lon))
}
polylineOptions.addAll(points)
polylineOptions.width(15f)
polylineOptions.color(Color.BLUE)
polylineOptions.geodesic(true)
}
// ui katmanı
}
}
private fun parseDirection(pathAsString: String): List<List<HashMap<String, String>>> {
var routes : List<List<HashMap<String, String>>> = listOf()
var jsonObject : JSONObject? = null
try {
jsonObject = JSONObject(pathAsString)
val parser = DirectionParser()
routes = parser.parse(jsonObject)
} catch (e : JSONException) {
e.printStackTrace()
}
return routes
}
private fun getDirectionFromPlaceApi(requestedUrl: String): String {
var responseString = ""
var inputStream : InputStream? = null
var httpURLConnection : HttpURLConnection? = null
try {
val url = URL(requestedUrl)
httpURLConnection = url.openConnection() as HttpURLConnection?
httpURLConnection!!.connect()
inputStream = httpURLConnection.inputStream
val inputStreamReader = InputStreamReader(inputStream!!)
val bufferedReader = BufferedReader(inputStreamReader)
val stringBuffer = StringBuffer()
var line = ""
while (bufferedReader.readLine() != null) {
line = bufferedReader.readLine()
stringBuffer.append(line)
}
responseString = stringBuffer.toString()
bufferedReader.close()
inputStreamReader.close()
}catch (e : Exception){
e.printStackTrace()
}finally {
if (inputStream != null) {
try {
inputStream.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
httpURLConnection?.disconnect()
return responseString
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment