如何在 Kotlin 中下载 GeoJSON 文件?

问题描述 投票:0回答:1

因此将使用以下代码创建 GeoJSON 文件:

val coordinates = listOf(
Coordinate(4.5165132153, 99.651681683),
Coordinate(4.5163152153, 99.878981683),
Coordinate(4.3584532153, 99.021481683),
Coordinate(4.1578132153, 99.698781683),
Coordinate(4.3655132153, 99.321481683),
Coordinate(4.8795132153, 99.874581683)
)

val geometry = mapOf(
    "type" to "Polygon",
    "coordinates" to listOf(listOf(coordinates.map { listOf(it.lon, it.lat) }))
)

val properties = mapOf(
    "name" to "Your Polygon Name",
    // Add other properties as needed
)

val feature = mapOf(
    "type" to "Feature",
    "geometry" to geometry,
    "properties" to properties
)

val featureCollection = mapOf(
    "type" to "FeatureCollection",
    "features" to listOf(feature)
)

然后将GeoJSON数据序列化为JSON字符串

val gson = Gson()
val geoJsonString = gson.toJson(featureCollection)

所以我想下载这些数据并通过单击按钮将其保存到手机存储中,例如:binding.downloadButton.setOnClickListener{ }

有人知道如何执行此任务吗?

谢谢!

android json kotlin android-manifest geojson
1个回答
0
投票

首先,定义所需的

permissions

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

检查

permissions

if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
       == PackageManager.PERMISSION_DENIED) {
    requestPermissions(
        arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
        PERMISSION_REQUEST_CODE
    )
}

以及保存文件操作

try {
    val root =  Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
    if (!root.exists()) {
        root.mkDirs()
    }
    val file = File(root, "fileName.json")
    val writer = FileWriter(file)
    writer.append(geoJsonString)
    writer.flush()
    writer.close()
} catch (e: Exception) {
    e.printStackTrace()
}

您的案例

binding.downloadButton.setOnClickListener {
    if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
            == PackageManager.PERMISSION_DENIED) {
        requestPermissions(
            arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
            PERMISSION_REQUEST_CODE
        )
    } else {
        try {
            val root =  Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
            if (!root.exists()) {
                root.mkdirs()
            }
            val file = File(root, "fileName.json")
            val writer = FileWriter(file)
            writer.append(geoJsonString)
            writer.flush()
            writer.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.