Home > database >  Distance Matrix Request in Kotlin Android
Distance Matrix Request in Kotlin Android

Time:03-14

I haven't found anything of the sort here, so I'm raising the question. How can I send a GET request to Distance Matrix like this:

https://maps.googleapis.com/maps/api/distancematrix/json?origins=&destinations=&units=metric&key=

And get JSON with results

I tried this but app killed when use it:

    val url = URL("https://maps.googleapis.com/maps/api/distancematrix/json?origins=$origen&destinations=$destino&units=metric&key=KEY")


    with(url.openConnection() as HttpURLConnection) {
        setRequestProperty("Accept","application/json")
        requestMethod = "GET"
        println("\nSent 'GET' request to URL : $url; Response Code : $responseCode")

        inputStream.bufferedReader().use {
            it.lines().forEach { line ->
                println(line)
            }
        }

    }

Thanks so much!

EDIT Error logs when call myFunction on autocomplete clicked

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.x.y, PID: 7168
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1316088539, result=-1, data=Intent { (has extras) }} to activity {com.x.y/com.x.y.MainActivity}: android.os.NetworkOnMainThreadException
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4901)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:4942)
    at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2069)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
 Caused by: android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1565)
    at com.android.org.conscrypt.Platform.blockGuardOnNetwork(Platform.java:430)
    at com.android.org.conscrypt.ConscryptEngineSocket$SSLOutputStream.writeInternal(ConscryptEngineSocket.java:666)
    at com.android.org.conscrypt.ConscryptEngineSocket$SSLOutputStream.access$200(ConscryptEngineSocket.java:625)
    at com.android.org.conscrypt.ConscryptEngineSocket.drainOutgoingQueue(ConscryptEngineSocket.java:594)
    at com.android.org.conscrypt.ConscryptEngineSocket.close(ConscryptEngineSocket.java:489)
    at com.android.okhttp.internal.Util.closeQuietly(Util.java:91)
    at com.android.okhttp.internal.http.StreamAllocation.deallocate(StreamAllocation.java:258)
    at com.android.okhttp.internal.http.StreamAllocation.connectionFailed(StreamAllocation.java:295)
    at com.android.okhttp.internal.http.HttpEngine.close(HttpEngine.java:469)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:513)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:411)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:542)
    at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getResponseCode(DelegatingHttpsURLConnection.java:106)
    at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:30)
    at com.x.MainActivity.myfunction(MainActivity.kt:127)
    at com.x.y.MainActivity$onCreate$2.onPlaceSelected(MainActivity.kt:91)
    at com.google.android.libraries.places.widget.AutocompleteSupportFragment.onActivityResult(com.google.android.libraries.places:places@@2.5.0:6)
    at androidx.fragment.app.FragmentManager$9.onActivityResult(FragmentManager.java:2905)
    at androidx.fragment.app.FragmentManager$9.onActivityResult(FragmentManager.java:2885)
    at androidx.activity.result.ActivityResultRegistry.doDispatch(ActivityResultRegistry.java:392)
    at androidx.activity.result.ActivityResultRegistry.dispatchResult(ActivityResultRegistry.java:351)
    at androidx.activity.ComponentActivity.onActivityResult(ComponentActivity.java:647)
    at androidx.fragment.app.FragmentActivity.onActivityResult(FragmentActivity.java:164)
    at android.app.Activity.dispatchActivityResult(Activity.java:8125)
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4894)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:4942) 
    at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51) 
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2069) 
    at android.os.Handler.dispatchMessage(Handler.java:107) 
    at android.os.Looper.loop(Looper.java:214) 
    at android.app.ActivityThread.main(ActivityThread.java:7417) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980) 

Error logs when call myFunction on autocomplete clicked

CodePudding user response:

SOLVED! i post the solution if anyone need it

    val origen = "36.000001"
    val destino = "120.000001"

    val urlMap = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=$origen&destinations=$destino&units=metric&key=YOUR_API_KEY"
    val request = Request.Builder()
        .url(urlMap)
        .build()
    client.newCall(request).enqueue(object : Callback {
        override fun onFailure(call: Call, e: IOException) {
            e.printStackTrace()
        }

        override fun onResponse(call: Call, response: Response) {
            response.use {
                if (!response.isSuccessful) throw IOException("Unexpected code $response")

                var json = JSONObject(response.body!!.string())
                val rows = json["rows"] as JSONArray
                val elements = rows[0] as JSONObject
                val distance = elements["elements"] as JSONArray
                val distanceArray = distance[0] as JSONObject
                val distanceData = distanceArray["distance"] as JSONObject

                val dist = distanceData["value"].toString().toDouble()
                val distKm = (dist/1000)

                if (distKm != null) {

                    val textview: TextView = findViewById(R.id.textview)
                    textview(Runnable { textview.setText(distKm.toString()) })

                }


            }
        }
    })
  • Related