如何在 Kotlin 中创建 GeoJson 文件?

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

假设我有一个农场的多边形,其坐标如下:

1st coordinate: lat: 4.5165132153 long: 99.651681683
2nd coordinate: lat: 4.5163152153 long: 99.878981683
3rd coordinate: lat: 4.3584532153 long: 99.021481683
4th coordinate: lat: 4.1578132153 long: 99.698781683
5th coordinate: lat: 4.3655132153 long: 99.321481683
6th coordinate: lat: 4.8795132153 long: 99.874581683

如何创建 GeoJSON 文件,然后单击按钮后下载创建的 GeoJSON 文件?

binding.downloadGeojsonFileButton.setOnClickListener{
}

谢谢你

android kotlin geospatial polygon geojson
1个回答
0
投票

如果您想创建并下载 GeoJSON 文件,您可以按照以下步骤操作:

  1. 使用标准 JSON 操作使用多边形坐标创建 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)
)
  1. 将 GeoJSON 数据序列化为 JSON 字符串:
val gson = Gson()
val geoJsonString = gson.toJson(featureCollection)
  1. 要下载 GeoJSON 文件,您可以将 JSON 字符串写入应用程序内部存储中的文件中:
val fileName = "my_polygon.geojson"
val file = File(context.filesDir, fileName)

file.writeText(geoJsonString)
  1. 要允许用户下载 GeoJSON 文件,您可以创建一个按钮单击侦听器,为用户提供下载链接:
binding.downloadGeojsonFileButton.setOnClickListener {
    val file = File(context.filesDir, "my_polygon.geojson")

    val uri = FileProvider.getUriForFile(
        context,
        "${context.packageName}.provider",
        file
    )

    val intent = Intent(Intent.ACTION_VIEW).apply {
        data = uri
        flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
        type = "application/json"
    }

    context.startActivity(intent)
}
  1. 在 AndroidManifest.xml 文件中定义一个文件提供程序,并创建一个
    file_paths.xml
    文件,如前面的响应中所述。

此方法允许您通过使用标准 JSON 操作技术手动构建 GeoJSON 结构来创建和下载 GeoJSON 文件,而无需使用第三方库。

© www.soinside.com 2019 - 2024. All rights reserved.