I am completely new to Kotlin and I have a task that I am trying to perform and cannot seem to find much documentation. I have coded what I need to do in JavaScript (see below), but I need to convert the same functionality to Kotlin. Basically, I have JSON file that contains coordinates within it. I need to extract these coordinates and push them into a brand new GeoJson variable. This is the code I need to convert, how can I go about doing this?
let routeTemp = {
'type': 'FeatureCollection',
'features': []
}
let geoTemp = {
'type': 'Feature',
'properties': {},
'geometry': {
'type': 'LineString',
'coordinates': [],
}
};
function jsonToGeo(data) {
for(track in data.track) {
let coords = [data.track[track].Lon, data.track[track].Lat];
geoTemp.geometry['coordinates'].push(coords);
}
routeTemp['features'].push(geoTemp);
}
My solution I ended up coming up with...
Make sure to import this:
import org.json.JSONObject
I defined my JSON as a string globally, and then used it to construct a JSON Object:
val jsonObject = JSONObject(jsonStr) // convert JSON string into JSON Object
Include this in the onCreate function:
val coordsLine = parseJsonL()
val geoStr = geoTemp(coordsLine)
Then define these functions:
// function to parse line coordinates from JSON
fun parseJsonL(): ArrayList<String> {
// extract tracks as an array from JSON
val trackArray = jsonObject.getJSONArray("track")
val coordList = ArrayList<String>()
// iterate through coordinates for each track, extract as strings, and add to a list
for (i in 0 until trackArray.length()) {
val coordsL = trackArray.getJSONObject(i)
val lon = coordsL.getString("Lon")
val lat = coordsL.getString("Lat")
coordList.add("[$lon, $lat]")
}
return coordList
}
// function to insert coordinates into GeoJSON template
fun geoTemp(coordsLine: ArrayList<String>): String {
val geoStr = """
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"name": "Sea Wall Route"
},
"geometry": {
"type": "LineString",
"coordinates": $coordsLine
}
}
]
}
""".trimIndent()
return geoStr
}
I'm open to suggestions for improving this code since, again, I'm very new to Kotlin :)