假设我有一个农场的多边形,其坐标如下:
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{
}
谢谢你
如果您想创建并下载 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)
)
val gson = Gson()
val geoJsonString = gson.toJson(featureCollection)
val fileName = "my_polygon.geojson"
val file = File(context.filesDir, fileName)
file.writeText(geoJsonString)
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)
}
file_paths.xml
文件,如前面的响应中所述。此方法允许您通过使用标准 JSON 操作技术手动构建 GeoJSON 结构来创建和下载 GeoJSON 文件,而无需使用第三方库。