Conflicts:
	app/src/main/assets/omdb_config.json
	app/src/main/java/com/navinfo/omqs/ui/fragment/tasklist/TaskViewModel.kt
This commit is contained in:
qiji4215 2023-10-26 15:02:34 +08:00
commit f03d8037d2
24 changed files with 1465 additions and 835 deletions

View File

@ -579,6 +579,12 @@
"zoomMin": 15, "zoomMin": 15,
"zoomMax": 17, "zoomMax": 17,
"transformer": [ "transformer": [
{
"k": "geometry",
"v": "~",
"klib": "geometry",
"vlib": "translateRight(direct=3)"
},
{ {
"k": "geometry", "k": "geometry",
"v": "~", "v": "~",

View File

@ -4,6 +4,7 @@ import android.util.Log
import com.google.gson.annotations.Expose import com.google.gson.annotations.Expose
import com.navinfo.collect.library.data.entity.RenderEntity import com.navinfo.collect.library.data.entity.RenderEntity
import com.navinfo.omqs.db.ImportPreProcess import com.navinfo.omqs.db.ImportPreProcess
import io.realm.Realm
import kotlin.reflect.KFunction import kotlin.reflect.KFunction
import kotlin.reflect.KParameter import kotlin.reflect.KParameter
import kotlin.reflect.full.declaredMemberFunctions import kotlin.reflect.full.declaredMemberFunctions
@ -12,13 +13,15 @@ import kotlin.reflect.full.declaredMemberFunctions
class ImportConfig { class ImportConfig {
@Expose @Expose
var tableMap: MutableMap<String, TableInfo> = mutableMapOf() var tableMap: MutableMap<String, TableInfo> = mutableMapOf()
@Expose @Expose
val tableGroupName: String = "OMDB数据" val tableGroupName: String = "OMDB数据"
@Expose @Expose
var checked: Boolean = true var checked: Boolean = true
val preProcess: ImportPreProcess = ImportPreProcess() val preProcess: ImportPreProcess = ImportPreProcess()
fun transformProperties(renderEntity: RenderEntity, realm: Realm): RenderEntity? {
fun transformProperties(renderEntity: RenderEntity): RenderEntity? { preProcess.realm = realm
val transformList = tableMap[renderEntity.code.toString()]?.transformer val transformList = tableMap[renderEntity.code.toString()]?.transformer
if (transformList.isNullOrEmpty()) { if (transformList.isNullOrEmpty()) {
Log.e("qj", "子表转换为空===${renderEntity.code}") Log.e("qj", "子表转换为空===${renderEntity.code}")
@ -36,7 +39,10 @@ class ImportConfig {
continue continue
} }
// 如果key和value都为空说明当前数据需要增加一个新字段 // 如果key和value都为空说明当前数据需要增加一个新字段
if (key.isNullOrEmpty()&&value.isNullOrEmpty()&&!renderEntity.properties.containsKey(keylib)) { if (key.isNullOrEmpty() && value.isNullOrEmpty() && !renderEntity.properties.containsKey(
keylib
)
) {
renderEntity.properties[keylib] = valuelib renderEntity.properties[keylib] = valuelib
continue continue
} }
@ -49,21 +55,27 @@ class ImportConfig {
// 获取方法名 // 获取方法名
val methodName = valuelib.substringBefore("(") val methodName = valuelib.substringBefore("(")
// 获取参数 // 获取参数
val params: List<String> = valuelib.substringAfter("(").substringBefore(")").split(",").filter{ it.isNotEmpty() }.map { it.trim() } val params: List<String> =
val method = preProcess::class.members.filter { it.name == methodName }.first() as KFunction<*> valuelib.substringAfter("(").substringBefore(")").split(",")
.filter { it.isNotEmpty() }.map { it.trim() }
val method =
preProcess::class.members.filter { it.name == methodName }
.first() as KFunction<*>
val methodParams = method.parameters val methodParams = method.parameters
val callByParams = mutableMapOf<KParameter, Any>( val callByParams = mutableMapOf<KParameter, Any>(
methodParams[0] to preProcess, methodParams[0] to preProcess,
methodParams[1] to renderEntity methodParams[1] to renderEntity,
) )
for ((index, value) in params.withIndex()) { for ((index, value) in params.withIndex()) {
// 前2个参数确定为对象本身和RenderEntity因此自定义参数从index+2开始设置 // 前2个参数确定为对象本身和RenderEntity因此自定义参数从index+2开始设置
if (methodParams.size > index + 2) { if (methodParams.size > index + 2) {
callByParams[methodParams[index+2]] = value.replace("'", "") callByParams[methodParams[index + 2]] =
value.replace("'", "")
} }
} }
when(val result = method.callBy(callByParams)) { // 如果方法返回的数据类型是boolean且返回为false则该数据不处理 when (val result =
method.callBy(callByParams)) { // 如果方法返回的数据类型是boolean且返回为false则该数据不处理
is Boolean -> is Boolean ->
if (!result) { if (!result) {
return null return null
@ -78,8 +90,12 @@ class ImportConfig {
// 获取方法名 // 获取方法名
val methodName = valuelib.substringBefore("(") val methodName = valuelib.substringBefore("(")
// 获取参数 // 获取参数
val params: List<String> = valuelib.substringAfter("(").substringBefore(")").split(",").filter{ it.isNotEmpty() }.map { it.trim() } val params: List<String> =
val method = preProcess::class.members.filter { it.name == methodName }.first() as KFunction<*> valuelib.substringAfter("(").substringBefore(")").split(",")
.filter { it.isNotEmpty() }.map { it.trim() }
val method =
preProcess::class.members.filter { it.name == methodName }
.first() as KFunction<*>
val methodParams = method.parameters val methodParams = method.parameters
val callByParams = mutableMapOf<KParameter, Any>( val callByParams = mutableMapOf<KParameter, Any>(
@ -107,6 +123,7 @@ class ImportConfig {
} }
} }
} }
preProcess.realm = null
return renderEntity return renderEntity
} }
@ -128,7 +145,8 @@ class TableInfo {
val filterData: Boolean = false//是否需要过滤数据 val filterData: Boolean = false//是否需要过滤数据
val existSubCode: Boolean = false//是否存在子编码 val existSubCode: Boolean = false//是否存在子编码
val catch: Boolean = false//是否需要捕捉 // 需要根据丹丹提供的捕捉原则进行设置参考文档W行设置条件https://navinfo.feishu.cn/sheets/shtcnfsxKZhekU26ezBcHgl7aWh?sheet=BZd6yM val catch: Boolean =
false//是否需要捕捉 // 需要根据丹丹提供的捕捉原则进行设置参考文档W行设置条件https://navinfo.feishu.cn/sheets/shtcnfsxKZhekU26ezBcHgl7aWh?sheet=BZd6yM
val name: String = "" val name: String = ""
var checked: Boolean = true var checked: Boolean = true
var transformer: MutableList<Transform> = mutableListOf() var transformer: MutableList<Transform> = mutableListOf()

View File

@ -10,11 +10,10 @@ import com.blankj.utilcode.util.FileIOUtils
import com.blankj.utilcode.util.ZipUtils import com.blankj.utilcode.util.ZipUtils
import com.google.gson.Gson import com.google.gson.Gson
import com.google.gson.reflect.TypeToken import com.google.gson.reflect.TypeToken
import com.navinfo.collect.library.data.entity.HadLinkDvoBean import com.navinfo.collect.library.data.entity.*
import com.navinfo.collect.library.data.entity.RenderEntity
import com.navinfo.collect.library.data.entity.TaskBean
import com.navinfo.collect.library.enums.DataCodeEnum import com.navinfo.collect.library.enums.DataCodeEnum
import com.navinfo.collect.library.utils.GeometryTools import com.navinfo.collect.library.utils.GeometryTools
import com.navinfo.collect.library.utils.StrZipUtil
import com.navinfo.omqs.Constant import com.navinfo.omqs.Constant
import com.navinfo.omqs.Constant.Companion.currentInstallTaskConfig import com.navinfo.omqs.Constant.Companion.currentInstallTaskConfig
import com.navinfo.omqs.Constant.Companion.currentInstallTaskFolder import com.navinfo.omqs.Constant.Companion.currentInstallTaskFolder
@ -27,6 +26,7 @@ import dagger.assisted.AssistedInject
import io.realm.Realm import io.realm.Realm
import io.realm.RealmConfiguration import io.realm.RealmConfiguration
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
@ -35,16 +35,19 @@ import org.locationtech.jts.geom.GeometryFactory
import org.locationtech.jts.geom.LineString import org.locationtech.jts.geom.LineString
import org.locationtech.jts.geom.MultiLineString import org.locationtech.jts.geom.MultiLineString
import org.spatialite.database.SQLiteDatabase import org.spatialite.database.SQLiteDatabase
import java.io.BufferedReader
import java.io.File import java.io.File
import java.io.FileReader
import java.util.*
import javax.inject.Inject import javax.inject.Inject
import kotlin.collections.HashMap
import kotlin.streams.toList import kotlin.streams.toList
/** /**
* 导入omdb数据的帮助类 * 导入omdb数据的帮助类
* */ * */
class ImportOMDBHelper @AssistedInject constructor( class ImportOMDBHelper @AssistedInject constructor(
@Assisted("context") val context: Context, @Assisted("context") val context: Context, @Assisted("omdbFile") val omdbFile: File
@Assisted("omdbFile") val omdbFile: File
) { ) {
@Inject @Inject
lateinit var omdbHiltFactory: OMDBDataBaseHiltFactory lateinit var omdbHiltFactory: OMDBDataBaseHiltFactory
@ -53,13 +56,10 @@ class ImportOMDBHelper @AssistedInject constructor(
lateinit var gson: Gson lateinit var gson: Gson
private val database by lazy { private val database by lazy {
omdbHiltFactory.obtainOmdbDataBaseHelper( omdbHiltFactory.obtainOmdbDataBaseHelper(
context, context, omdbFile.absolutePath, 1
omdbFile.absolutePath,
1
).writableDatabase ).writableDatabase
} }
private val configFile: File = private val configFile: File = File("${Constant.USER_DATA_PATH}", Constant.OMDB_CONFIG)
File("${Constant.USER_DATA_PATH}", Constant.OMDB_CONFIG)
private val importConfigList by lazy { private val importConfigList by lazy {
openConfigFile() openConfigFile()
@ -103,8 +103,14 @@ class ImportOMDBHelper @AssistedInject constructor(
}.toList() }.toList()
val cursor = database.query( val cursor = database.query(
table, finalColumns.toTypedArray(), "1=1", table,
mutableListOf<String>().toTypedArray(), null, null, null, null finalColumns.toTypedArray(),
"1=1",
mutableListOf<String>().toTypedArray(),
null,
null,
null,
null
) )
with(cursor) { with(cursor) {
if (moveToFirst()) { if (moveToFirst()) {
@ -150,13 +156,11 @@ class ImportOMDBHelper @AssistedInject constructor(
installTaskid = task.id.toString() installTaskid = task.id.toString()
currentInstallTaskFolder = File(Constant.USER_DATA_PATH + "/$installTaskid") currentInstallTaskFolder = File(Constant.USER_DATA_PATH + "/$installTaskid")
if (!currentInstallTaskFolder.exists()) currentInstallTaskFolder.mkdirs() if (!currentInstallTaskFolder.exists()) currentInstallTaskFolder.mkdirs()
currentInstallTaskConfig = RealmConfiguration.Builder() currentInstallTaskConfig =
.directory(currentInstallTaskFolder) RealmConfiguration.Builder().directory(currentInstallTaskFolder).name("OMQS.realm")
.name("OMQS.realm")
.encryptionKey(Constant.PASSWORD) .encryptionKey(Constant.PASSWORD)
.allowQueriesOnUiThread(true) // .allowQueriesOnUiThread(true)
.schemaVersion(2) .schemaVersion(2).build()
.build()
val unZipFolder = File(omdbZipFile.parentFile, "result") val unZipFolder = File(omdbZipFile.parentFile, "result")
flow { flow {
@ -166,7 +170,6 @@ class ImportOMDBHelper @AssistedInject constructor(
unZipFolder.mkdirs() unZipFolder.mkdirs()
// 开始解压zip文件 // 开始解压zip文件
val unZipFiles = ZipUtils.unzipFile(omdbZipFile, unZipFolder) val unZipFiles = ZipUtils.unzipFile(omdbZipFile, unZipFolder)
// 先获取当前配置的所有图层的个数,方便后续计算数据解析进度 // 先获取当前配置的所有图层的个数,方便后续计算数据解析进度
var tableNum = 0 var tableNum = 0
var processIndex = 0 var processIndex = 0
@ -177,71 +180,69 @@ class ImportOMDBHelper @AssistedInject constructor(
//单个表要素统计 //单个表要素统计
var elementIndex = 0 var elementIndex = 0
//单个表要素时间统计 //单个表要素时间统计
var tableImportTime = System.currentTimeMillis() // var tableImportTime = System.currentTimeMillis()
//总表要素统计时间 //总表要素统计时间
var dataImportTime = System.currentTimeMillis() // var dataImportTime = System.currentTimeMillis()
// Realm.compactRealm(currentInstallTaskConfig)
Realm.getInstance(currentInstallTaskConfig).beginTransaction() var realm = Realm.getInstance(currentInstallTaskConfig)
realm.beginTransaction()
for (importConfig in importConfigList) { for (importConfig in importConfigList) {
tableNum += importConfig.tableMap.size tableNum += importConfig.tableMap.size
} }
//缓存任务link信息便于下面与数据进行任务link匹配 //缓存任务link信息便于下面与数据进行任务link匹配
val hashMap: HashMap<Long, HadLinkDvoBean> = HashMap<Long, HadLinkDvoBean>() val hashMap: HashMap<Long, HadLinkDvoBean> = HashMap<Long, HadLinkDvoBean>()
val lineList = arrayOfNulls<LineString>(task.hadLinkDvoList.size) // val lineList = arrayOfNulls<LineString>(task.hadLinkDvoList.size)
var index = 0 // var index = 0
task.hadLinkDvoList.forEach { task.hadLinkDvoList.forEach {
hashMap[it.linkPid.toLong()] = it hashMap[it.linkPid.toLong()] = it
lineList[index] = GeometryTools.createGeometry(it.geometry) as LineString // lineList[index] = GeometryTools.createGeometry(it.geometry) as LineString
index++ // index++
} }
val resHashMap: HashMap<String, RenderEntity> = val resHashMap: HashMap<String, RenderEntity> = HashMap() //define empty hashmap
HashMap<String, RenderEntity>() //define empty hashmap val listRenderEntity = mutableListOf<RenderEntity>()
try { try {
var multipLine = MultiLineString(lineList, GeometryFactory()) // var multipLine = MultiLineString(lineList, GeometryFactory())
// 遍历解压后的文件,读取该数据返回 // 遍历解压后的文件,读取该数据返回
Log.d("ImportOMDBHelper", "表解析===开始时间$dataImportTime===") // Log.d("ImportOMDBHelper", "表解析===开始时间$dataImportTime===")
for (importConfig in importConfigList) { for (importConfig in importConfigList) {
for ((index, currentEntry) in importConfig.tableMap.entries.withIndex()) { for ((index, currentEntry) in importConfig.tableMap.entries.withIndex()) {
processIndex += 1 processIndex += 1
Log.d( // Log.d(
"ImportOMDBHelper", // "ImportOMDBHelper",
"表解析===开始时间$tableImportTime===${currentEntry.value.table}" // "表解析===开始时间$tableImportTime===${currentEntry.value.table}"
) // )
Log.d( // Log.d(
"ImportOMDBHelper", // "ImportOMDBHelper",
"表解析===processIndex${processIndex}====${processIndex}/${tableNum}" // "表解析===processIndex${processIndex}====${processIndex}/${tableNum}"
) // )
val listResult = mutableListOf<RenderEntity>() // val listResult = mutableListOf<RenderEntity>()
val currentConfig = currentEntry.value val currentConfig = currentEntry.value
val txtFile = unZipFiles.find { val txtFile = unZipFiles.find {
it.name == currentConfig.table it.name == currentConfig.table
} }
// 将listResult数据插入到Realm数据库中 if (txtFile != null) {
currentConfig?.let { val fileReader = FileReader(txtFile)
val list = FileIOUtils.readFile2List(txtFile, "UTF-8") val bufferedReader = BufferedReader(fileReader)
Log.d("ImportOMDBHelper", "开始解析:${txtFile?.name}") var line: String? = bufferedReader.readLine()
if (list != null) { while (line != null) {
// 将list数据转换为map
for ((index, line) in list.withIndex()) {
if (line == null || line.trim() == "") { if (line == null || line.trim() == "") {
line = bufferedReader.readLine()
continue continue
} }
elementIndex += 1 elementIndex += 1
dataIndex += 1 dataIndex += 1
Log.d("ImportOMDBHelper", "解析第:${index + 1}---${txtFile?.name}") // Log.d("ImportOMDBHelper", "解析第:${index + 1}行")
val map = gson.fromJson<Map<String, Any>>( val map = gson.fromJson<Map<String, Any>>(
line, line, object : TypeToken<Map<String, Any>>() {}.type
object : TypeToken<Map<String, Any>>() {}.getType() ).toMutableMap()
)
.toMutableMap()
map["qi_table"] = currentConfig.table map["qi_table"] = currentConfig.table
map["qi_name"] = currentConfig.name map["qi_name"] = currentConfig.name
map["qi_code"] = map["qi_code"] =
@ -258,8 +259,27 @@ class ImportOMDBHelper @AssistedInject constructor(
renderEntity.zoomMin = map["qi_zoomMin"].toString().toInt() renderEntity.zoomMin = map["qi_zoomMin"].toString().toInt()
renderEntity.zoomMax = map["qi_zoomMax"].toString().toInt() renderEntity.zoomMax = map["qi_zoomMax"].toString().toInt()
// 在外层记录当前数据的linkPid
if (map.containsKey("linkPid")) {
renderEntity.linkPid =
map["linkPid"].toString().split(",")[0]
} else if (map.containsKey("linkList")) {
val linkList = map["linkList"].toString()
if (!linkList.isNullOrEmpty() && linkList != "null") {
val list: List<LinkList> = gson.fromJson(
linkList,
object : TypeToken<List<LinkList>>() {}.type
)
renderEntity.linkPid = list[0].linkPid
}
}
Log.e(
"jingo",
"安装数据 ${renderEntity.table} ${renderEntity.linkPid} ${elementIndex} ${insertIndex}"
)
renderEntity.geometry = map["geometry"].toString() renderEntity.geometry = map["geometry"].toString()
Log.d("ImportOMDBHelper", "解析===1处理3D") // Log.d("ImportOMDBHelper", "解析===1处理3D")
// 其他数据插入到Properties中 // 其他数据插入到Properties中
/* if (!currentConfig.is3D) { // 如果是非3d要素则自动将Z轴坐标全部置为0 /* if (!currentConfig.is3D) { // 如果是非3d要素则自动将Z轴坐标全部置为0
val coordinates = val coordinates =
@ -284,58 +304,53 @@ class ImportOMDBHelper @AssistedInject constructor(
renderEntity.geometry = newGeometry.toString() renderEntity.geometry = newGeometry.toString()
} }
}*/ }*/
Log.d("ImportOMDBHelper", "解析===2处理3D") // Log.d("ImportOMDBHelper", "解析===2处理3D")
Log.d("ImportOMDBHelper", "解析===1处理属性") // Log.d("ImportOMDBHelper", "解析===1处理属性")
for ((key, value) in map) { for ((key, value) in map) {
when (value) { when (value) {
is String -> renderEntity.properties.put(key, value) is String -> renderEntity.properties[key] = value
is Int -> renderEntity.properties.put( is Int -> renderEntity.properties[key] =
key,
value.toInt().toString() value.toInt().toString()
)
is Double -> renderEntity.properties.put( is Double -> renderEntity.properties[key] =
key,
value.toDouble().toString() value.toDouble().toString()
)
else -> renderEntity.properties.put( else -> renderEntity.properties[key] = value.toString()
key,
value.toString()
)
} }
} }
Log.d("ImportOMDBHelper", "解析===2处理属性") // Log.d("ImportOMDBHelper", "解析===2处理属性")
Log.d("ImportOMDBHelper", "解析===1处理name") // Log.d("ImportOMDBHelper", "解析===1处理name")
// 如果properties中不包含name那么自动将要素名称添加进properties中 // 如果properties中不包含name那么自动将要素名称添加进properties中
if (!renderEntity.properties.containsKey("name")) { if (!renderEntity.properties.containsKey("name")) {
renderEntity.properties["name"] = renderEntity.name; renderEntity.properties["name"] = renderEntity.name;
} }
Log.d("ImportOMDBHelper", "解析===2处理name") // Log.d("ImportOMDBHelper", "解析===2处理name")
Log.d("ImportOMDBHelper", "解析===1处理杆状物") // Log.d("ImportOMDBHelper", "解析===1处理杆状物")
if (currentConfig.filterData) { if (currentConfig.filterData) {
when (renderEntity.code.toInt()) { when (renderEntity.code.toInt()) {
DataCodeEnum.OMDB_POLE.code.toInt() -> { DataCodeEnum.OMDB_POLE.code.toInt() -> {
//过滤树类型的杆状物,无需导入到数据库中 //过滤树类型的杆状物,无需导入到数据库中
val poleType = val poleType = renderEntity.properties["poleType"]
renderEntity.properties["poleType"]
if (poleType != null && poleType.toInt() == 2) { if (poleType != null && poleType.toInt() == 2) {
line = bufferedReader.readLine()
continue continue
} }
} }
DataCodeEnum.OMDB_LANE_MARK_BOUNDARYTYPE.code.toInt() -> { DataCodeEnum.OMDB_LANE_MARK_BOUNDARYTYPE.code.toInt() -> {
var boundaryType = renderEntity.properties["boundaryType"] val boundaryType =
renderEntity.properties["boundaryType"]
if (boundaryType != null) { if (boundaryType != null) {
when (boundaryType.toInt()) { when (boundaryType.toInt()) {
0, 1, 6, 8, 9 -> { 0, 1, 6, 8, 9 -> {
renderEntity.enable = 0 renderEntity.enable = 0
Log.e( // Log.e(
"qj", // "qj",
"过滤不显示数据${renderEntity.table}" // "过滤不显示数据${renderEntity.table}"
) // )
line = bufferedReader.readLine()
continue continue
} }
} }
@ -343,16 +358,17 @@ class ImportOMDBHelper @AssistedInject constructor(
} }
DataCodeEnum.OMDB_RDBOUND_BOUNDARYTYPE.code.toInt() -> { DataCodeEnum.OMDB_RDBOUND_BOUNDARYTYPE.code.toInt() -> {
var boundaryType = val boundaryType =
renderEntity.properties["boundaryType"] renderEntity.properties["boundaryType"]
if (boundaryType != null) { if (boundaryType != null) {
when (boundaryType.toInt()) { when (boundaryType.toInt()) {
0, 1, 3, 4, 5, 7, 9 -> { 0, 1, 3, 4, 5, 7, 9 -> {
renderEntity.enable = 0 renderEntity.enable = 0
Log.e( // Log.e(
"qj", // "qj",
"过滤不显示数据${renderEntity.table}" // "过滤不显示数据${renderEntity.table}"
) // )
line = bufferedReader.readLine()
continue continue
} }
} }
@ -360,16 +376,17 @@ class ImportOMDBHelper @AssistedInject constructor(
} }
DataCodeEnum.OMDB_OBJECT_STOPLOCATION.code.toInt() -> { DataCodeEnum.OMDB_OBJECT_STOPLOCATION.code.toInt() -> {
var locationType = val locationType =
renderEntity.properties["locationType"] renderEntity.properties["locationType"]
if (locationType != null) { if (locationType != null) {
when (locationType.toInt()) { when (locationType.toInt()) {
3, 4 -> { 3, 4 -> {
renderEntity.enable = 0 renderEntity.enable = 0
Log.e( // Log.e(
"qj", // "qj",
"过滤不显示数据${renderEntity.table}" // "过滤不显示数据${renderEntity.table}"
) // )
line = bufferedReader.readLine()
continue continue
} }
} }
@ -381,17 +398,16 @@ class ImportOMDBHelper @AssistedInject constructor(
"linkOut" "linkOut"
) )
) { ) {
var linkIn = val linkIn = renderEntity.properties["linkIn"]
renderEntity.properties["linkIn"] val linkOut = renderEntity.properties["linkOut"]
var linkOut =
renderEntity.properties["linkOut"]
if (linkIn != null && linkOut != null) { if (linkIn != null && linkOut != null) {
var checkMsg = "$linkIn$linkOut" val checkMsg = "$linkIn$linkOut"
if (resHashMap.containsKey(checkMsg)) { if (resHashMap.containsKey(checkMsg)) {
Log.e( // Log.e(
"qj", // "qj",
"${renderEntity.name}==过滤交限linkin与linkout相同且存在多条数据" // "${renderEntity.name}==过滤交限linkin与linkout相同且存在多条数据"
) // )
line = bufferedReader.readLine()
continue continue
} else { } else {
resHashMap[checkMsg] = renderEntity resHashMap[checkMsg] = renderEntity
@ -403,40 +419,39 @@ class ImportOMDBHelper @AssistedInject constructor(
} }
Log.d("ImportOMDBHelper", "解析===2处理杆状物") // Log.d("ImportOMDBHelper", "解析===2处理杆状物")
Log.d("ImportOMDBHelper", "解析===1任务路线匹配") // Log.d("ImportOMDBHelper", "解析===1任务路线匹配")
//遍历判断只显示与任务Link相关的任务数据 //遍历判断只显示与任务Link相关的任务数据
if (currentConfig.checkLinkId) { if (currentConfig.checkLinkId) {
if (renderEntity.properties.containsKey("linkPid")) { if (renderEntity.linkPid.isNotEmpty()) {
var currentLinkPid = val currentLinkPid = renderEntity.linkPid
renderEntity.properties["linkPid"]
Log.d( // Log.d(
"ImportOMDBHelper", // "ImportOMDBHelper",
"解析===1任务路线匹配${currentLinkPid}" // "解析===1任务路线匹配${currentLinkPid}"
) // )
if (!currentLinkPid.isNullOrEmpty() && currentLinkPid != "null") { if (!currentLinkPid.isNullOrEmpty() && currentLinkPid != "null") {
var list = currentLinkPid.split(",") val list = currentLinkPid.split(",")
if (list != null && list.isNotEmpty()) { if (list.isNotEmpty()) {
Log.d( // Log.d(
"ImportOMDBHelper", // "ImportOMDBHelper",
"解析===1任务路线匹配${list.size}" // "解析===1任务路线匹配${list.size}"
) // )
m@ for (linkPid in list) { m@ for (linkPid in list) {
if (hashMap.containsKey(linkPid.toLong())) { if (hashMap.containsKey(linkPid.toLong())) {
renderEntity.enable = 1 renderEntity.enable = 1
Log.e( // Log.e(
"qj", // "qj",
"${renderEntity.name}==包括任务link" // "${renderEntity.name}==包括任务link"
) // )
break@m break@m
} }
} }
@ -450,51 +465,49 @@ class ImportOMDBHelper @AssistedInject constructor(
if (renderEntity.properties["linkList"] != null) { if (renderEntity.properties["linkList"] != null) {
Log.e( // Log.e(
"qj", // "qj",
"linkList==开始${renderEntity.name}==${renderEntity.properties["linkList"]}}" // "linkList==开始${renderEntity.name}==${renderEntity.properties["linkList"]}}"
) // )
val linkList = val linkList = renderEntity.properties["linkList"]
renderEntity.properties["linkList"]
if (!linkList.isNullOrEmpty() && linkList != "null") { if (!linkList.isNullOrEmpty() && linkList != "null") {
Log.e( // Log.e(
"qj", // "qj",
"linkList==${renderEntity.name}==${renderEntity.properties["linkList"]}}" // "linkList==${renderEntity.name}==${renderEntity.properties["linkList"]}}"
) // )
val list: List<LinkList> = gson.fromJson( val list: List<LinkList> = gson.fromJson(
linkList, linkList,
object : object : TypeToken<List<LinkList>>() {}.type
TypeToken<List<LinkList>>() {}.type
) )
if (list != null) {
m@ for (link in list) { m@ for (link in list) {
if (hashMap.containsKey(link.linkPid.toLong())) { if (hashMap.containsKey(link.linkPid.toLong())) {
renderEntity.enable = 1 renderEntity.enable = 1
Log.e( // Log.e(
"qj", // "qj",
"${renderEntity.name}==包括任务link" // "${renderEntity.name}==包括任务link"
) // )
break@m break@m
} }
} }
} }
} }
}
} else { } else {
//不包括linkPid直接过滤 //不包括linkPid直接过滤
line = bufferedReader.readLine()
continue continue
} }
//过滤掉非任务路线上的数据 //过滤掉非任务路线上的数据
if (renderEntity.enable != 1) { if (renderEntity.enable != 1) {
Log.e( // Log.e(
"qj", // "qj",
"${renderEntity.name}==过滤不包括任务路线上的数据" // "${renderEntity.name}==过滤不包括任务路线上的数据"
) // )
line = bufferedReader.readLine()
continue continue
} }
@ -512,10 +525,10 @@ class ImportOMDBHelper @AssistedInject constructor(
renderEntity.enable = 1 renderEntity.enable = 1
} }
}*/ }*/
Log.e("qj", "${renderEntity.name}==不包括任务linkPid") // Log.e("qj", "${renderEntity.name}==不包括任务linkPid")
} }
Log.d("ImportOMDBHelper", "解析===2任务路线匹配") // Log.d("ImportOMDBHelper", "解析===2任务路线匹配")
Log.d("ImportOMDBHelper", "解析===1预处理") // Log.d("ImportOMDBHelper", "解析===1预处理")
if (currentConfig.catch) { if (currentConfig.catch) {
renderEntity.catchEnable = 1 renderEntity.catchEnable = 1
@ -524,31 +537,32 @@ class ImportOMDBHelper @AssistedInject constructor(
} }
// 对renderEntity做预处理后再保存 // 对renderEntity做预处理后再保存
val resultEntity = importConfig.transformProperties(renderEntity) val resultEntity =
Log.d("ImportOMDBHelper", "解析===2预处理") importConfig.transformProperties(renderEntity, realm)
// Log.d("ImportOMDBHelper", "解析===2预处理")
if (resultEntity != null) { if (resultEntity != null) {
Log.d("ImportOMDBHelper", "解析===1子code处理") // Log.d("ImportOMDBHelper", "解析===1子code处理")
//对code编码需要特殊处理 存在多个属性值时渲染优先级SA>PA,存在多个属性值时渲染优先级FRONTAGE>MAIN_SIDE_A CCESS //对code编码需要特殊处理 存在多个属性值时渲染优先级SA>PA,存在多个属性值时渲染优先级FRONTAGE>MAIN_SIDE_A CCESS
if (currentConfig.existSubCode) { if (currentConfig.existSubCode) {
when (renderEntity.code.toInt()) { when (renderEntity.code.toInt()) {
DataCodeEnum.OMDB_LINK_ATTRIBUTE.code.toInt() -> { DataCodeEnum.OMDB_LINK_ATTRIBUTE.code.toInt() -> {
Log.e("qj", "道路属性===0") // Log.e("qj", "道路属性===0")
var type = renderEntity.properties["sa"] var type = renderEntity.properties["sa"]
if (type != null && type == "1") { if (type != null && type == "1") {
renderEntity.code = renderEntity.code =
DataCodeEnum.OMDB_LINK_ATTRIBUTE_SA.code DataCodeEnum.OMDB_LINK_ATTRIBUTE_SA.code
Log.e("qj", "道路属性===1") // Log.e("qj", "道路属性===1")
} else { } else {
type = renderEntity.properties["pa"] type = renderEntity.properties["pa"]
if (type != null && type == "1") { if (type != null && type == "1") {
renderEntity.code = renderEntity.code =
DataCodeEnum.OMDB_LINK_ATTRIBUTE_PA.code DataCodeEnum.OMDB_LINK_ATTRIBUTE_PA.code
Log.e("qj", "道路属性===2") // Log.e("qj", "道路属性===2")
} else { } else {
type = type =
renderEntity.properties["frontage"] renderEntity.properties["frontage"]
@ -557,7 +571,7 @@ class ImportOMDBHelper @AssistedInject constructor(
DataCodeEnum.OMDB_LINK_ATTRIBUTE_FORNTAGE.code DataCodeEnum.OMDB_LINK_ATTRIBUTE_FORNTAGE.code
renderEntity.zoomMin = 15 renderEntity.zoomMin = 15
renderEntity.zoomMax = 17 renderEntity.zoomMax = 17
Log.e("qj", "道路属性===3") // Log.e("qj", "道路属性===3")
} else { } else {
type = type =
renderEntity.properties["mainSideAccess"] renderEntity.properties["mainSideAccess"]
@ -566,16 +580,17 @@ class ImportOMDBHelper @AssistedInject constructor(
DataCodeEnum.OMDB_LINK_ATTRIBUTE_MAIN_SIDE_ACCESS.code DataCodeEnum.OMDB_LINK_ATTRIBUTE_MAIN_SIDE_ACCESS.code
renderEntity.zoomMin = 15 renderEntity.zoomMin = 15
renderEntity.zoomMax = 17 renderEntity.zoomMax = 17
Log.e("qj", "道路属性===4") // Log.e("qj", "道路属性===4")
} else { } else {
renderEntity.enable = 0 renderEntity.enable = 0
renderEntity.zoomMin = 15 renderEntity.zoomMin = 15
renderEntity.zoomMax = 17 renderEntity.zoomMax = 17
Log.e( // Log.e(
"qj", // "qj",
"过滤不显示数据${renderEntity.table}" // "过滤不显示数据${renderEntity.table}"
) // )
Log.e("qj", "道路属性===5") // Log.e("qj", "道路属性===5")
line = bufferedReader.readLine()
continue continue
} }
} }
@ -596,7 +611,7 @@ class ImportOMDBHelper @AssistedInject constructor(
DataCodeEnum.OMDB_RAMP.code.toInt() -> { DataCodeEnum.OMDB_RAMP.code.toInt() -> {
/*匝道*/ /*匝道*/
var formWay = val formWay =
renderEntity.properties["formOfWay"] renderEntity.properties["formOfWay"]
if (formWay != null) { if (formWay != null) {
when (formWay.toInt()) { when (formWay.toInt()) {
@ -626,7 +641,7 @@ class ImportOMDBHelper @AssistedInject constructor(
DataCodeEnum.OMDB_LINK_FORM1.code.toInt() -> { DataCodeEnum.OMDB_LINK_FORM1.code.toInt() -> {
/*道路形态1*/ /*道路形态1*/
var formWay = val formWay =
renderEntity.properties["formOfWay"] renderEntity.properties["formOfWay"]
if (formWay != null) { if (formWay != null) {
when (formWay.toInt()) { when (formWay.toInt()) {
@ -643,12 +658,12 @@ class ImportOMDBHelper @AssistedInject constructor(
} }
DataCodeEnum.OMDB_LINK_FORM2.code.toInt() -> { DataCodeEnum.OMDB_LINK_FORM2.code.toInt() -> {
Log.e( // Log.e(
"qj", // "qj",
"道路形态2${renderEntity.properties["formOfWay"]}" // "道路形态2${renderEntity.properties["formOfWay"]}"
) // )
/*道路形态2*/ /*道路形态2*/
var formWay = val formWay =
renderEntity.properties["formOfWay"] renderEntity.properties["formOfWay"]
if (formWay != null) { if (formWay != null) {
when (formWay.toInt()) { when (formWay.toInt()) {
@ -696,7 +711,7 @@ class ImportOMDBHelper @AssistedInject constructor(
DataCodeEnum.OMDB_LANE_CONSTRUCTION.code.toInt() -> { DataCodeEnum.OMDB_LANE_CONSTRUCTION.code.toInt() -> {
//特殊处理空数据,渲染原则使用 //特殊处理空数据,渲染原则使用
var startTime = val startTime =
renderEntity.properties["startTime"] renderEntity.properties["startTime"]
if (startTime == null || startTime == "") { if (startTime == null || startTime == "") {
renderEntity.properties["startTime"] = renderEntity.properties["startTime"] =
@ -707,38 +722,39 @@ class ImportOMDBHelper @AssistedInject constructor(
if (renderEntity.table == DataCodeEnum.OMDB_NODE_FORM.name) {//特殊处理因为code相同使用表名判断 if (renderEntity.table == DataCodeEnum.OMDB_NODE_FORM.name) {//特殊处理因为code相同使用表名判断
//过滤不需要渲染的要素 //过滤不需要渲染的要素
var formOfWay = val formOfWay = renderEntity.properties["formOfWay"]
renderEntity.properties["formOfWay"]
if (formOfWay != null && formOfWay.toInt() == 30) { if (formOfWay != null && formOfWay.toInt() == 30) {
renderEntity.enable = 2 renderEntity.enable = 2
renderEntity.code = renderEntity.code =
DataCodeEnum.OMDB_NODE_FORM.code DataCodeEnum.OMDB_NODE_FORM.code
} else { } else {
Log.e( // Log.e(
"qj", // "qj",
"过滤不显示数据${renderEntity.table}" // "过滤不显示数据${renderEntity.table}"
) // )
line = bufferedReader.readLine()
continue continue
} }
} else if (renderEntity.table == DataCodeEnum.OMDB_NODE_PA.name) {//特殊处理因为code相同使用表名判断 } else if (renderEntity.table == DataCodeEnum.OMDB_NODE_PA.name) {//特殊处理因为code相同使用表名判断
//过滤不需要渲染的要素 //过滤不需要渲染的要素
var attributeType = val attributeType =
renderEntity.properties["attributeType"] renderEntity.properties["attributeType"]
if (attributeType != null && attributeType.toInt() == 30) { if (attributeType != null && attributeType.toInt() == 30) {
renderEntity.enable = 2 renderEntity.enable = 2
renderEntity.code = renderEntity.code =
DataCodeEnum.OMDB_NODE_PA.code DataCodeEnum.OMDB_NODE_PA.code
} else { } else {
Log.e( // Log.e(
"qj", // "qj",
"过滤不显示数据${renderEntity.table}" // "过滤不显示数据${renderEntity.table}"
) // )
line = bufferedReader.readLine()
continue continue
} }
} }
} }
Log.d("ImportOMDBHelper", "解析===2子code处理") // Log.d("ImportOMDBHelper", "解析===2子code处理")
++insertIndex ++insertIndex
Log.e("qj", "统计==${insertIndex}") Log.e("qj", "统计==${insertIndex}")
@ -746,58 +762,77 @@ class ImportOMDBHelper @AssistedInject constructor(
if (renderEntity.properties.containsKey("geometry")) { if (renderEntity.properties.containsKey("geometry")) {
renderEntity.properties.remove("geometry") renderEntity.properties.remove("geometry")
} }
Log.d("ImportOMDBHelper", "解析===1insert")
Realm.getInstance(currentInstallTaskConfig) //移除该字段,减少数据量
.insert(renderEntity) if (renderEntity.properties.containsKey("linkPid")) {
Log.d("ImportOMDBHelper", "解析===2insert") renderEntity.properties.remove("linkPid")
if (currentConfig.code == DataCodeEnum.OMDB_RD_LINK.code.toInt()) {
listResult.add(renderEntity)
}
}
}
}
} }
// 如果当前解析的是OMDB_RD_LINK数据将其缓存在预处理类中以便后续处理其他要素时使用 // 如果当前解析的是OMDB_RD_LINK数据将其缓存在预处理类中以便后续处理其他要素时使用
if (currentConfig.code == DataCodeEnum.OMDB_RD_LINK.code.toInt()) { if (currentConfig.code == DataCodeEnum.OMDB_RD_LINK.code.toInt()) {
importConfig.preProcess.cacheRdLink = if (renderEntity.linkRelation == null) {
listResult.associateBy { it.properties["linkPid"] } renderEntity.linkRelation = LinkRelation()
}
renderEntity.linkRelation!!.linkPid =
renderEntity.linkPid
renderEntity.linkRelation!!.sNodeId =
renderEntity.properties["snodePid"]
renderEntity.linkRelation!!.eNodeId =
renderEntity.properties["enodePid"]
}
renderEntity.propertiesDb = StrZipUtil.compress(
gson.toJson(renderEntity.properties).toString()
)
listRenderEntity.add(renderEntity)
}
if (listRenderEntity.size > 10000) {
Log.e(
"jingo", "10000刷新"
)
realm.copyToRealm(listRenderEntity)
realm.commitTransaction()
realm.close()
listRenderEntity.clear()
insertIndex = 0
// Realm.compactRealm(currentInstallTaskConfig)
realm = Realm.getInstance(currentInstallTaskConfig)
realm.beginTransaction()
}
line = bufferedReader.readLine()
}
bufferedReader.close()
} }
// 1个文件发送一次flow流 // 1个文件发送一次flow流
emit("${processIndex}/${tableNum}") emit("${processIndex}/${tableNum}")
Log.d("ImportOMDBHelper", "表解析===2${currentConfig.table}") // Log.d("ImportOMDBHelper", "表解析===2${currentConfig.table}")
Log.d( // Log.d(
"ImportOMDBHelper", // "ImportOMDBHelper",
"表解析===结束用时时间${(System.currentTimeMillis() - tableImportTime)}===${currentEntry.value.table}===$elementIndex" // "表解析===结束用时时间${(System.currentTimeMillis() - tableImportTime)}===${currentEntry.value.table}===$elementIndex"
) // )
elementIndex = 0 elementIndex = 0
tableImportTime = System.currentTimeMillis() // tableImportTime = System.currentTimeMillis()
if (insertIndex % 20000 == 0) {
Log.d(
"ImportOMDBHelper",
"表解析===结束用时时间===事物开始"
)
Realm.getInstance(currentInstallTaskConfig).commitTransaction()
Realm.getInstance(currentInstallTaskConfig).beginTransaction()
Log.d(
"ImportOMDBHelper",
"表解析===结束用时时间===事物结束"
)
} }
} }
}
Realm.getInstance(currentInstallTaskConfig).commitTransaction() realm.copyToRealm(listRenderEntity)
Realm.getInstance(currentInstallTaskConfig).close() realm.commitTransaction()
Log.d(
"ImportOMDBHelper", realm.close()
"表解析===结束用时时间${(System.currentTimeMillis() - dataImportTime)}===$dataIndex===插入$insertIndex" listRenderEntity.clear()
) // Log.d(
// "ImportOMDBHelper",
// "表解析===结束用时时间${(System.currentTimeMillis() - dataImportTime)}===$dataIndex===插入$insertIndex"
// )
Log.e("qj", "安装结束") Log.e("qj", "安装结束")
} catch (e: Exception) { } catch (e: Exception) {
if (Realm.getInstance(currentInstallTaskConfig).isInTransaction) { if (realm.isInTransaction) {
Realm.getInstance(currentInstallTaskConfig).cancelTransaction() realm.cancelTransaction()
realm.close()
} }
Log.e("ImportOMDBHelper", "安装失败", e)
throw e throw e
} }
emit("finish") emit("finish")

View File

@ -1,10 +1,13 @@
package com.navinfo.omqs.db package com.navinfo.omqs.db
import android.util.Log import android.util.Log
import com.google.gson.Gson
import com.navinfo.collect.library.data.entity.LinkRelation
import com.navinfo.collect.library.data.entity.ReferenceEntity import com.navinfo.collect.library.data.entity.ReferenceEntity
import com.navinfo.collect.library.data.entity.RenderEntity import com.navinfo.collect.library.data.entity.RenderEntity
import com.navinfo.collect.library.enums.DataCodeEnum import com.navinfo.collect.library.enums.DataCodeEnum
import com.navinfo.collect.library.utils.GeometryTools import com.navinfo.collect.library.utils.GeometryTools
import com.navinfo.collect.library.utils.StrZipUtil
import com.navinfo.omqs.Constant import com.navinfo.omqs.Constant
import io.realm.Realm import io.realm.Realm
import io.realm.RealmModel import io.realm.RealmModel
@ -15,20 +18,33 @@ import org.locationtech.jts.geom.Coordinate
import org.locationtech.jts.geom.Geometry import org.locationtech.jts.geom.Geometry
import org.locationtech.jts.io.WKTWriter import org.locationtech.jts.io.WKTWriter
import org.oscim.core.GeoPoint import org.oscim.core.GeoPoint
import java.util.*
class ImportPreProcess { class ImportPreProcess {
val code2NameMap = Code2NameMap() val code2NameMap = Code2NameMap()
lateinit var cacheRdLink: Map<String?, RenderEntity>
// lateinit var cacheRdLink: Map<String?, RenderEntity>
val defaultTranslateDistance = 3.0 val defaultTranslateDistance = 3.0
val testFlag: Boolean = false val testFlag: Boolean = false
var realm: Realm? = null var realm: Realm? = null
val gson = Gson()
fun checkCircleRoad(renderEntity: RenderEntity): Boolean { fun checkCircleRoad(renderEntity: RenderEntity): Boolean {
val linkInId = renderEntity.properties["linkIn"] val linkInId = renderEntity.properties["linkIn"]
val linkOutId = renderEntity.properties["linkOut"] val linkOutId = renderEntity.properties["linkOut"]
// 根据linkIn和linkOut获取对应的link数据 // // 根据linkIn和linkOut获取对应的link数据
val linkInEntity = cacheRdLink[linkInId] // val linkInEntity = cacheRdLink[linkInId]
val linkOutEntity = cacheRdLink[linkOutId] // val linkOutEntity = cacheRdLink[linkOutId]
realm?.let {
val linkInEntity = it.where(RenderEntity::class.java)
.equalTo("code", DataCodeEnum.OMDB_RD_LINK.code)
.and().equalTo("linkPid", linkInId)
.findFirst()
val linkOutEntity = it.where(RenderEntity::class.java)
.equalTo("code", DataCodeEnum.OMDB_RD_LINK.code)
.and().equalTo("linkPid", linkOutId)
.findFirst()
Log.d( Log.d(
"checkCircleRoad", "checkCircleRoad",
"LinkInEntity: ${linkInId}- ${linkInEntity?.properties?.get("snodePid")}LinkOutEntity: ${linkOutId}- ${ "LinkInEntity: ${linkInId}- ${linkInEntity?.properties?.get("snodePid")}LinkOutEntity: ${linkOutId}- ${
@ -41,6 +57,7 @@ class ImportPreProcess {
return false return false
} }
} }
}
return true return true
} }
@ -200,16 +217,16 @@ class ImportPreProcess {
startGeometry!!.coordinates[startGeometry.numPoints - 1] // 获取这个geometry对应的结束点坐标 startGeometry!!.coordinates[startGeometry.numPoints - 1] // 获取这个geometry对应的结束点坐标
if (translateGeometry.geometryType == Geometry.TYPENAME_LINESTRING) { // 如果是线数据,则取倒数第二个点作为偏移的起止点 if (translateGeometry.geometryType == Geometry.TYPENAME_LINESTRING) { // 如果是线数据,则取倒数第二个点作为偏移的起止点
pointEnd = pointEnd =
translateGeometry!!.coordinates[translateGeometry.numPoints - 2] // 获取这个geometry对应的结束点坐标 translateGeometry.coordinates[translateGeometry.numPoints - 2] // 获取这个geometry对应的结束点坐标
} }
if (startGeometry.geometryType == Geometry.TYPENAME_LINESTRING) { // 如果是线数据,则取倒数第二个点作为偏移的起止点 if (startGeometry.geometryType == Geometry.TYPENAME_LINESTRING) { // 如果是线数据,则取倒数第二个点作为偏移的起止点
pointStart = pointStart =
startGeometry!!.coordinates[startGeometry.numPoints - 2] // 获取这个geometry对应的结束点坐标 startGeometry.coordinates[startGeometry.numPoints - 2] // 获取这个geometry对应的结束点坐标
} }
// 将这个起终点的线记录在数据中 // 将这个起终点的线记录在数据中
val startEndReference = ReferenceEntity() val startEndReference = ReferenceEntity()
startEndReference.renderEntityId = renderEntity.id // startEndReference.renderEntityId = renderEntity.id
startEndReference.name = "${renderEntity.name}参考线" startEndReference.name = "${renderEntity.name}参考线"
startEndReference.table = renderEntity.table startEndReference.table = renderEntity.table
startEndReference.zoomMin = renderEntity.zoomMin startEndReference.zoomMin = renderEntity.zoomMin
@ -222,6 +239,9 @@ class ImportPreProcess {
startEndReference.properties["qi_table"] = renderEntity.table startEndReference.properties["qi_table"] = renderEntity.table
startEndReference.properties["type"] = "s_2_e" startEndReference.properties["type"] = "s_2_e"
val listResult = mutableListOf<ReferenceEntity>() val listResult = mutableListOf<ReferenceEntity>()
startEndReference.propertiesDb = StrZipUtil.compress(
gson.toJson(startEndReference.properties).toString()
)
listResult.add(startEndReference) listResult.add(startEndReference)
insertData(listResult) insertData(listResult)
} }
@ -240,7 +260,7 @@ class ImportPreProcess {
// 将这个起终点的线记录在数据中 // 将这个起终点的线记录在数据中
val startReference = ReferenceEntity() val startReference = ReferenceEntity()
startReference.renderEntityId = renderEntity.id // startReference.renderEntityId = renderEntity.id
startReference.name = "${renderEntity.name}参考点" startReference.name = "${renderEntity.name}参考点"
startReference.code = renderEntity.code startReference.code = renderEntity.code
startReference.table = renderEntity.table startReference.table = renderEntity.table
@ -258,7 +278,7 @@ class ImportPreProcess {
listResult.add(startReference) listResult.add(startReference)
val endReference = ReferenceEntity() val endReference = ReferenceEntity()
endReference.renderEntityId = renderEntity.id // endReference.renderEntityId = renderEntity.id
endReference.name = "${renderEntity.name}参考点" endReference.name = "${renderEntity.name}参考点"
endReference.code = renderEntity.code endReference.code = renderEntity.code
endReference.table = renderEntity.table endReference.table = renderEntity.table
@ -292,7 +312,7 @@ class ImportPreProcess {
// 将这个起终点的线记录在数据中 // 将这个起终点的线记录在数据中
val startReference = ReferenceEntity() val startReference = ReferenceEntity()
startReference.renderEntityId = renderEntity.id // startReference.renderEntityId = renderEntity.id
startReference.name = "${renderEntity.name}参考点" startReference.name = "${renderEntity.name}参考点"
startReference.code = renderEntity.code startReference.code = renderEntity.code
startReference.table = renderEntity.table startReference.table = renderEntity.table
@ -324,12 +344,15 @@ class ImportPreProcess {
Log.e("qj", "generateS2EReferencePoint===${startReference.geometry}") Log.e("qj", "generateS2EReferencePoint===${startReference.geometry}")
startReference.properties["geometry"] = startReference.geometry startReference.properties["geometry"] = startReference.geometry
startReference.propertiesDb = StrZipUtil.compress(
gson.toJson(startReference.properties).toString()
)
listResult.add(startReference) listResult.add(startReference)
Log.e("qj", "generateS2EReferencePoint===1") Log.e("qj", "generateS2EReferencePoint===1")
val endReference = ReferenceEntity() val endReference = ReferenceEntity()
endReference.renderEntityId = renderEntity.id // endReference.renderEntityId = renderEntity.id
endReference.name = "${renderEntity.name}参考点" endReference.name = "${renderEntity.name}参考点"
endReference.code = renderEntity.code endReference.code = renderEntity.code
endReference.table = renderEntity.table endReference.table = renderEntity.table
@ -358,7 +381,9 @@ class ImportPreProcess {
Log.e("qj", "generateS2EReferencePoint===e_2_p${renderEntity.name}") Log.e("qj", "generateS2EReferencePoint===e_2_p${renderEntity.name}")
} }
endReference.properties["geometry"] = endReference.geometry endReference.properties["geometry"] = endReference.geometry
endReference.propertiesDb = StrZipUtil.compress(
gson.toJson(endReference.properties).toString()
)
listResult.add(endReference) listResult.add(endReference)
Log.e("qj", "generateS2EReferencePoint===4") Log.e("qj", "generateS2EReferencePoint===4")
insertData(listResult) insertData(listResult)
@ -444,7 +469,7 @@ class ImportPreProcess {
val coorEnd = Coordinate(pointStart.getX() + dx, pointStart.getY() + dy, pointStart.z) val coorEnd = Coordinate(pointStart.getX() + dx, pointStart.getY() + dy, pointStart.z)
val angleReference = ReferenceEntity() val angleReference = ReferenceEntity()
angleReference.renderEntityId = renderEntity.id // angleReference.renderEntityId = renderEntity.id
angleReference.name = "${renderEntity.name}参考方向" angleReference.name = "${renderEntity.name}参考方向"
angleReference.table = renderEntity.table angleReference.table = renderEntity.table
angleReference.zoomMin = renderEntity.zoomMin angleReference.zoomMin = renderEntity.zoomMin
@ -456,6 +481,9 @@ class ImportPreProcess {
WKTWriter(3).write(GeometryTools.createLineString(arrayOf(pointStart, coorEnd))) WKTWriter(3).write(GeometryTools.createLineString(arrayOf(pointStart, coorEnd)))
angleReference.properties["qi_table"] = renderEntity.table angleReference.properties["qi_table"] = renderEntity.table
angleReference.properties["type"] = "angle" angleReference.properties["type"] = "angle"
angleReference.propertiesDb = StrZipUtil.compress(
gson.toJson(angleReference.properties).toString()
)
listResult.add(angleReference) listResult.add(angleReference)
} }
insertData(listResult) insertData(listResult)
@ -593,7 +621,7 @@ class ImportPreProcess {
for (i in 0 until laneInfoDirectArray.length()) { for (i in 0 until laneInfoDirectArray.length()) {
// 根据后续的数据生成辅助表数据 // 根据后续的数据生成辅助表数据
val referenceEntity = ReferenceEntity() val referenceEntity = ReferenceEntity()
referenceEntity.renderEntityId = renderEntity.id // referenceEntity.renderEntityId = renderEntity.id
referenceEntity.name = "${renderEntity.name}参考方向" referenceEntity.name = "${renderEntity.name}参考方向"
referenceEntity.table = renderEntity.table referenceEntity.table = renderEntity.table
referenceEntity.enable = renderEntity.enable referenceEntity.enable = renderEntity.enable
@ -601,7 +629,7 @@ class ImportPreProcess {
referenceEntity.zoomMin = renderEntity.zoomMin referenceEntity.zoomMin = renderEntity.zoomMin
referenceEntity.zoomMax = renderEntity.zoomMax referenceEntity.zoomMax = renderEntity.zoomMax
// 与原数据使用相同的geometry // 与原数据使用相同的geometry
referenceEntity.geometry = renderEntity.geometry.toString() referenceEntity.geometry = renderEntity.geometry
referenceEntity.properties["qi_table"] = renderEntity.table referenceEntity.properties["qi_table"] = renderEntity.table
referenceEntity.properties["currentDirect"] = referenceEntity.properties["currentDirect"] =
laneInfoDirectArray[i].toString().split(",").distinct().joinToString("_") laneInfoDirectArray[i].toString().split(",").distinct().joinToString("_")
@ -612,6 +640,9 @@ class ImportPreProcess {
referenceEntity.properties["symbol"] = referenceEntity.properties["symbol"] =
"assets:omdb/4601/${type}/1301_${referenceEntity.properties["currentDirect"]}.svg" "assets:omdb/4601/${type}/1301_${referenceEntity.properties["currentDirect"]}.svg"
Log.d("unpackingLaneInfo", referenceEntity.properties["symbol"].toString()) Log.d("unpackingLaneInfo", referenceEntity.properties["symbol"].toString())
referenceEntity.propertiesDb = StrZipUtil.compress(
gson.toJson(referenceEntity.properties).toString()
)
listResult.add(referenceEntity) listResult.add(referenceEntity)
} }
insertData(listResult) insertData(listResult)
@ -706,7 +737,7 @@ class ImportPreProcess {
fun generateAddWidthLine(renderEntity: RenderEntity) { fun generateAddWidthLine(renderEntity: RenderEntity) {
// 添加车道中心面渲染原则,根据车道宽度进行渲染 // 添加车道中心面渲染原则,根据车道宽度进行渲染
val angleReference = ReferenceEntity() val angleReference = ReferenceEntity()
angleReference.renderEntityId = renderEntity.id // angleReference.renderEntityId = renderEntity.id
angleReference.name = "${renderEntity.name}车道中线面" angleReference.name = "${renderEntity.name}车道中线面"
angleReference.table = renderEntity.table angleReference.table = renderEntity.table
angleReference.geometry = angleReference.geometry =
@ -719,6 +750,9 @@ class ImportPreProcess {
angleReference.taskId = renderEntity.taskId angleReference.taskId = renderEntity.taskId
angleReference.enable = renderEntity.enable angleReference.enable = renderEntity.enable
val listResult = mutableListOf<ReferenceEntity>() val listResult = mutableListOf<ReferenceEntity>()
angleReference.propertiesDb = StrZipUtil.compress(
gson.toJson(angleReference.properties).toString()
)
listResult.add(angleReference) listResult.add(angleReference)
insertData(listResult) insertData(listResult)
} }
@ -736,7 +770,7 @@ class ImportPreProcess {
for (i in 0 until nodeListJsonArray.length()) { for (i in 0 until nodeListJsonArray.length()) {
val nodeJSONObject = nodeListJsonArray.getJSONObject(i) val nodeJSONObject = nodeListJsonArray.getJSONObject(i)
val intersectionReference = ReferenceEntity() val intersectionReference = ReferenceEntity()
intersectionReference.renderEntityId = renderEntity.id // intersectionReference.renderEntityId = renderEntity.id
intersectionReference.name = "${renderEntity.name}参考点" intersectionReference.name = "${renderEntity.name}参考点"
intersectionReference.code = renderEntity.code intersectionReference.code = renderEntity.code
intersectionReference.table = renderEntity.table intersectionReference.table = renderEntity.table
@ -749,6 +783,9 @@ class ImportPreProcess {
GeometryTools.createGeometry(nodeJSONObject["geometry"].toString()).toString() GeometryTools.createGeometry(nodeJSONObject["geometry"].toString()).toString()
intersectionReference.properties["qi_table"] = renderEntity.table intersectionReference.properties["qi_table"] = renderEntity.table
intersectionReference.properties["type"] = "node" intersectionReference.properties["type"] = "node"
intersectionReference.propertiesDb = StrZipUtil.compress(
gson.toJson(intersectionReference.properties).toString()
)
listResult.add(intersectionReference) listResult.add(intersectionReference)
} }
insertData(listResult) insertData(listResult)
@ -903,7 +940,7 @@ class ImportPreProcess {
val coorEnd = Coordinate(pointStart.getX() + dx, pointStart.getY() + dy, pointStart.z) val coorEnd = Coordinate(pointStart.getX() + dx, pointStart.getY() + dy, pointStart.z)
val dynamicSrcReference = ReferenceEntity() val dynamicSrcReference = ReferenceEntity()
dynamicSrcReference.renderEntityId = renderEntity.id // dynamicSrcReference.renderEntityId = renderEntity.id
dynamicSrcReference.name = "${renderEntity.name}动态icon" dynamicSrcReference.name = "${renderEntity.name}动态icon"
dynamicSrcReference.table = renderEntity.table dynamicSrcReference.table = renderEntity.table
dynamicSrcReference.zoomMin = renderEntity.zoomMin dynamicSrcReference.zoomMin = renderEntity.zoomMin
@ -917,19 +954,24 @@ class ImportPreProcess {
dynamicSrcReference.properties["type"] = "dynamicSrc" dynamicSrcReference.properties["type"] = "dynamicSrc"
val code = renderEntity.properties[codeName] val code = renderEntity.properties[codeName]
dynamicSrcReference.properties["src"] = "${prefix}${code}${suffix}" dynamicSrcReference.properties["src"] = "${prefix}${code}${suffix}"
dynamicSrcReference.propertiesDb = StrZipUtil.compress(
gson.toJson(dynamicSrcReference.properties).toString()
)
listResult.add(dynamicSrcReference) listResult.add(dynamicSrcReference)
} }
insertData(listResult) insertData(listResult)
} }
private fun insertData(list: List<RealmModel>) { private fun insertData(list: List<RealmModel>) {
realm?.let {
Log.e("qj", "子表插入==") Log.e("qj", "子表插入==")
if (list != null && list.isNotEmpty()) { if (list != null && list.isNotEmpty()) {
Log.e("qj", "子表插入开始==") Log.e("qj", "子表插入开始==")
Realm.getInstance(Constant.currentInstallTaskConfig).insert(list) it.copyToRealm(list)
Log.e("qj", "子表插入结束==") Log.e("qj", "子表插入结束==")
} }
} }
}
/** /**
* 向当前renderEntity中添加动态属性 * 向当前renderEntity中添加动态属性

View File

@ -6,7 +6,6 @@ import androidx.annotation.RequiresApi
import com.navinfo.collect.library.data.entity.HadLinkDvoBean import com.navinfo.collect.library.data.entity.HadLinkDvoBean
import com.navinfo.collect.library.data.entity.QsRecordBean import com.navinfo.collect.library.data.entity.QsRecordBean
import com.navinfo.collect.library.data.entity.RenderEntity import com.navinfo.collect.library.data.entity.RenderEntity
import com.navinfo.collect.library.data.entity.RenderEntity.Companion.LinkTable
import com.navinfo.collect.library.enums.DataCodeEnum import com.navinfo.collect.library.enums.DataCodeEnum
import com.navinfo.collect.library.map.NIMapController import com.navinfo.collect.library.map.NIMapController
import com.navinfo.collect.library.utils.GeometryTools import com.navinfo.collect.library.utils.GeometryTools
@ -65,13 +64,12 @@ class RealmOperateHelper() {
val yEnd = tileYSet.stream().max(Comparator.naturalOrder()).orElse(null) val yEnd = tileYSet.stream().max(Comparator.naturalOrder()).orElse(null)
// 查询realm中对应tile号的数据 // 查询realm中对应tile号的数据
// val realm = getSelectTaskRealmInstance() // val realm = getSelectTaskRealmInstance()
val sql =
" ((tileXMin <= $xStart and tileXMax >= $xStart) or (tileXMin <=$xEnd and tileXMax >=$xStart)) and ((tileYMin <= $yStart and tileYMax >= $yStart) or (tileYMin <=$yEnd and tileYMin >=$yStart))"
val realmList = val realmList =
getSelectTaskRealmTools(realm, RenderEntity::class.java, false) getSelectTaskRealmTools(realm, RenderEntity::class.java, false)
.equalTo("table", DataCodeEnum.OMDB_LINK_DIRECT.name) .equalTo("table", DataCodeEnum.OMDB_LINK_DIRECT.name)
.greaterThanOrEqualTo("tileX", xStart) .rawPredicate(sql)
.lessThanOrEqualTo("tileX", xEnd)
.greaterThanOrEqualTo("tileY", yStart)
.lessThanOrEqualTo("tileY", yEnd)
.findAll() .findAll()
// 将获取到的数据和查询的polygon做相交只返回相交的数据 // 将获取到的数据和查询的polygon做相交只返回相交的数据
val dataList = realm.copyFromRealm(realmList) val dataList = realm.copyFromRealm(realmList)
@ -133,12 +131,11 @@ class RealmOperateHelper() {
val yEnd = tileYSet.stream().max(Comparator.naturalOrder()).orElse(null) val yEnd = tileYSet.stream().max(Comparator.naturalOrder()).orElse(null)
// 查询realm中对应tile号的数据 // 查询realm中对应tile号的数据
val realm = getSelectTaskRealmInstance() val realm = getSelectTaskRealmInstance()
val sql =
" ((tileXMin <= $xStart and tileXMax >= $xStart) or (tileXMin <=$xEnd and tileXMax >=$xStart)) and ((tileYMin <= $yStart and tileYMax >= $yStart) or (tileYMin <=$yEnd and tileYMin >=$yStart))"
val realmList = getSelectTaskRealmTools(realm, RenderEntity::class.java, true) val realmList = getSelectTaskRealmTools(realm, RenderEntity::class.java, true)
.equalTo("table", table) .equalTo("table", table)
.greaterThanOrEqualTo("tileX", xStart) .rawPredicate(sql)
.lessThanOrEqualTo("tileX", xEnd)
.greaterThanOrEqualTo("tileY", yStart)
.lessThanOrEqualTo("tileY", yEnd)
.findAll() .findAll()
// 将获取到的数据和查询的polygon做相交只返回相交的数据 // 将获取到的数据和查询的polygon做相交只返回相交的数据
val dataList = realm.copyFromRealm(realmList) val dataList = realm.copyFromRealm(realmList)
@ -178,7 +175,8 @@ class RealmOperateHelper() {
) )
val realm = getRealmDefaultInstance() val realm = getRealmDefaultInstance()
try { try {
val realmList = realm.where(HadLinkDvoBean::class.java).equalTo("taskId", taskId).findAll() val realmList =
realm.where(HadLinkDvoBean::class.java).equalTo("taskId", taskId).findAll()
var linkBean: HadLinkDvoBean? = null var linkBean: HadLinkDvoBean? = null
var nearLast: Double = 99999.99 var nearLast: Double = 99999.99
for (link in realmList) { for (link in realmList) {
@ -206,7 +204,7 @@ class RealmOperateHelper() {
val realm = getSelectTaskRealmInstance() val realm = getSelectTaskRealmInstance()
val realmR = val realmR =
realm.where(RenderEntity::class.java).equalTo("table", "OMDB_RD_LINK_KIND") realm.where(RenderEntity::class.java).equalTo("table", "OMDB_RD_LINK_KIND")
.equalTo("properties['${LinkTable.linkPid}']", linkPid).findFirst() .equalTo("linkPid", linkPid).findFirst()
if (realmR != null) { if (realmR != null) {
link = realm.copyFromRealm(realmR) link = realm.copyFromRealm(realmR)
} }
@ -238,7 +236,7 @@ class RealmOperateHelper() {
// val realm = getSelectTaskRealmInstance() // val realm = getSelectTaskRealmInstance()
val realmR = getSelectTaskRealmTools(realm, RenderEntity::class.java, true) val realmR = getSelectTaskRealmTools(realm, RenderEntity::class.java, true)
.equalTo("properties['${LinkTable.linkPid}']", linkPid).findAll() .equalTo("linkPid", linkPid).findAll()
val dataList = realm.copyFromRealm(realmR) val dataList = realm.copyFromRealm(realmR)
@ -284,11 +282,11 @@ class RealmOperateHelper() {
val yEnd = tileYSet.stream().max(Comparator.naturalOrder()).orElse(null) val yEnd = tileYSet.stream().max(Comparator.naturalOrder()).orElse(null)
val realm = getSelectTaskRealmInstance() val realm = getSelectTaskRealmInstance()
var realmList = mutableListOf<RenderEntity>() var realmList = mutableListOf<RenderEntity>()
val sql =
" ((tileXMin <= $xStart and tileXMax >= $xStart) or (tileXMin <=$xEnd and tileXMax >=$xStart)) and ((tileYMin <= $yStart and tileYMax >= $yStart) or (tileYMin <=$yEnd and tileYMin >=$yStart))"
val realmQuery = getSelectTaskRealmTools(realm, RenderEntity::class.java, false) val realmQuery = getSelectTaskRealmTools(realm, RenderEntity::class.java, false)
.greaterThanOrEqualTo("tileX", xStart) .rawPredicate(sql)
.lessThanOrEqualTo("tileX", xEnd)
.greaterThanOrEqualTo("tileY", yStart)
.lessThanOrEqualTo("tileY", yEnd)
// 筛选不显示的数据 // 筛选不显示的数据
if (catchAll) { if (catchAll) {
// 查询realm中对应tile号的数据 // 查询realm中对应tile号的数据
@ -333,7 +331,7 @@ class RealmOperateHelper() {
val result = mutableListOf<RenderEntity>() val result = mutableListOf<RenderEntity>()
val realmList = getSelectTaskRealmTools(realm, RenderEntity::class.java, false) val realmList = getSelectTaskRealmTools(realm, RenderEntity::class.java, false)
.notEqualTo("table", DataCodeEnum.OMDB_RD_LINK.name) .notEqualTo("table", DataCodeEnum.OMDB_RD_LINK.name)
.equalTo("properties['${LinkTable.linkPid}']", linkPid) .equalTo("linkPid", linkPid)
.findAll() .findAll()
result.addAll(realm.copyFromRealm(realmList)) result.addAll(realm.copyFromRealm(realmList))
return result return result

View File

@ -154,20 +154,6 @@ class GlobalModule {
) )
} }
// /**
// * realm 注册
// */
// @Provides
// @Singleton
// fun provideRealmService(context: Application): RealmCoroutineScope {
// return RealmCoroutineScope(context)
// }
// @Singleton
// @Provides
// fun provideRealmDefaultInstance(): Realm {
// return Realm.getDefaultInstance()
// }
@Singleton @Singleton
@Provides @Provides

View File

@ -1,7 +1,5 @@
package com.navinfo.omqs.ui.activity.login package com.navinfo.omqs.ui.activity.login
import android.app.Activity
import android.app.ActivityManager
import android.content.Intent import android.content.Intent
import android.os.Bundle import android.os.Bundle
import android.util.DisplayMetrics import android.util.DisplayMetrics
@ -11,7 +9,6 @@ import androidx.activity.viewModels
import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AlertDialog
import androidx.databinding.DataBindingUtil import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer import androidx.lifecycle.Observer
import androidx.lifecycle.viewModelScope
import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.navinfo.omqs.R import com.navinfo.omqs.R
import com.navinfo.omqs.databinding.ActivityLoginBinding import com.navinfo.omqs.databinding.ActivityLoginBinding
@ -19,8 +16,6 @@ import com.navinfo.omqs.ui.activity.CheckPermissionsActivity
import com.navinfo.omqs.ui.activity.map.MainActivity import com.navinfo.omqs.ui.activity.map.MainActivity
import com.umeng.commonsdk.UMConfigure import com.umeng.commonsdk.UMConfigure
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
/** /**
* 登陆页面 * 登陆页面

View File

@ -8,10 +8,13 @@ import android.widget.Toast
import androidx.lifecycle.MutableLiveData import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.blankj.utilcode.util.FileIOUtils import com.blankj.utilcode.util.FileIOUtils
import com.blankj.utilcode.util.ResourceUtils import com.blankj.utilcode.util.ResourceUtils
import com.google.gson.Gson import com.google.gson.Gson
import com.google.gson.reflect.TypeToken import com.google.gson.reflect.TypeToken
import com.navinfo.collect.library.data.entity.LinkRelation
import com.navinfo.collect.library.data.entity.RenderEntity import com.navinfo.collect.library.data.entity.RenderEntity
import com.navinfo.collect.library.data.entity.TaskBean import com.navinfo.collect.library.data.entity.TaskBean
import com.navinfo.collect.library.utils.GeometryTools import com.navinfo.collect.library.utils.GeometryTools
@ -27,6 +30,8 @@ import com.navinfo.omqs.util.DateTimeUtil
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import io.realm.Realm import io.realm.Realm
import io.realm.RealmConfiguration import io.realm.RealmConfiguration
import io.realm.RealmMigration
import io.realm.RealmSchema
import kotlinx.coroutines.* import kotlinx.coroutines.*
import java.io.File import java.io.File
import java.io.IOException import java.io.IOException
@ -442,8 +447,9 @@ class LoginViewModel @Inject constructor(
.directory(userFolder) .directory(userFolder)
.name("OMQS.realm") .name("OMQS.realm")
.encryptionKey(Constant.PASSWORD) .encryptionKey(Constant.PASSWORD)
.allowQueriesOnUiThread(true) // .allowQueriesOnUiThread(true)
.schemaVersion(2) .schemaVersion(3)
// .migration(migration)
.build() .build()
Realm.setDefaultConfiguration(config) Realm.setDefaultConfiguration(config)
// 拷贝配置文件到用户目录下 // 拷贝配置文件到用户目录下
@ -469,4 +475,17 @@ class LoginViewModel @Inject constructor(
private fun byteArrayToHexString(byteArray: ByteArray): String { private fun byteArrayToHexString(byteArray: ByteArray): String {
return byteArray.joinToString("") { "%02x".format(it) } return byteArray.joinToString("") { "%02x".format(it) }
} }
val migration : RealmMigration = RealmMigration {
realm, oldVersion, newVersion -> {
if (oldVersion == 2L && newVersion == 3L) {
// DynamicRealm exposes an editable schema
val schema: RealmSchema = realm.schema
if (!schema.get("RenderEntity")!!.hasField("linkPid")) {
schema.get("RenderEntity")
?.addField("linkPid", String::class.java)
}
}
}
}
} }

View File

@ -51,7 +51,9 @@ import io.realm.Realm
import io.realm.RealmConfiguration import io.realm.RealmConfiguration
import io.realm.RealmSet import io.realm.RealmSet
import kotlinx.coroutines.* import kotlinx.coroutines.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.Mutex
import org.locationtech.jts.geom.Geometry import org.locationtech.jts.geom.Geometry
import org.oscim.core.GeoPoint import org.oscim.core.GeoPoint
@ -240,11 +242,14 @@ class MainViewModel @Inject constructor(
//导航信息 //导航信息
private var naviEngine: NaviEngine? = null private var naviEngine: NaviEngine? = null
private var naviEngineNew: NaviEngineNew = NaviEngineNew(realmOperateHelper)
// 0:不导航 1导航 2暂停 // 0:不导航 1导航 2暂停
private var naviEngineStatus = 0 private var naviEngineStatus = 0
// 定义一个互斥锁 // 定义一个互斥锁
private val naviMutex = Mutex() private val naviMutex = Mutex()
private var testRealm: Realm? = null;
private var traceCount = 0 private var traceCount = 0
@ -339,32 +344,45 @@ class MainViewModel @Inject constructor(
File(Constant.USER_DATA_PATH + "/${MapParamUtils.getTaskId()}") File(Constant.USER_DATA_PATH + "/${MapParamUtils.getTaskId()}")
Constant.currentSelectTaskConfig = Constant.currentSelectTaskConfig =
RealmConfiguration.Builder().directory(Constant.currentSelectTaskFolder) RealmConfiguration.Builder().directory(Constant.currentSelectTaskFolder)
.name("OMQS.realm").encryptionKey(Constant.PASSWORD).allowQueriesOnUiThread(true) .name("OMQS.realm").encryptionKey(Constant.PASSWORD)
// .assetFile("${Constant.currentSelectTaskFolder}/OMQS.realm")
// .readOnly()
// .allowQueriesOnUiThread(true)
.schemaVersion(2).build() .schemaVersion(2).build()
MapParamUtils.setTaskConfig(Constant.currentSelectTaskConfig) MapParamUtils.setTaskConfig(Constant.currentSelectTaskConfig)
socketServer = SocketServer(mapController, traceDataBase, sharedPreferences) socketServer = SocketServer(mapController, traceDataBase, sharedPreferences)
// viewModelScope.launch(Dispatchers.Default) { viewModelScope.launch(Dispatchers.IO) {
// naviTestFlow().collect { point ->
// if (naviEngineStatus == 1) { naviTestFlow().collect { point ->
// naviEngine?.let { if (naviEngineStatus == 1) {
naviEngineNew.let {
// naviMutex.lock() // naviMutex.lock()
if (testRealm == null)
testRealm = realmOperateHelper.getSelectTaskRealmInstance()
if (currentTaskBean != null) {
naviEngineNew.bindingRoute(
taskBean = currentTaskBean!!,
geoPoint = point,
realm = testRealm!!
)
}
// it.bindingRoute(null, point) // it.bindingRoute(null, point)
// naviMutex.unlock() // naviMutex.unlock()
// } }
// } }
// } }
// } }
} }
// fun naviTestFlow(): Flow<GeoPoint> = flow { fun naviTestFlow(): Flow<GeoPoint> = flow {
//
// while (true) { while (true) {
// emit(mapController.mMapView.vtmMap.mapPosition.geoPoint) emit(mapController.mMapView.vtmMap.mapPosition.geoPoint)
// delay(1000) delay(5000)
// } }
// } }
/** /**
* 获取当前任务 * 获取当前任务
@ -406,7 +424,10 @@ class MainViewModel @Inject constructor(
naviOption = naviOption, naviOption = naviOption,
callback = object : OnNaviEngineCallbackListener { callback = object : OnNaviEngineCallbackListener {
override fun planningPathStatus(status: NaviStatus) { override fun planningPathStatus(
status: NaviStatus, linkdId: String?,
geometry: String?
) {
when (status) { when (status) {
NaviStatus.NAVI_STATUS_PATH_PLANNING -> naviEngineStatus = 0 NaviStatus.NAVI_STATUS_PATH_PLANNING -> naviEngineStatus = 0
NaviStatus.NAVI_STATUS_PATH_ERROR_NODE -> naviEngineStatus = 0 NaviStatus.NAVI_STATUS_PATH_ERROR_NODE -> naviEngineStatus = 0
@ -418,7 +439,23 @@ class MainViewModel @Inject constructor(
NaviStatus.NAVI_STATUS_DIRECTION_OFF -> {} NaviStatus.NAVI_STATUS_DIRECTION_OFF -> {}
} }
liveDataNaviStatus.postValue(status) liveDataNaviStatus.postValue(status)
if (geometry != null) {
viewModelScope.launch(Dispatchers.Main) {
val lineString = GeometryTools.createGeometry(geometry)
val envelope = lineString.envelopeInternal
mapController.animationHandler.animateToBox(
envelope.maxX,
envelope.maxY,
envelope.minX,
envelope.minY
)
mapController.lineHandler.showLine(geometry)
} }
}
}
override suspend fun bindingResults( override suspend fun bindingResults(
route: NaviRoute?, route: NaviRoute?,
@ -805,7 +842,7 @@ class MainViewModel @Inject constructor(
if (linkList.isNotEmpty()) { if (linkList.isNotEmpty()) {
val link = linkList[0] val link = linkList[0]
val linkId = link.properties[RenderEntity.Companion.LinkTable.linkPid] val linkId = link.linkPid
//看板数据 //看板数据
val signList = mutableListOf<SignBean>() val signList = mutableListOf<SignBean>()
val topSignList = mutableListOf<SignBean>() val topSignList = mutableListOf<SignBean>()
@ -835,8 +872,12 @@ class MainViewModel @Inject constructor(
val newLineString = GeometryTools.createLineString(linePoints) val newLineString = GeometryTools.createLineString(linePoints)
linkId?.let { linkId?.let {
val time = System.currentTimeMillis()
val elementList = realmOperateHelper.queryLinkByLinkPid(realm, it) val elementList = realmOperateHelper.queryLinkByLinkPid(realm, it)
Log.e("jingo", "捕捉到数据 ${elementList.size}") Log.e(
"jingo",
"捕捉到数据 ${elementList.size}${System.currentTimeMillis() - time}"
)
for (element in elementList) { for (element in elementList) {
if (element.code == DataCodeEnum.OMDB_LINK_NAME.code) { if (element.code == DataCodeEnum.OMDB_LINK_NAME.code) {
hisRoadName = true hisRoadName = true
@ -949,7 +990,7 @@ class MainViewModel @Inject constructor(
.equalTo("table", DataCodeEnum.OMDB_RD_LINK_KIND.name) .equalTo("table", DataCodeEnum.OMDB_RD_LINK_KIND.name)
.and() .and()
.equalTo( .equalTo(
"properties['${RenderEntity.Companion.LinkTable.linkPid}']", "linkPid",
outLink outLink
).findFirst() ).findFirst()
if (linkOutEntity != null) { if (linkOutEntity != null) {
@ -983,6 +1024,7 @@ class MainViewModel @Inject constructor(
if (!hisRoadName) { if (!hisRoadName) {
liveDataRoadName.postValue(null) liveDataRoadName.postValue(null)
} }
Log.e("jingo", "另一个地方查询数据库")
realm.close() realm.close()
} }
} catch (e: Exception) { } catch (e: Exception) {
@ -1001,6 +1043,7 @@ class MainViewModel @Inject constructor(
mapPosition.setBearing(0f) // 锁定角度,自动将地图旋转到正北方向 mapPosition.setBearing(0f) // 锁定角度,自动将地图旋转到正北方向
mapController.mMapView.vtmMap.mapPosition = mapPosition mapController.mMapView.vtmMap.mapPosition = mapPosition
mapController.locationLayerHandler.animateToCurrentPosition() mapController.locationLayerHandler.animateToCurrentPosition()
naviEngineStatus = 1
} }
/** /**
@ -1677,7 +1720,7 @@ class MainViewModel @Inject constructor(
val tempTime = nowTime - lastTime val tempTime = nowTime - lastTime
if (tempTime > 10000) { if (tempTime > 10000) {
liveDataMessage.postValue("下个定位点与当前定位点时间间隔超过10秒(${tempTime}),将直接跳转到下个点") liveDataMessage.postValue("下个定位点与当前定位点时间间隔超过10秒(${tempTime}),将直接跳转到下个点")
delay(5000) delay(2000)
} else { } else {
delay(tempTime) delay(tempTime)
} }

View File

@ -23,7 +23,6 @@ import com.blankj.utilcode.util.ToastUtils
import com.navinfo.collect.library.data.entity.AttachmentBean import com.navinfo.collect.library.data.entity.AttachmentBean
import com.navinfo.collect.library.data.entity.HadLinkDvoBean import com.navinfo.collect.library.data.entity.HadLinkDvoBean
import com.navinfo.collect.library.data.entity.QsRecordBean import com.navinfo.collect.library.data.entity.QsRecordBean
import com.navinfo.collect.library.data.entity.RenderEntity.Companion.LinkTable
import com.navinfo.collect.library.data.entity.TaskBean import com.navinfo.collect.library.data.entity.TaskBean
import com.navinfo.collect.library.map.NIMapController import com.navinfo.collect.library.map.NIMapController
import com.navinfo.collect.library.map.OnGeoPointClickListener import com.navinfo.collect.library.map.OnGeoPointClickListener
@ -236,7 +235,7 @@ class EvaluationResultViewModel @Inject constructor(
} else { } else {
val linkList = realmOperateHelper.queryLink(realm, point = point) val linkList = realmOperateHelper.queryLink(realm, point = point)
if (linkList.isNotEmpty()) { if (linkList.isNotEmpty()) {
it.linkId = linkList[0].properties[LinkTable.linkPid] ?: "" it.linkId = linkList[0].linkPid
mapController.lineHandler.showLine(linkList[0].geometry) mapController.lineHandler.showLine(linkList[0].geometry)
Log.e("jingo", "捕捉道路EEE 2") Log.e("jingo", "捕捉道路EEE 2")
return return

View File

@ -146,7 +146,7 @@ class TaskViewModel @Inject constructor(
if (links.isNotEmpty()) { if (links.isNotEmpty()) {
val l = links[0] val l = links[0]
for (link in currentSelectTaskBean!!.hadLinkDvoList) { for (link in currentSelectTaskBean!!.hadLinkDvoList) {
if (link.linkPid == l.properties["linkPid"]) { if (link.linkPid == l.linkPid) {
return@launch return@launch
} }
} }
@ -165,7 +165,7 @@ class TaskViewModel @Inject constructor(
if (links.isNotEmpty()) { if (links.isNotEmpty()) {
val l = links[0] val l = links[0]
for (link in currentSelectTaskBean!!.hadLinkDvoList) { for (link in currentSelectTaskBean!!.hadLinkDvoList) {
if (link.linkPid == l.properties["linkPid"]) { if (link.linkPid == l.linkPid) {
liveDataSelectLink.postValue(link.linkPid) liveDataSelectLink.postValue(link.linkPid)
mapController.lineHandler.showLine(link.geometry) mapController.lineHandler.showLine(link.geometry)
break break
@ -382,6 +382,16 @@ class TaskViewModel @Inject constructor(
) )
} }
} }
//重新加载轨迹
viewModelScope.launch(Dispatchers.IO) {
val list: List<NiLocation>? = TraceDataBase.getDatabase(
mapController.mMapView.context, Constant.USER_DATA_PATH
).niLocationDao.findToTaskIdAll(taskBean.id.toString())
list!!.forEach {
mapController.markerHandle.addNiLocationMarkerItem(it)
}
}
} }
/** /**
@ -463,71 +473,6 @@ class TaskViewModel @Inject constructor(
} }
} }
/**
* 重新下载数据任务
*/
fun resetDownload(context: Context, taskBean: TaskBean) {
val mDialog = FirstDialog(context)
mDialog.setTitle("提示?")
mDialog.setMessage("是否重置下载状态,请确认!")
mDialog.setPositiveButton(
"确定"
) { dialog, _ ->
dialog.dismiss()
liveDataCloseTask.postValue(TaskDelStatus.TASK_DEL_STATUS_BEGIN)
viewModelScope.launch(Dispatchers.IO) {
//删除已下载的数据
val fileTemp =
File("${Constant.DOWNLOAD_PATH}${taskBean.evaluationTaskName}_${taskBean.dataVersion}.zip")
if (fileTemp.exists()) {
fileTemp.delete()
}
val taskFileTemp = File(Constant.USER_DATA_PATH + "/${taskBean.id}")
//重命名
if (taskFileTemp.exists()) {
/* var currentSelectTaskFolder = File(Constant.USER_DATA_PATH + "/${taskBean.id}")
var currentSelectTaskConfig =
RealmConfiguration.Builder().directory(currentSelectTaskFolder)
.name("OMQS.realm").encryptionKey(Constant.PASSWORD)
.allowQueriesOnUiThread(true)
.schemaVersion(2).build()
Realm.getInstance(currentSelectTaskConfig).executeTransaction { r ->
//删除已有所有数据
r.delete(RenderEntity::class.java)
r.delete(ReferenceEntity::class.java)
}
Realm.getInstance(currentSelectTaskConfig).close()*/
}
//将下载状态修改已下载
val realm = realmOperateHelper.getRealmDefaultInstance()
taskBean.syncStatus = FileManager.Companion.FileUploadStatus.NONE
taskBean.status = FileManager.Companion.FileDownloadStatus.NONE
realm.beginTransaction()
realm.copyToRealmOrUpdate(taskBean)
realm.commitTransaction()
realm.close()
liveDataCloseTask.postValue(TaskDelStatus.TASK_DEL_STATUS_SUCCESS)
withContext(Dispatchers.Main) {
if (taskBean.id == currentSelectTaskBean?.id ?: 0) {
mapController.layerManagerHandler.updateOMDBVectorTileLayer()
} else {
setSelectTaskBean(taskBean)
}
realmOperateHelper.getRealmDefaultInstance().refresh()
//重新加载数据
getLocalTaskList()
}
}
}
mDialog.setNegativeButton(
"取消"
) { _, _ ->
liveDataCloseTask.postValue(TaskDelStatus.TASK_DEL_STATUS_CANCEL)
mDialog.dismiss()
}
mDialog.show()
}
/** /**
* 关闭任务 * 关闭任务
*/ */
@ -539,9 +484,7 @@ class TaskViewModel @Inject constructor(
"确定" "确定"
) { dialog, _ -> ) { dialog, _ ->
dialog.dismiss() dialog.dismiss()
liveDataCloseTask.postValue(TaskDelStatus.TASK_DEL_STATUS_BEGIN)
viewModelScope.launch(Dispatchers.IO) { viewModelScope.launch(Dispatchers.IO) {
liveDataCloseTask.postValue(TaskDelStatus.TASK_DEL_STATUS_LOADING)
val realm = realmOperateHelper.getRealmDefaultInstance() val realm = realmOperateHelper.getRealmDefaultInstance()
realm.executeTransaction { realm.executeTransaction {
val objects = val objects =
@ -575,14 +518,14 @@ class TaskViewModel @Inject constructor(
FileManager.checkOMDBFileInfo(item) FileManager.checkOMDBFileInfo(item)
} }
liveDataTaskList.postValue(taskList) liveDataTaskList.postValue(taskList)
liveDataCloseTask.postValue(TaskDelStatus.TASK_DEL_STATUS_SUCCESS) liveDataCloseTask.postValue(true)
realm.close() realm.close()
} }
} }
mDialog.setNegativeButton( mDialog.setNegativeButton(
"取消" "取消"
) { _, _ -> ) { _, _ ->
liveDataCloseTask.postValue(TaskDelStatus.TASK_DEL_STATUS_CANCEL) liveDataCloseTask.postValue(false)
mDialog.dismiss() mDialog.dismiss()
} }
mDialog.show() mDialog.show()
@ -679,7 +622,7 @@ class TaskViewModel @Inject constructor(
viewModelScope.launch(Dispatchers.IO) { viewModelScope.launch(Dispatchers.IO) {
val hadLinkDvoBean = HadLinkDvoBean( val hadLinkDvoBean = HadLinkDvoBean(
taskId = currentSelectTaskBean!!.id, taskId = currentSelectTaskBean!!.id,
linkPid = data.properties["linkPid"]!!, linkPid = data.linkPid,
geometry = data.geometry, geometry = data.geometry,
linkStatus = 2 linkStatus = 2
) )
@ -692,7 +635,7 @@ class TaskViewModel @Inject constructor(
r.copyToRealmOrUpdate(currentSelectTaskBean!!) r.copyToRealmOrUpdate(currentSelectTaskBean!!)
} }
//根据Link数据查询对应数据上要素对要素进行显示重置 //根据Link数据查询对应数据上要素对要素进行显示重置
data.properties["linkPid"]?.let { data.linkPid.let {
realmOperateHelper.queryLinkToMutableRenderEntityList(realm, it) realmOperateHelper.queryLinkToMutableRenderEntityList(realm, it)
?.forEach { renderEntity -> ?.forEach { renderEntity ->
if (renderEntity.enable != 1) { if (renderEntity.enable != 1) {

View File

@ -11,15 +11,17 @@ import com.navinfo.omqs.bean.NaviRoute
import com.navinfo.omqs.bean.NaviRouteItem import com.navinfo.omqs.bean.NaviRouteItem
import com.navinfo.omqs.db.RealmOperateHelper import com.navinfo.omqs.db.RealmOperateHelper
import io.realm.Realm import io.realm.Realm
import org.locationtech.jts.geom.Geometry
import org.locationtech.jts.geom.LineString import org.locationtech.jts.geom.LineString
import org.locationtech.jts.geom.Point import org.locationtech.jts.geom.Point
import org.oscim.core.GeoPoint import org.oscim.core.GeoPoint
interface OnNaviEngineCallbackListener { interface OnNaviEngineCallbackListener {
fun planningPathStatus(code: NaviStatus) fun planningPathStatus(code: NaviStatus, linkdId: String? = null, geometry: String? = null)
// fun planningPathError(errorCode: NaviStatus, errorMessage: String) // fun planningPathError(errorCode: NaviStatus, errorMessage: String)
suspend fun bindingResults(route: NaviRoute?, list: List<NaviRouteItem>) suspend fun bindingResults(route: NaviRoute?, list: List<NaviRouteItem>)
} }
enum class NaviStatus { enum class NaviStatus {
@ -206,9 +208,12 @@ class NaviEngine(
callback.planningPathStatus(NaviStatus.NAVI_STATUS_PATH_PLANNING) callback.planningPathStatus(NaviStatus.NAVI_STATUS_PATH_PLANNING)
val pathList = mutableListOf<NaviRoute>() val pathList = mutableListOf<NaviRoute>()
val realm = realmOperateHelper.getSelectTaskRealmInstance() val realm = realmOperateHelper.getSelectTaskRealmInstance()
for (link in taskBean.hadLinkDvoList) { Log.e("jingo", "路径计算 条数 ${taskBean.hadLinkDvoList.size}")
for (i in 0 until taskBean.hadLinkDvoList.size) {
val link = taskBean.hadLinkDvoList[i]
Log.e("jingo","获取 S E $i 总共 ${taskBean.hadLinkDvoList.size}")
//测线不参与导航 //测线不参与导航
if (link.linkStatus == 3) { if (link!!.linkStatus == 3) {
continue continue
} }
val route = NaviRoute( val route = NaviRoute(
@ -218,7 +223,7 @@ class NaviEngine(
route.pointList = GeometryTools.getGeoPoints(link.geometry) route.pointList = GeometryTools.getGeoPoints(link.geometry)
val res = realm.where(RenderEntity::class.java).`in`("table", QUERY_KEY_LINK_INFO_LIST) val res = realm.where(RenderEntity::class.java).`in`("table", QUERY_KEY_LINK_INFO_LIST)
.equalTo("properties['linkPid']", link.linkPid).findAll() .equalTo("linkPid", link.linkPid).findAll()
var bHasNode = false var bHasNode = false
var bHasDir = false var bHasDir = false
var bHasName = false var bHasName = false
@ -256,13 +261,17 @@ class NaviEngine(
} }
if (!bHasNode) { if (!bHasNode) {
callback.planningPathStatus( callback.planningPathStatus(
NaviStatus.NAVI_STATUS_PATH_ERROR_NODE NaviStatus.NAVI_STATUS_PATH_ERROR_NODE,
link.linkPid,
link.geometry
) )
return return
} }
if (!bHasDir) { if (!bHasDir) {
callback.planningPathStatus( callback.planningPathStatus(
NaviStatus.NAVI_STATUS_PATH_ERROR_DIRECTION NaviStatus.NAVI_STATUS_PATH_ERROR_DIRECTION,
link!!.linkPid,
link.geometry
) )
return return
} }
@ -347,7 +356,9 @@ class NaviEngine(
if (!bHasLast && !bHasNext) { if (!bHasLast && !bHasNext) {
bBreak = false bBreak = false
callback.planningPathStatus( callback.planningPathStatus(
NaviStatus.NAVI_STATUS_PATH_ERROR_BLOCKED NaviStatus.NAVI_STATUS_PATH_ERROR_BLOCKED,
tempRouteList[0].linkId,
GeometryTools.getLineString(tempRouteList[0].pointList)
) )
realm.close() realm.close()
return return
@ -357,11 +368,13 @@ class NaviEngine(
val itemMap: MutableMap<GeoPoint, MutableList<RenderEntity>> = mutableMapOf() val itemMap: MutableMap<GeoPoint, MutableList<RenderEntity>> = mutableMapOf()
//查询每根link上的关联要素 //查询每根link上的关联要素
for (route in newRouteList) { for (i in newRouteList.indices) {
val route = newRouteList[i]
Log.e("jingo","获取 插入要素 $i 总共 ${newRouteList.size}")
itemMap.clear() itemMap.clear()
//常规点限速 //常规点限速
val res = realm.where(RenderEntity::class.java) val res = realm.where(RenderEntity::class.java)
.equalTo("properties['linkPid']", route.linkId).and().`in`( .equalTo("linkPid", route.linkId).and().`in`(
"table", "table",
QUERY_KEY_ITEM_LIST QUERY_KEY_ITEM_LIST
).findAll() ).findAll()

View File

@ -0,0 +1,90 @@
package com.navinfo.omqs.util
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import com.navinfo.collect.library.data.entity.HadLinkDvoBean
import com.navinfo.collect.library.data.entity.NiLocation
import com.navinfo.collect.library.data.entity.RenderEntity
import com.navinfo.collect.library.data.entity.TaskBean
import com.navinfo.collect.library.enums.DataCodeEnum
import com.navinfo.collect.library.utils.FootAndDistance
import com.navinfo.collect.library.utils.GeometryTools
import com.navinfo.omqs.db.RealmOperateHelper
import io.realm.Realm
import org.oscim.core.GeoPoint
import java.time.LocalDate
import java.time.LocalDateTime
class NaviEngineNew(
private val realmOperateHelper: RealmOperateHelper,
) {
/**
* 要查询的link基本信息列表
*/
private val QUERY_KEY_LINK_INFO_LIST = arrayOf(
DataCodeEnum.OMDB_RD_LINK.name,
DataCodeEnum.OMDB_LINK_DIRECT.name,
DataCodeEnum.OMDB_LINK_NAME.name,
)
private val locationList = mutableListOf<NiLocation>()
suspend fun bindingRoute(
niLocation: NiLocation? = null,
taskBean: TaskBean,
geoPoint: GeoPoint,
realm:Realm
) {
// val geoPoint = GeoPoint(niLocation.latitude, niLocation.longitude)
var latestRoute: HadLinkDvoBean? = null
var lastDis = -1.0
for (link in taskBean.hadLinkDvoList) {
val linkGeometry = GeometryTools.createGeometry(link.geometry)
val footAndDistance = GeometryTools.pointToLineDistance(geoPoint, linkGeometry)
val meterD = footAndDistance.getMeterDistance()
if (meterD < 15 && (lastDis < 0 || lastDis > meterD)) {
latestRoute = link
lastDis = meterD
}
}
latestRoute?.let {
val res2 =
realm.where(RenderEntity::class.java).`in`("table", QUERY_KEY_LINK_INFO_LIST)
.equalTo("linkPid", it.linkPid).findAll()
if (res2 != null) {
for (entity in res2) {
when (entity.code) {
DataCodeEnum.OMDB_RD_LINK.code -> {
val snodePid = entity.properties["snodePid"]
if (snodePid != null) {
} else {
}
val enodePid = entity.properties["enodePid"]
if (enodePid != null) {
} else {
}
}
DataCodeEnum.OMDB_LINK_DIRECT.code -> {
val direct = entity.properties["direct"]
if (direct != null) {
}
}
DataCodeEnum.OMDB_LINK_NAME.code -> {
// var name = realm.copyFromRealm(res4)
}
}
}
}
}
}
}

View File

@ -35,7 +35,7 @@ class SignUtil {
return SignBean( return SignBean(
iconId = getSignIcon(element), iconId = getSignIcon(element),
iconText = getSignIconText(element), iconText = getSignIconText(element),
linkId = element.properties[RenderEntity.Companion.LinkTable.linkPid] linkId = element.linkPid
?: "", ?: "",
name = getSignNameText(element), name = getSignNameText(element),
bottomRightText = getSignBottomRightText( bottomRightText = getSignBottomRightText(
@ -208,7 +208,7 @@ class SignUtil {
DataCodeEnum.OMDB_RD_LINK.code -> { DataCodeEnum.OMDB_RD_LINK.code -> {
list.add( list.add(
TwoItemAdapterItem( TwoItemAdapterItem(
title = "linkPid", text = "${data.properties["linkPid"]}" title = "linkPid", text = "${data.linkPid}"
) )
) )
list.add( list.add(
@ -226,7 +226,7 @@ class SignUtil {
DataCodeEnum.OMDB_RD_LINK_KIND.code -> { DataCodeEnum.OMDB_RD_LINK_KIND.code -> {
list.add( list.add(
TwoItemAdapterItem( TwoItemAdapterItem(
title = "linkPid", text = "${data.properties["linkPid"]}" title = "linkPid", text = "${data.linkPid}"
) )
) )
try { try {
@ -244,7 +244,7 @@ class SignUtil {
DataCodeEnum.OMDB_LINK_DIRECT.code -> { DataCodeEnum.OMDB_LINK_DIRECT.code -> {
list.add( list.add(
TwoItemAdapterItem( TwoItemAdapterItem(
title = "linkPid", text = "${data.properties["linkPid"]}" title = "linkPid", text = "${data.linkPid}"
) )
) )
try { try {
@ -333,7 +333,7 @@ class SignUtil {
DataCodeEnum.OMDB_LINK_CONSTRUCTION.code -> { DataCodeEnum.OMDB_LINK_CONSTRUCTION.code -> {
list.add( list.add(
TwoItemAdapterItem( TwoItemAdapterItem(
title = "linkPid", text = "${data.properties["linkPid"]}" title = "linkPid", text = "${data.linkPid}"
) )
) )
@ -386,7 +386,7 @@ class SignUtil {
DataCodeEnum.OMDB_WARNINGSIGN.code -> { DataCodeEnum.OMDB_WARNINGSIGN.code -> {
list.add( list.add(
TwoItemAdapterItem( TwoItemAdapterItem(
title = "linkPid", text = "${data.properties["linkPid"]}" title = "linkPid", text = "${data.linkPid}"
) )
) )
list.add( list.add(
@ -751,7 +751,7 @@ class SignUtil {
fun getTollgateInfo(renderEntity: RenderEntity): List<LaneBoundaryItem> { fun getTollgateInfo(renderEntity: RenderEntity): List<LaneBoundaryItem> {
val list = mutableListOf<LaneBoundaryItem>() val list = mutableListOf<LaneBoundaryItem>()
list.add( list.add(
LaneBoundaryItem("linkPid", "${renderEntity.properties["linkPid"]}", null) LaneBoundaryItem("linkPid", "${renderEntity.linkPid}", null)
) )
list.add( list.add(
LaneBoundaryItem("收费站号码", "${renderEntity.properties["tollgatePid"]}", null) LaneBoundaryItem("收费站号码", "${renderEntity.properties["tollgatePid"]}", null)

View File

@ -0,0 +1,27 @@
package com.navinfo.collect.library.data.entity
import android.os.Parcelable
import com.navinfo.collect.library.system.Constant
import com.navinfo.collect.library.utils.GeometryTools
import com.navinfo.collect.library.utils.GeometryToolsKt
import io.realm.RealmDictionary
import io.realm.RealmObject
import io.realm.RealmSet
import io.realm.annotations.Ignore
import io.realm.annotations.Index
import io.realm.annotations.PrimaryKey
import kotlinx.parcelize.Parcelize
import org.locationtech.jts.geom.Coordinate
import org.locationtech.jts.geom.Geometry
import org.oscim.core.MercatorProjection
import java.util.*
/**
* 渲染要素对应的实体
* */
@Parcelize
open class LinkRelation() : RealmObject(), Parcelable {
var linkPid:String = ""
var sNodeId: String? = null
var eNodeId: String? = null
}

View File

@ -1,7 +1,11 @@
package com.navinfo.collect.library.data.entity package com.navinfo.collect.library.data.entity
import android.util.Log
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.navinfo.collect.library.utils.GeometryTools import com.navinfo.collect.library.utils.GeometryTools
import com.navinfo.collect.library.utils.GeometryToolsKt import com.navinfo.collect.library.utils.GeometryToolsKt
import com.navinfo.collect.library.utils.StrZipUtil
import io.realm.RealmDictionary import io.realm.RealmDictionary
import io.realm.RealmObject import io.realm.RealmObject
import io.realm.RealmSet import io.realm.RealmSet
@ -14,18 +18,28 @@ import java.util.*
* 渲染要素对应的实体 * 渲染要素对应的实体
* */ * */
open class ReferenceEntity() : RealmObject() { open class ReferenceEntity() : RealmObject() {
@PrimaryKey // @PrimaryKey
var id: String = UUID.randomUUID().toString() // id // var id: Int = 0 // id
var renderEntityId: String = "" // 参考的renderEntity的Id // var renderEntityId: Int = 0 // 参考的renderEntity的Id
@Ignore
lateinit var name: String //要素名 lateinit var name: String //要素名
lateinit var table: String //要素表名 lateinit var table: String //要素表名
var propertiesDb: String = ""
var code: String = "0" // 要素编码 var code: String = "0" // 要素编码
@Ignore
var zoomMin: Int = 18 //显示最小级别 var zoomMin: Int = 18 //显示最小级别
@Ignore
var zoomMax: Int = 23 //显示最大级别 var zoomMax: Int = 23 //显示最大级别
var taskId: Int = 0 //任务ID var taskId: Int = 0 //任务ID
var enable: Int = 0 // 默认0不是显示 1为渲染显示 var enable: Int = 0 // 默认0不是显示 1为渲染显示
var tileXMin: Int = 0
var geometry: String = "" // 要素渲染参考的geometry该数据可能会在导入预处理环节被修改原始geometry会保存在properties的geometry字段下 var tileXMax: Int = 0
var tileYMin: Int = 0
var tileYMax: Int = 0
var geometry: String =
"" // 要素渲染参考的geometry该数据可能会在导入预处理环节被修改原始geometry会保存在properties的geometry字段下
get() { get() {
wkt = GeometryTools.createGeometry(field) wkt = GeometryTools.createGeometry(field)
return field return field
@ -34,7 +48,13 @@ open class ReferenceEntity() : RealmObject() {
field = value field = value
// 根据geometry自动计算当前要素的x-tile和y-tile // 根据geometry自动计算当前要素的x-tile和y-tile
GeometryToolsKt.getTileXByGeometry(value, tileX) GeometryToolsKt.getTileXByGeometry(value, tileX)
tileXMin = tileX.min()
tileXMax = tileX.max()
GeometryToolsKt.getTileYByGeometry(value, tileY) GeometryToolsKt.getTileYByGeometry(value, tileY)
tileYMin = tileY.min()
tileYMax = tileY.max()
// 根据传入的geometry文本自动转换为Geometry对象 // 根据传入的geometry文本自动转换为Geometry对象
try { try {
wkt = GeometryTools.createGeometry(value) wkt = GeometryTools.createGeometry(value)
@ -55,8 +75,26 @@ open class ReferenceEntity() : RealmObject() {
} }
return field return field
} }
@Ignore
var properties: RealmDictionary<String> = RealmDictionary() var properties: RealmDictionary<String> = RealmDictionary()
get() {
if (propertiesDb.isNotEmpty() && field.isEmpty()) {
try {
val gson = Gson()
val type = object : TypeToken<RealmDictionary<String>>() {}.type
field = gson.fromJson(StrZipUtil.uncompress(propertiesDb), type)
} catch (e: Exception) {
Log.e("jingo","ReferenceEntity 转 properties $e")
}
}
return field
}
@Ignore
var tileX: RealmSet<Int> = RealmSet() // x方向的tile编码 var tileX: RealmSet<Int> = RealmSet() // x方向的tile编码
@Ignore
var tileY: RealmSet<Int> = RealmSet() // y方向的tile编码 var tileY: RealmSet<Int> = RealmSet() // y方向的tile编码
constructor(name: String) : this() { constructor(name: String) : this() {

View File

@ -1,40 +1,63 @@
package com.navinfo.collect.library.data.entity package com.navinfo.collect.library.data.entity
import android.os.Parcelable import android.os.Parcelable
import android.util.Log
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.navinfo.collect.library.system.Constant import com.navinfo.collect.library.system.Constant
import com.navinfo.collect.library.utils.GeometryTools import com.navinfo.collect.library.utils.GeometryTools
import com.navinfo.collect.library.utils.GeometryToolsKt import com.navinfo.collect.library.utils.GeometryToolsKt
import com.navinfo.collect.library.utils.StrZipUtil
import io.realm.RealmDictionary import io.realm.RealmDictionary
import io.realm.RealmObject import io.realm.RealmObject
import io.realm.RealmSet import io.realm.RealmSet
import io.realm.annotations.Ignore import io.realm.annotations.Ignore
import io.realm.annotations.Index
import io.realm.annotations.PrimaryKey import io.realm.annotations.PrimaryKey
import kotlinx.parcelize.Parcelize import kotlinx.parcelize.Parcelize
import org.locationtech.jts.geom.Coordinate import org.locationtech.jts.geom.Coordinate
import org.locationtech.jts.geom.Geometry import org.locationtech.jts.geom.Geometry
import org.oscim.core.MercatorProjection import org.oscim.core.MercatorProjection
import java.util.* import java.util.*
import java.util.zip.GZIPInputStream
/** /**
* 渲染要素对应的实体 * 渲染要素对应的实体
* */ * */
@Parcelize @Parcelize
open class RenderEntity() : RealmObject(), Parcelable { open class RenderEntity() : RealmObject(), Parcelable {
@PrimaryKey // @PrimaryKey
var id: String = UUID.randomUUID().toString() // id // var id: String = UUID.randomUUID().toString() // id
lateinit var name: String //要素名 lateinit var name: String //要素名
lateinit var table: String //要素表名 lateinit var table: String //要素表名
var code: String = "0" // 要素编码 var code: String = "0" // 要素编码
var geometry: String = "" // 要素渲染参考的geometry该数据可能会在导入预处理环节被修改原始geometry会保存在properties的geometry字段下 var propertiesDb: String = ""
var geometry: String =
"" // 要素渲染参考的geometry该数据可能会在导入预处理环节被修改原始geometry会保存在properties的geometry字段下
get() { get() {
wkt = GeometryTools.createGeometry(field) wkt = GeometryTools.createGeometry(field)
return field return field
} }
// get() {
// if (geometryDb != null && geometryDb.isNotEmpty() && field.isEmpty()) {
// field = StrZipUtil.uncompress(geometryDb)
// }
// return field
// }
set(value) { set(value) {
field = value field = value
// geometryDb = StrZipUtil.compress(value)
// 根据geometry自动计算当前要素的x-tile和y-tile // 根据geometry自动计算当前要素的x-tile和y-tile
GeometryToolsKt.getTileXByGeometry(value, tileX) GeometryToolsKt.getTileXByGeometry(value, tileX)
tileXMin = tileX.min()
tileXMax = tileX.max()
GeometryToolsKt.getTileYByGeometry(value, tileY) GeometryToolsKt.getTileYByGeometry(value, tileY)
tileYMin = tileY.min()
tileYMax = tileY.max()
// 根据传入的geometry文本自动转换为Geometry对象 // 根据传入的geometry文本自动转换为Geometry对象
try { try {
wkt = GeometryTools.createGeometry(value) wkt = GeometryTools.createGeometry(value)
@ -50,36 +73,47 @@ open class RenderEntity() : RealmObject(), Parcelable {
try { try {
field = GeometryTools.createGeometry(geometry) field = GeometryTools.createGeometry(geometry)
} catch (e: Exception) { } catch (e: Exception) {
Log.e("jingo","RenderEntity 转 wkt失败 $e")
} }
} }
return field return field
} }
@Ignore
var properties: RealmDictionary<String> = RealmDictionary() var properties: RealmDictionary<String> = RealmDictionary()
get() {
if (propertiesDb != null && propertiesDb.isNotEmpty() && field.isEmpty()) {
try {
val gson = Gson()
val type = object : TypeToken<RealmDictionary<String>>() {}.type
field = gson.fromJson(StrZipUtil.uncompress(propertiesDb), type)
} catch (e: Exception) {
Log.e("jingo","RenderEntity 转 properties $e")
}
}
return field
}
@Ignore
var tileX: RealmSet<Int> = RealmSet() // x方向的tile编码 var tileX: RealmSet<Int> = RealmSet() // x方向的tile编码
@Ignore
var tileY: RealmSet<Int> = RealmSet() // y方向的tile编码 var tileY: RealmSet<Int> = RealmSet() // y方向的tile编码
var tileXMin: Int = 0
var tileXMax: Int = 0
var tileYMin: Int = 0
var tileYMax: Int = 0
var taskId: Int = 0 //任务ID var taskId: Int = 0 //任务ID
var zoomMin: Int = 18 //显示最小级别 var zoomMin: Int = 18 //显示最小级别
var zoomMax: Int = 23 //显示最大级别 var zoomMax: Int = 23 //显示最大级别
var enable: Int = 0 // 默认0不是显示 1为渲染显示 2为常显 var enable: Int = 0 // 默认0不是显示 1为渲染显示 2为常显
var catchEnable: Int = 0 // 0不捕捉 1捕捉 var catchEnable: Int = 0 // 0不捕捉 1捕捉
var linkPid: String = "" // RenderEntity关联的linkPid集合(可能会关联多个)
var linkRelation: LinkRelation? = null
constructor(name: String) : this() { constructor(name: String) : this() {
this.name = name this.name = name
} }
companion object {
object LinkTable {
//道路linkId
const val linkPid = "linkPid"
}
object LimitTable {
const val linkPid = "linkPid"
}
object KindCodeTable {
const val linkPid = "linkPid"
}
}
} }

View File

@ -224,7 +224,6 @@ private class MyLocationListener(callback: (BDLocation) -> Unit) : BDAbstractLoc
val call = callback; val call = callback;
override fun onReceiveLocation(location: BDLocation) { override fun onReceiveLocation(location: BDLocation) {
call(location) call(location)
Log.e("jingo", "定位结果:速度=" + location.speed + " 方向=" + location.direction)
} }
} }

View File

@ -6,6 +6,7 @@ import android.util.Log;
import androidx.annotation.RequiresApi; import androidx.annotation.RequiresApi;
import com.navinfo.collect.library.data.entity.ReferenceEntity; import com.navinfo.collect.library.data.entity.ReferenceEntity;
import com.navinfo.collect.library.data.entity.RenderEntity;
import com.navinfo.collect.library.system.Constant; import com.navinfo.collect.library.system.Constant;
import com.navinfo.collect.library.utils.GeometryTools; import com.navinfo.collect.library.utils.GeometryTools;
import com.navinfo.collect.library.utils.MapParamUtils; import com.navinfo.collect.library.utils.MapParamUtils;
@ -17,6 +18,7 @@ import org.oscim.tiling.ITileDataSink;
import org.oscim.tiling.ITileDataSource; import org.oscim.tiling.ITileDataSource;
import org.oscim.tiling.QueryResult; import org.oscim.tiling.QueryResult;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -41,8 +43,12 @@ public class OMDBReferenceDataSource implements ITileDataSource {
@RequiresApi(api = Build.VERSION_CODES.N) @RequiresApi(api = Build.VERSION_CODES.N)
@Override @Override
public void query(MapTile tile, ITileDataSink mapDataSink) { public void query(MapTile tile, ITileDataSink mapDataSink) {
if(MapParamUtils.getTaskConfig() == null)
return;
// 获取tile对应的坐标范围 // 获取tile对应的坐标范围
if (tile.zoomLevel >= Constant.OMDB_MIN_ZOOM && tile.zoomLevel <= Constant.DATA_ZOOM) { if (tile.zoomLevel >= Constant.OMDB_MIN_ZOOM && tile.zoomLevel <= Constant.DATA_ZOOM) {
Realm realm = Realm.getInstance(MapParamUtils.getTaskConfig());
RealmQuery<ReferenceEntity> realmQuery = realm.where(ReferenceEntity.class);
int m = Constant.DATA_ZOOM - tile.zoomLevel; int m = Constant.DATA_ZOOM - tile.zoomLevel;
int xStart = tile.tileX; int xStart = tile.tileX;
int xEnd = tile.tileX + 1; int xEnd = tile.tileX + 1;
@ -57,11 +63,13 @@ public class OMDBReferenceDataSource implements ITileDataSource {
final int currentTileX = xStart; final int currentTileX = xStart;
if (isUpdate) { if (isUpdate) {
Realm.getInstance(MapParamUtils.getTaskConfig()).refresh(); realm.refresh();
isUpdate = false; isUpdate = false;
} }
String sql = " tileX>=" + xStart + " and tileX<=" + xEnd + " and tileY>=" + yStart + " and tileY<=" + yEnd + ""; String sql = " ((tileXMin <= " + xStart + " and tileXMax >= " + xStart + ") or (tileXMin <=" + xEnd + " and tileXMax >=" + xStart + ")) and ((tileYMin <= " + yStart + " and tileYMax >= " + yStart + ") or (tileYMin <=" + yEnd + " and tileYMin >=" + yStart + "))";
// String sql = " tileX>=" + xStart + " and tileX<=" + xEnd + " and tileY>=" + yStart + " and tileY<=" + yEnd + "";
if (MapParamUtils.getDataLayerEnum() != null) { if (MapParamUtils.getDataLayerEnum() != null) {
sql += " and enable" + MapParamUtils.getDataLayerEnum().getSql(); sql += " and enable" + MapParamUtils.getDataLayerEnum().getSql();
@ -69,8 +77,7 @@ public class OMDBReferenceDataSource implements ITileDataSource {
sql += " and enable>=0"; sql += " and enable>=0";
} }
RealmQuery<ReferenceEntity> realmQuery = Realm.getInstance(MapParamUtils.getTaskConfig()).where(ReferenceEntity.class) realmQuery.rawPredicate(sql);
.rawPredicate(sql);
// 筛选不显示的数据 // 筛选不显示的数据
if (Constant.HAD_LAYER_INVISIABLE_ARRAY != null && Constant.HAD_LAYER_INVISIABLE_ARRAY.length > 0) { if (Constant.HAD_LAYER_INVISIABLE_ARRAY != null && Constant.HAD_LAYER_INVISIABLE_ARRAY.length > 0) {
realmQuery.beginGroup(); realmQuery.beginGroup();
@ -91,10 +98,11 @@ public class OMDBReferenceDataSource implements ITileDataSource {
} else { } else {
mapDataSink.completed(QueryResult.SUCCESS); mapDataSink.completed(QueryResult.SUCCESS);
} }
Realm.getInstance(MapParamUtils.getTaskConfig()).close(); realm.close();
} else { } else {
mapDataSink.completed(QueryResult.SUCCESS); mapDataSink.completed(QueryResult.SUCCESS);
} }
} }
@Override @Override
@ -104,13 +112,12 @@ public class OMDBReferenceDataSource implements ITileDataSource {
@Override @Override
public void cancel() { public void cancel() {
if (Realm.getDefaultInstance().isInTransaction()) { // if (Realm.getDefaultInstance().isInTransaction()) {
Realm.getDefaultInstance().cancelTransaction(); // Realm.getDefaultInstance().cancelTransaction();
} // }
} }
public void update() { public void update() {
isUpdate = true; isUpdate = true;
Log.e("qj",Thread.currentThread().getName());
} }
} }

View File

@ -11,21 +11,45 @@ import com.navinfo.collect.library.utils.GeometryTools;
import com.navinfo.collect.library.utils.MapParamUtils; import com.navinfo.collect.library.utils.MapParamUtils;
import org.locationtech.jts.geom.Polygon; import org.locationtech.jts.geom.Polygon;
import org.oscim.core.MapPosition;
import org.oscim.layers.tile.MapTile; import org.oscim.layers.tile.MapTile;
import org.oscim.map.Map;
import org.oscim.map.Viewport; import org.oscim.map.Viewport;
import org.oscim.tiling.ITileDataSink; import org.oscim.tiling.ITileDataSink;
import org.oscim.tiling.ITileDataSource; import org.oscim.tiling.ITileDataSource;
import org.oscim.tiling.QueryResult; import org.oscim.tiling.QueryResult;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import io.realm.Realm; import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmQuery; import io.realm.RealmQuery;
public class OMDBTileDataSource implements ITileDataSource { public class OMDBTileDataSource implements ITileDataSource {
class RealmObject {
int threadCode;
int realmConfigCode;
Realm realm;
}
// class DataObject {
// int threadCode = 0;
// byte zoom = 0;
// String lonLat = "";
// List<String> listIds = new ArrayList<>();
// }
private boolean isUpdate; private boolean isUpdate;
private Viewport viewport; private Viewport viewport;
private List<RealmObject> realmObjectList = new ArrayList<>();
// private List<DataObject> dataObjectList = new ArrayList<>();
private final ThreadLocal<OMDBDataDecoder> mThreadLocalDecoders = new ThreadLocal<OMDBDataDecoder>() { private final ThreadLocal<OMDBDataDecoder> mThreadLocalDecoders = new ThreadLocal<OMDBDataDecoder>() {
@Override @Override
protected OMDBDataDecoder initialValue() { protected OMDBDataDecoder initialValue() {
@ -40,8 +64,37 @@ public class OMDBTileDataSource implements ITileDataSource {
@RequiresApi(api = Build.VERSION_CODES.N) @RequiresApi(api = Build.VERSION_CODES.N)
@Override @Override
public void query(MapTile tile, ITileDataSink mapDataSink) { public void query(MapTile tile, ITileDataSink mapDataSink) {
if(MapParamUtils.getTaskConfig() == null)
return;
// 获取tile对应的坐标范围 // 获取tile对应的坐标范围
if (tile.zoomLevel >= Constant.OMDB_MIN_ZOOM && tile.zoomLevel <= Constant.DATA_ZOOM) { if (tile.zoomLevel >= Constant.OMDB_MIN_ZOOM && tile.zoomLevel <= Constant.DATA_ZOOM) {
Realm realm = null;
int threadCode = Thread.currentThread().hashCode();
synchronized (realmObjectList) {
int configCode = MapParamUtils.getTaskConfig().hashCode();
for (RealmObject object : realmObjectList) {
if (object.threadCode == threadCode) {
if (object.realmConfigCode == configCode) {
realm = object.realm;
} else {
object.realm.close();
realmObjectList.remove(object);
}
break;
}
}
if (realm == null) {
realm = Realm.getInstance(MapParamUtils.getTaskConfig());
RealmObject o = new RealmObject();
o.threadCode = threadCode;
o.realmConfigCode = configCode;
o.realm = realm;
realmObjectList.add(o);
}
}
// Realm realm = Realm.getInstance(MapParamUtils.getTaskConfig());
RealmQuery<RenderEntity> realmQuery = realm.where(RenderEntity.class);
int m = Constant.DATA_ZOOM - tile.zoomLevel; int m = Constant.DATA_ZOOM - tile.zoomLevel;
int xStart = tile.tileX; int xStart = tile.tileX;
int xEnd = tile.tileX + 1; int xEnd = tile.tileX + 1;
@ -54,21 +107,19 @@ public class OMDBTileDataSource implements ITileDataSource {
yEnd = (int) (yEnd << m); yEnd = (int) (yEnd << m);
} }
final int currentTileX = xStart;
if (isUpdate) { if (isUpdate) {
Realm.getInstance(MapParamUtils.getTaskConfig()).refresh(); realm.refresh();
isUpdate = false; isUpdate = false;
} }
String sql =" tileX>=" + xStart + " and tileX<=" + xEnd + " and tileY>=" + yStart + " and tileY<=" + yEnd + ""; String sql = " ((tileXMin <= " + xStart + " and tileXMax >= " + xStart + ") or (tileXMin <=" + xEnd + " and tileXMax >=" + xStart + ")) and ((tileYMin <= " + yStart + " and tileYMax >= " + yStart + ") or (tileYMin <=" + yEnd + " and tileYMin >=" + yStart + "))";
if (MapParamUtils.getDataLayerEnum() != null) { if (MapParamUtils.getDataLayerEnum() != null) {
sql += " and enable" + MapParamUtils.getDataLayerEnum().getSql(); sql += " and enable" + MapParamUtils.getDataLayerEnum().getSql();
} else { } else {
sql += " and enable>=0"; sql += " and enable>=0";
} }
realmQuery.rawPredicate(sql);
RealmQuery<RenderEntity> realmQuery = Realm.getInstance(MapParamUtils.getTaskConfig()).where(RenderEntity.class).rawPredicate(sql);
// 筛选不显示的数据 // 筛选不显示的数据
if (Constant.HAD_LAYER_INVISIABLE_ARRAY != null && Constant.HAD_LAYER_INVISIABLE_ARRAY.length > 0) { if (Constant.HAD_LAYER_INVISIABLE_ARRAY != null && Constant.HAD_LAYER_INVISIABLE_ARRAY.length > 0) {
realmQuery.beginGroup(); realmQuery.beginGroup();
@ -77,13 +128,17 @@ public class OMDBTileDataSource implements ITileDataSource {
} }
realmQuery.endGroup(); realmQuery.endGroup();
} }
List<RenderEntity> listResult = realmQuery/*.distinct("id")*/.findAll(); long time = System.currentTimeMillis();
List<RenderEntity> listResult = realmQuery.findAll();
long newTime = System.currentTimeMillis() - time;
Log.e("jingo", "当前OMDBTileDataSource " + Thread.currentThread().hashCode() + " 当前realm " + realm.hashCode() + " 查询耗时" + newTime + " 条数" + listResult.size());
// 数据记录的tile号是以正外接tile号列表此处过滤并未与当前tile相交的数据 // 数据记录的tile号是以正外接tile号列表此处过滤并未与当前tile相交的数据
if (!listResult.isEmpty()) { if (!listResult.isEmpty()) {
Polygon tilePolygon = GeometryTools.getTilePolygon(tile); Polygon tilePolygon = GeometryTools.getTilePolygon(tile);
// System.out.println("第一条数据的最小x值:" + listResult.get(0).getTileX().stream().min(Integer::compare).get()); listResult = listResult.stream().filter((RenderEntity renderEntity) ->
// System.out.println("当前tile的:" + listResult.get(0).getTileX().stream().min(Integer::compare).get()); renderEntity.getWkt().intersects(tilePolygon)
listResult = listResult.stream().filter((RenderEntity renderEntity) -> renderEntity.getWkt().intersects(tilePolygon)) )
/*过滤数据只有最小x屏幕的最小x或数据的最小x会被渲染跨Tile的其他数据不再重复渲染*/ /*过滤数据只有最小x屏幕的最小x或数据的最小x会被渲染跨Tile的其他数据不再重复渲染*/
// .filter((RenderEntity renderEntity) -> MercatorProjection.longitudeToTileX(viewport.fromScreenPoint(0,0).getLongitude(), (byte) Constant.DATA_ZOOM) == currentTileX || renderEntity.getTileX().stream().min(Integer::compare).get() == currentTileX) // .filter((RenderEntity renderEntity) -> MercatorProjection.longitudeToTileX(viewport.fromScreenPoint(0,0).getLongitude(), (byte) Constant.DATA_ZOOM) == currentTileX || renderEntity.getTileX().stream().min(Integer::compare).get() == currentTileX)
.collect(Collectors.toList()); .collect(Collectors.toList());
@ -92,7 +147,7 @@ public class OMDBTileDataSource implements ITileDataSource {
} else { } else {
mapDataSink.completed(QueryResult.SUCCESS); mapDataSink.completed(QueryResult.SUCCESS);
} }
Realm.getInstance(MapParamUtils.getTaskConfig()).close(); // realm.close();
} else { } else {
mapDataSink.completed(QueryResult.SUCCESS); mapDataSink.completed(QueryResult.SUCCESS);
} }
@ -105,13 +160,12 @@ public class OMDBTileDataSource implements ITileDataSource {
@Override @Override
public void cancel() { public void cancel() {
if (Realm.getDefaultInstance().isInTransaction()) { // if (Realm.getDefaultInstance().isInTransaction()) {
Realm.getDefaultInstance().cancelTransaction(); // Realm.getDefaultInstance().cancelTransaction();
} // }
} }
public void update() { public void update() {
isUpdate = true; isUpdate = true;
Log.e("qj",Thread.currentThread().getName());
} }
} }

View File

@ -27,7 +27,7 @@ public class OMDBTileSource extends RealmDBTileSource {
@Override @Override
public OpenResult open() { public OpenResult open() {
Log.d("qj", Realm.getDefaultInstance().where(RenderEntity.class).findAll().size()+"open安装数量"); // Log.d("qj", Realm.getDefaultInstance().where(RenderEntity.class).findAll().size()+"open安装数量");
return OpenResult.SUCCESS; return OpenResult.SUCCESS;
} }

View File

@ -35,27 +35,29 @@ public class RealmDBTileDataSource implements ITileDataSource {
public void query(MapTile tile, ITileDataSink mapDataSink) { public void query(MapTile tile, ITileDataSink mapDataSink) {
// 获取tile对应的坐标范围 // 获取tile对应的坐标范围
if (tile.zoomLevel>=15&&tile.zoomLevel<=Constant.OVER_ZOOM) { if (tile.zoomLevel>=15&&tile.zoomLevel<=Constant.OVER_ZOOM) {
int m = Constant.OVER_ZOOM-tile.zoomLevel; Log.e("jingo","RealmDBTileDataSource RealmDBTileDataSource RealmDBTileDataSource");
int xStart = (int)tile.tileX<<m; // int m = Constant.OVER_ZOOM-tile.zoomLevel;
int xEnd = (int)((tile.tileX+1)<<m); // int xStart = (int)tile.tileX<<m;
int yStart = (int)tile.tileY<<m; // int xEnd = (int)((tile.tileX+1)<<m);
int yEnd = (int)((tile.tileY+1)<<m); // int yStart = (int)tile.tileY<<m;
// int yEnd = (int)((tile.tileY+1)<<m);
RealmQuery<GeometryFeatureEntity> realmQuery = Realm.getDefaultInstance().where(GeometryFeatureEntity.class) //
.rawPredicate("tileX>="+xStart+" and tileX<="+xEnd+" and tileY>="+yStart+" and tileY<="+yEnd); // RealmQuery<GeometryFeatureEntity> realmQuery = Realm.getDefaultInstance().where(GeometryFeatureEntity.class)
// 筛选不显示的数据 // .rawPredicate("tileX>="+xStart+" and tileX<="+xEnd+" and tileY>="+yStart+" and tileY<="+yEnd);
if (Constant.HAD_LAYER_INVISIABLE_ARRAY!=null&&Constant.HAD_LAYER_INVISIABLE_ARRAY.length>0) { // // 筛选不显示的数据
realmQuery.beginGroup(); // if (Constant.HAD_LAYER_INVISIABLE_ARRAY!=null&&Constant.HAD_LAYER_INVISIABLE_ARRAY.length>0) {
for (String type: Constant.HAD_LAYER_INVISIABLE_ARRAY) { // realmQuery.beginGroup();
realmQuery.notEqualTo("name", type); // for (String type: Constant.HAD_LAYER_INVISIABLE_ARRAY) {
} // realmQuery.notEqualTo("name", type);
realmQuery.endGroup(); // }
} // realmQuery.endGroup();
List<GeometryFeatureEntity> listResult = realmQuery.distinct("id").findAll(); // }
mThreadLocalDecoders.get().decode(tile, mapDataSink, listResult); // List<GeometryFeatureEntity> listResult = realmQuery.distinct("id").findAll();
mapDataSink.completed(QueryResult.SUCCESS); // mThreadLocalDecoders.get().decode(tile, mapDataSink, listResult);
Realm.getDefaultInstance().close(); // mapDataSink.completed(QueryResult.SUCCESS);
// Realm.getDefaultInstance().close();
// Log.d("RealmDBTileDataSource", "tile:"+tile.getBoundingBox().toString()); // Log.d("RealmDBTileDataSource", "tile:"+tile.getBoundingBox().toString());
mapDataSink.completed(QueryResult.SUCCESS);
} else { } else {
mapDataSink.completed(QueryResult.SUCCESS); mapDataSink.completed(QueryResult.SUCCESS);
} }
@ -68,8 +70,8 @@ public class RealmDBTileDataSource implements ITileDataSource {
@Override @Override
public void cancel() { public void cancel() {
if (Realm.getInstance(RealmUtils.getInstance().getRealmConfiguration()).isInTransaction()) { // if (Realm.getInstance(RealmUtils.getInstance().getRealmConfiguration()).isInTransaction()) {
Realm.getInstance(RealmUtils.getInstance().getRealmConfiguration()).cancelTransaction(); // Realm.getInstance(RealmUtils.getInstance().getRealmConfiguration()).cancelTransaction();
} // }
} }
} }

View File

@ -0,0 +1,282 @@
package com.navinfo.collect.library.utils
import sun.misc.BASE64Decoder
import sun.misc.BASE64Encoder
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.util.*
import java.util.zip.*
object StrZipUtil {
/**
* @param input 需要压缩的字符串
* @return 压缩后的字符串
* @throws IOException IO
*/
fun compress(input: String): String {
if (input.isEmpty()) {
return input
}
try {
val out = ByteArrayOutputStream()
val gzipOs = GZIPOutputStream(out)
gzipOs.write(input.toByteArray())
gzipOs.close()
return BASE64Encoder().encode(out.toByteArray())
} catch (e: Exception) {
return input
}
}
/**
* @param zippedStr 压缩后的字符串
* @return 解压缩后的
* @throws IOException IO
*/
fun uncompress(zippedStr: String): String {
if (zippedStr.isEmpty()) {
return zippedStr
}
try {
val out = ByteArrayOutputStream()
val `in` = ByteArrayInputStream(
BASE64Decoder().decodeBuffer(zippedStr)
)
val gzipIs = GZIPInputStream(`in`)
val buffer = ByteArray(256)
var n: Int
while (gzipIs.read(buffer).also { n = it } >= 0) {
out.write(buffer, 0, n)
}
// toString()使用平台默认编码也可以显式的指定如toString("GBK")
return out.toString()
} catch (e: Exception) {
return zippedStr
}
}
/***
* 压缩GZip
*
* @param data
* @return
*/
fun gZip(data: ByteArray?): ByteArray? {
var b: ByteArray? = null
try {
val bos = ByteArrayOutputStream()
val gzip = GZIPOutputStream(bos)
gzip.write(data)
gzip.finish()
gzip.close()
b = bos.toByteArray()
bos.close()
} catch (ex: java.lang.Exception) {
ex.printStackTrace()
}
return b
}
/***
* 解压GZip
*
* @param data
* @return
*/
fun unGZip(data: ByteArray?): ByteArray? {
var b: ByteArray? = null
try {
val bis = ByteArrayInputStream(data)
val gzip = GZIPInputStream(bis)
val buf = ByteArray(1024)
var num = -1
val baos = ByteArrayOutputStream()
while (gzip.read(buf, 0, buf.size).also { num = it } != -1) {
baos.write(buf, 0, num)
}
b = baos.toByteArray()
baos.flush()
baos.close()
gzip.close()
bis.close()
} catch (ex: java.lang.Exception) {
ex.printStackTrace()
}
return b
}
/***
* 压缩Zip
*
* @param data
* @return
*/
fun zip(data: ByteArray): ByteArray? {
var b: ByteArray? = null
try {
val bos = ByteArrayOutputStream()
val zip = ZipOutputStream(bos)
val entry = ZipEntry("zip")
entry.size = data.size.toLong()
zip.putNextEntry(entry)
zip.write(data)
zip.closeEntry()
zip.close()
b = bos.toByteArray()
bos.close()
} catch (ex: java.lang.Exception) {
ex.printStackTrace()
}
return b
}
/***
* 解压Zip
*
* @param data
* @return
*/
fun unZip(data: ByteArray?): ByteArray? {
var b: ByteArray? = null
try {
val bis = ByteArrayInputStream(data)
val zip = ZipInputStream(bis)
while (zip.nextEntry != null) {
val buf = ByteArray(1024)
var num = -1
val baos = ByteArrayOutputStream()
while (zip.read(buf, 0, buf.size).also { num = it } != -1) {
baos.write(buf, 0, num)
}
b = baos.toByteArray()
baos.flush()
baos.close()
}
zip.close()
bis.close()
} catch (ex: java.lang.Exception) {
ex.printStackTrace()
}
return b
}
// /***
// * 压缩BZip2
// *
// * @param data
// * @return
// */
// public static byte[] bZip2(byte[] data) {
// byte[] b = null;
// try {
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// CBZip2OutputStream bzip2 = new CBZip2OutputStream(bos);
// bzip2.write(data);
// bzip2.flush();
// bzip2.close();
// b = bos.toByteArray();
// bos.close();
// } catch (Exception ex) {
// ex.printStackTrace();
// }
// return b;
// }
// /***
// * 解压BZip2
// *
// * @param data
// * @return
// */
// public static byte[] unBZip2(byte[] data) {
// byte[] b = null;
// try {
// ByteArrayInputStream bis = new ByteArrayInputStream(data);
// CBZip2InputStream bzip2 = new CBZip2InputStream(bis);
// byte[] buf = new byte[1024];
// int num = -1;
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// while ((num = bzip2.read(buf, 0, buf.length)) != -1) {
// baos.write(buf, 0, num);
// }
// b = baos.toByteArray();
// baos.flush();
// baos.close();
// bzip2.close();
// bis.close();
// } catch (Exception ex) {
// ex.printStackTrace();
// }
// return b;
// }
// /***
// * 压缩BZip2
// *
// * @param data
// * @return
// */
// public static byte[] bZip2(byte[] data) {
// byte[] b = null;
// try {
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// CBZip2OutputStream bzip2 = new CBZip2OutputStream(bos);
// bzip2.write(data);
// bzip2.flush();
// bzip2.close();
// b = bos.toByteArray();
// bos.close();
// } catch (Exception ex) {
// ex.printStackTrace();
// }
// return b;
// }
// /***
// * 解压BZip2
// *
// * @param data
// * @return
// */
// public static byte[] unBZip2(byte[] data) {
// byte[] b = null;
// try {
// ByteArrayInputStream bis = new ByteArrayInputStream(data);
// CBZip2InputStream bzip2 = new CBZip2InputStream(bis);
// byte[] buf = new byte[1024];
// int num = -1;
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// while ((num = bzip2.read(buf, 0, buf.length)) != -1) {
// baos.write(buf, 0, num);
// }
// b = baos.toByteArray();
// baos.flush();
// baos.close();
// bzip2.close();
// bis.close();
// } catch (Exception ex) {
// ex.printStackTrace();
// }
// return b;
// }
/**
* 把字节数组转换成16进制字符串
*
* @param bArray
* @return
*/
fun bytesToHexString(bArray: ByteArray): String? {
val sb = StringBuffer(bArray.size)
var sTemp: String
for (i in bArray.indices) {
sTemp = Integer.toHexString(0xFF and bArray[i].toInt())
if (sTemp.length < 2) sb.append(0)
sb.append(sTemp.uppercase(Locale.getDefault()))
}
return sb.toString()
}
}

2
vtm

@ -1 +1 @@
Subproject commit 9e0cc6dcdce04d1082ed6459e8810d6329e8cfdc Subproject commit c046e788f5c739612a31c308639fca2de639669a