fix: 合并代码

This commit is contained in:
xiaoyan 2023-11-03 15:31:34 +08:00
commit 92181c5ab4
49 changed files with 3588 additions and 1981 deletions

View File

@ -107,6 +107,7 @@ dependencies {
// implementation 'javax.xml.stream:stax-api:1.0-2' // implementation 'javax.xml.stream:stax-api:1.0-2'
// implementation 'com.bea.xml.stream:com.bea.xml.stream:1.0.0' // implementation 'com.bea.xml.stream:com.bea.xml.stream:1.0.0'
implementation 'commons-io:commons-io:2.11.0' implementation 'commons-io:commons-io:2.11.0'
implementation 'com.alibaba:fastjson:1.2.73'
// spatialite文件 // spatialite文件
implementation 'com.github.sevar83:android-spatialite:2.0.1' implementation 'com.github.sevar83:android-spatialite:2.0.1'

View File

@ -83,6 +83,7 @@
"name": "车道边界类型", "name": "车道边界类型",
"zoomMin": 18, "zoomMin": 18,
"zoomMax": 20, "zoomMax": 20,
"isDependOnOtherTable": true,
"checkLinkId": false, "checkLinkId": false,
"filterData": true, "filterData": true,
"catch": true, "catch": true,
@ -125,16 +126,6 @@
"zoomMin": 15, "zoomMin": 15,
"zoomMax": 17 "zoomMax": 17
}, },
"2041":{
"table": "OMDB_LANE_NUM",
"code": 2041,
"name": "车道数"
},
"2097":{
"table": "OMDB_PHY_LANENUM",
"code": 2097,
"name": "物理车道数"
},
"2083": { "2083": {
"table": "OMDB_RDBOUND_BOUNDARYTYPE", "table": "OMDB_RDBOUND_BOUNDARYTYPE",
"code": 2083, "code": 2083,
@ -150,7 +141,6 @@
"code": 2090, "code": 2090,
"name": "车道施工", "name": "车道施工",
"existSubCode": true, "existSubCode": true,
"checkLinkId": false,
"catch": true, "catch": true,
"zoomMin": 18, "zoomMin": 18,
"zoomMax": 20 "zoomMax": 20
@ -160,6 +150,7 @@
"code": 2092, "code": 2092,
"name": "车道类型", "name": "车道类型",
"catch": true, "catch": true,
"isDependOnOtherTable": true,
"zoomMin": 18, "zoomMin": 18,
"zoomMax": 20, "zoomMax": 20,
"transformer": [ "transformer": [
@ -177,12 +168,18 @@
} }
] ]
}, },
"2097": {
"table": "OMDB_PHY_LANENUM",
"code": 2097,
"name": "物理车道数"
},
"2201": { "2201": {
"table": "OMDB_BRIDGE", "table": "OMDB_BRIDGE",
"code": 2201, "code": 2201,
"name": "桥", "name": "桥",
"catch": true, "catch": true,
"existSubCode": true, "existSubCode": true,
"isDependOnOtherTable": true,
"zoomMin": 15, "zoomMin": 15,
"zoomMax": 20, "zoomMax": 20,
"transformer": [ "transformer": [
@ -359,6 +356,7 @@
"code": 4001, "code": 4001,
"name": "路口", "name": "路口",
"zoomMin": 15, "zoomMin": 15,
"isDependOnOtherTable": true,
"zoomMax": 17, "zoomMax": 17,
"catch": true, "catch": true,
"transformer": [ "transformer": [
@ -460,6 +458,7 @@
"zoomMin": 15, "zoomMin": 15,
"zoomMax": 17, "zoomMax": 17,
"filterData": true, "filterData": true,
"isDependOnOtherTable": true,
"catch": true, "catch": true,
"transformer": [ "transformer": [
{ {
@ -499,6 +498,7 @@
"code": 4009, "code": 4009,
"name": "警示信息", "name": "警示信息",
"catch": true, "catch": true,
"isDependOnOtherTable": true,
"zoomMin": 15, "zoomMin": 15,
"zoomMax": 20, "zoomMax": 20,
"transformer": [ "transformer": [
@ -562,24 +562,6 @@
} }
] ]
}, },
"4016": {
"table": "OMDB_ZLEVEL",
"code": 4016,
"name": "立交",
"zoomMin": 15,
"zoomMax": 20,
"filterData": true,
"catch": true,
"checkLinkId": false,
"transformer": [
{
"k": "geometry",
"v": "~",
"klib": "geometry",
"vlib": "obtainZLevelReference()"
}
]
},
"4022": { "4022": {
"table": "OMDB_TRAFFICLIGHT", "table": "OMDB_TRAFFICLIGHT",
"code": 4022, "code": 4022,
@ -605,6 +587,7 @@
"code": 4601, "code": 4601,
"name": "车信", "name": "车信",
"catch": true, "catch": true,
"isDependOnOtherTable": true,
"zoomMin": 15, "zoomMin": 15,
"zoomMax": 17, "zoomMax": 17,
"transformer": [ "transformer": [
@ -633,6 +616,7 @@
"code": 5001, "code": 5001,
"name": "车道中心线", "name": "车道中心线",
"catch": false, "catch": false,
"isDependOnOtherTable": true,
"checkLinkId": false, "checkLinkId": false,
"zoomMin": 18, "zoomMin": 18,
"zoomMax": 20, "zoomMax": 20,
@ -715,7 +699,6 @@
"zoomMin": 15, "zoomMin": 15,
"zoomMax": 17 "zoomMax": 17
} }
} }
} }
] ]

View File

@ -40,6 +40,20 @@ class Constant {
*/ */
lateinit var USER_DATA_PATH: String lateinit var USER_DATA_PATH: String
/**
* 用户数据安装标识
*/
var INSTALL_DATA: Boolean = false
/**
* 轨迹渲染个数统计
*/
var TRACE_COUNT : Int = 0
var TRACE_COUNT_TIME : Int = 9
var TRACE_COUNT_MORE_TIME : Int = 24
/** /**
* 当前安装任务 * 当前安装任务
*/ */
@ -79,6 +93,11 @@ class Constant {
*/ */
lateinit var DOWNLOAD_PATH: String lateinit var DOWNLOAD_PATH: String
/**
* 日志目录
*/
lateinit var USER_DATA_LOG_PATH: String
/** /**
* 图层管理对应的配置 * 图层管理对应的配置
* */ * */
@ -107,6 +126,11 @@ class Constant {
*/ */
var MapMarkerCloseEnable = false var MapMarkerCloseEnable = false
/**
* 轨迹显隐
*/
var MapTraceCloseEnable = false
/** /**
* 是否开启线捕捉 * 是否开启线捕捉
*/ */

View File

@ -8,6 +8,7 @@ import android.view.Surface
import android.view.WindowManager import android.view.WindowManager
import com.navinfo.omqs.tools.FileManager import com.navinfo.omqs.tools.FileManager
import com.navinfo.omqs.ui.manager.TakePhotoManager import com.navinfo.omqs.ui.manager.TakePhotoManager
import com.navinfo.omqs.util.CMLog
import com.navinfo.omqs.util.NetUtils import com.navinfo.omqs.util.NetUtils
import com.umeng.commonsdk.UMConfigure import com.umeng.commonsdk.UMConfigure
import dagger.hilt.android.HiltAndroidApp import dagger.hilt.android.HiltAndroidApp
@ -20,6 +21,7 @@ class OMQSApplication : Application() {
super.onCreate() super.onCreate()
FileManager.initRootDir(this) FileManager.initRootDir(this)
Util.getInstance().init(applicationContext) Util.getInstance().init(applicationContext)
CMLog.getInstance().init(applicationContext)
NetUtils.getInstance().init(this) NetUtils.getInstance().init(this)
TakePhotoManager.getInstance().init(this, 1) TakePhotoManager.getInstance().init(this, 1)
// 初始化友盟统计 // 初始化友盟统计

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,19 +13,19 @@ 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}")
return renderEntity return renderEntity
} }
Log.e("qj", "子表转换不为空===${renderEntity.code}")
for (transform in transformList) { for (transform in transformList) {
// 开始执行转换 // 开始执行转换
val key: String = transform.k val key: String = transform.k
@ -36,7 +37,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 +53,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 +88,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 +121,7 @@ class ImportConfig {
} }
} }
} }
preProcess.realm = null
return renderEntity return renderEntity
} }
@ -127,8 +142,9 @@ class TableInfo {
val checkLinkId: Boolean = true//是否需要校验linkid val checkLinkId: Boolean = true//是否需要校验linkid
val filterData: Boolean = false//是否需要过滤数据 val filterData: Boolean = false//是否需要过滤数据
val existSubCode: Boolean = false//是否存在子编码 val existSubCode: Boolean = false//是否存在子编码
val isDependOnOtherTable = 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()

File diff suppressed because it is too large Load Diff

View File

@ -1,10 +1,15 @@
package com.navinfo.omqs.db package com.navinfo.omqs.db
import android.util.Log import android.util.Log
import com.alibaba.fastjson.JSON
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.DeflaterUtil
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 +20,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 +59,7 @@ class ImportPreProcess {
return false return false
} }
} }
}
return true return true
} }
@ -200,16 +219,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 +241,7 @@ 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 = DeflaterUtil.zipString(JSON.toJSONString(startEndReference.properties))
listResult.add(startEndReference) listResult.add(startEndReference)
insertData(listResult) insertData(listResult)
} }
@ -254,7 +274,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
@ -262,7 +282,6 @@ class ImportPreProcess {
startReference.zoomMax = renderEntity.zoomMax startReference.zoomMax = renderEntity.zoomMax
startReference.taskId = renderEntity.taskId startReference.taskId = renderEntity.taskId
startReference.enable = renderEntity.enable startReference.enable = renderEntity.enable
// 起点坐标 // 起点坐标
startReference.geometry = startReference.geometry =
GeometryTools.createGeometry(GeoPoint(pointStart.y, pointStart.x)).toString() GeometryTools.createGeometry(GeoPoint(pointStart.y, pointStart.x)).toString()
@ -272,7 +291,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
@ -306,7 +325,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
@ -338,12 +357,13 @@ 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 = DeflaterUtil.zipString(JSON.toJSONString(startReference.properties))
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
@ -372,7 +392,7 @@ 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 = DeflaterUtil.zipString(JSON.toJSONString(endReference.properties))
listResult.add(endReference) listResult.add(endReference)
Log.e("qj", "generateS2EReferencePoint===4") Log.e("qj", "generateS2EReferencePoint===4")
insertData(listResult) insertData(listResult)
@ -458,7 +478,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
@ -470,6 +490,7 @@ 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 = DeflaterUtil.zipString(JSON.toJSONString(angleReference.properties))
listResult.add(angleReference) listResult.add(angleReference)
} }
insertData(listResult) insertData(listResult)
@ -553,10 +574,12 @@ class ImportPreProcess {
renderEntityTemp.catchEnable = renderEntity.catchEnable renderEntityTemp.catchEnable = renderEntity.catchEnable
var dis = -lateralOffset.toDouble() / 100000000 var dis = -lateralOffset.toDouble() / 100000000
//最小值取10厘米否正渲染太近无法显示 //最小值取10厘米否正渲染太近无法显示
if (dis > 0 && dis < 0.0000028) { if (dis > 0 && dis < 0.000005) {
dis = 0.0000028 dis = 0.000005
} else if (dis > -0.0000028 && dis < 0) { Log.d("lateralOffset", "$dis")
dis = -0.0000028 } else if (dis > -0.000005 && dis < 0) {
dis = -0.000005
Log.d("lateralOffset", "$dis")
} }
renderEntityTemp.geometry = GeometryTools.computeLine( renderEntityTemp.geometry = GeometryTools.computeLine(
dis, dis,
@ -605,7 +628,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
@ -613,7 +636,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("_")
@ -624,6 +647,7 @@ 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 = DeflaterUtil.zipString(JSON.toJSONString(referenceEntity.properties))
listResult.add(referenceEntity) listResult.add(referenceEntity)
} }
insertData(listResult) insertData(listResult)
@ -716,14 +740,16 @@ class ImportPreProcess {
* 生成车道中心线面宽度 * 生成车道中心线面宽度
* */ * */
fun generateAddWidthLine(renderEntity: RenderEntity) { fun generateAddWidthLine(renderEntity: RenderEntity) {
var newTime = 0L
// 添加车道中心面渲染原则,根据车道宽度进行渲染 // 添加车道中心面渲染原则,根据车道宽度进行渲染
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 = Log.e("jingo", "几何转换开始")
GeometryTools.createGeometry(renderEntity.geometry).buffer(0.000035) angleReference.geometry = renderEntity.geometry
.toString()//GeometryTools.computeLine(0.000035,0.000035,renderEntity.geometry) //GeometryTools.createGeometry(renderEntity.geometry).buffer(0.000035).toString()//GeometryTools.computeLine(0.000035,0.000035,renderEntity.geometry)
Log.e("jingo", "几何转换结束")
angleReference.properties["qi_table"] = renderEntity.table angleReference.properties["qi_table"] = renderEntity.table
angleReference.properties["widthProperties"] = "3" angleReference.properties["widthProperties"] = "3"
angleReference.zoomMin = renderEntity.zoomMin angleReference.zoomMin = renderEntity.zoomMin
@ -731,6 +757,7 @@ 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 = DeflaterUtil.zipString(JSON.toJSONString(angleReference.properties))
listResult.add(angleReference) listResult.add(angleReference)
insertData(listResult) insertData(listResult)
} }
@ -748,7 +775,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
@ -761,6 +788,7 @@ 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 = DeflaterUtil.zipString(JSON.toJSONString(intersectionReference.properties))
listResult.add(intersectionReference) listResult.add(intersectionReference)
} }
insertData(listResult) insertData(listResult)
@ -915,7 +943,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
@ -929,17 +957,17 @@ 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 = DeflaterUtil.zipString(JSON.toJSONString(dynamicSrcReference.properties))
listResult.add(dynamicSrcReference) listResult.add(dynamicSrcReference)
} }
insertData(listResult) insertData(listResult)
} }
private fun insertData(list: List<RealmModel>) { private fun insertData(list: List<RealmModel>) {
Log.e("qj", "子表插入==") realm?.let {
if (list != null && list.isNotEmpty()) { if (list != null && list.isNotEmpty()) {
Log.e("qj", "子表插入开始==") it.copyToRealm(list)
Realm.getInstance(Constant.currentInstallTaskConfig).insert(list) }
Log.e("qj", "子表插入结束==")
} }
} }

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

@ -155,9 +155,8 @@ class TaskDownloadScope(
fileNew fileNew
) )
if (task != null) { if (task != null) {
importOMDBHelper.importOmdbZipFile(importOMDBHelper.omdbFile, task).collect { if (importOMDBHelper.importOmdbZipFile(importOMDBHelper.omdbFile, task, this)) {
Log.e("jingo", "数据安装 $it") // if (it == "finish") {
if (it == "finish") {
change(FileDownloadStatus.DONE) change(FileDownloadStatus.DONE)
Log.e("jingo", "数据安装结束") Log.e("jingo", "数据安装结束")
withContext(Dispatchers.Main) { withContext(Dispatchers.Main) {
@ -167,9 +166,9 @@ class TaskDownloadScope(
} }
} }
} else { } else {
change(FileDownloadStatus.IMPORTING, it) change(FileDownloadStatus.IMPORTING, "anzhuang")
}
} }
// }
} }
} catch (e: Exception) { } catch (e: Exception) {
Log.e("jingo", "数据安装失败 ${e.toString()}") Log.e("jingo", "数据安装失败 ${e.toString()}")

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
@ -282,6 +287,12 @@ class LoginViewModel @Inject constructor(
task.fileSize = item.fileSize task.fileSize = item.fileSize
task.status = item.status task.status = item.status
task.currentSize = item.currentSize task.currentSize = item.currentSize
//增加mesh==null兼容性处理
for (hadLink in item.hadLinkDvoList) {
if(hadLink.mesh==null){
hadLink.mesh = ""
}
}
task.hadLinkDvoList = item.hadLinkDvoList task.hadLinkDvoList = item.hadLinkDvoList
task.syncStatus = item.syncStatus task.syncStatus = item.syncStatus
//已上传后不在更新操作时间 //已上传后不在更新操作时间
@ -293,8 +304,10 @@ class LoginViewModel @Inject constructor(
} }
} else { } else {
for (hadLink in task.hadLinkDvoList) { for (hadLink in task.hadLinkDvoList) {
if(hadLink.geometry==null||hadLink.mesh==null){ if(hadLink.geometry==null){
inSertData = false inSertData = false
}else if(hadLink.mesh==null){
hadLink.mesh = ""
}else{ }else{
hadLink.taskId = task.id hadLink.taskId = task.id
} }
@ -418,12 +431,15 @@ class LoginViewModel @Inject constructor(
Constant.VERSION_ID = userId Constant.VERSION_ID = userId
Constant.USER_DATA_PATH = Constant.DATA_PATH + Constant.USER_ID + "/" + Constant.VERSION_ID Constant.USER_DATA_PATH = Constant.DATA_PATH + Constant.USER_ID + "/" + Constant.VERSION_ID
Constant.USER_DATA_ATTACHEMNT_PATH = Constant.USER_DATA_PATH + "/attachment/" Constant.USER_DATA_ATTACHEMNT_PATH = Constant.USER_DATA_PATH + "/attachment/"
Constant.USER_DATA_LOG_PATH = Constant.USER_DATA_PATH + "/log/"
// 在SD卡创建用户目录解压资源等 // 在SD卡创建用户目录解压资源等
val userFolder = File(Constant.USER_DATA_PATH) val userFolder = File(Constant.USER_DATA_PATH)
if (!userFolder.exists()) userFolder.mkdirs() if (!userFolder.exists()) userFolder.mkdirs()
//创建附件目录 //创建附件目录
val userAttachmentFolder = File(Constant.USER_DATA_ATTACHEMNT_PATH) val userAttachmentFolder = File(Constant.USER_DATA_ATTACHEMNT_PATH)
if (!userAttachmentFolder.exists()) userAttachmentFolder.mkdirs() if (!userAttachmentFolder.exists()) userAttachmentFolder.mkdirs()
val userLogFolder = File(Constant.USER_DATA_LOG_PATH)
if (!userLogFolder.exists()) userLogFolder.mkdirs()
// 初始化Realm // 初始化Realm
Realm.init(context.applicationContext) Realm.init(context.applicationContext)
// 656e6372797000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 // 656e6372797000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
@ -431,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)
// 拷贝配置文件到用户目录下 // 拷贝配置文件到用户目录下
@ -458,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)
}
}
}
}
} }

File diff suppressed because one or more lines are too long

View File

@ -23,6 +23,7 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import androidx.navigation.findNavController import androidx.navigation.findNavController
import com.blankj.utilcode.util.ToastUtils import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.navinfo.collect.library.data.dao.impl.TraceDataBase import com.navinfo.collect.library.data.dao.impl.TraceDataBase
import com.navinfo.collect.library.data.entity.* import com.navinfo.collect.library.data.entity.*
import com.navinfo.collect.library.enums.DataCodeEnum import com.navinfo.collect.library.enums.DataCodeEnum
@ -50,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
@ -67,6 +70,18 @@ import kotlin.concurrent.fixedRateTimer
* 创建Activity全局viewmode * 创建Activity全局viewmode
*/ */
enum class LoadDataStatus {
/**
* 加载开始
*/
LOAD_DATA_STATUS_BEGIN,
/**
* 加载结束
*/
LOAD_DATA_STATUS_FISISH,
}
@HiltViewModel @HiltViewModel
class MainViewModel @Inject constructor( class MainViewModel @Inject constructor(
private val mapController: NIMapController, private val mapController: NIMapController,
@ -94,6 +109,9 @@ class MainViewModel @Inject constructor(
//地图点击捕捉到的轨迹列表 //地图点击捕捉到的轨迹列表
val liveDataNILocationList = MutableLiveData<NiLocation>() val liveDataNILocationList = MutableLiveData<NiLocation>()
//加载数据
val liveDataLoadData = MutableLiveData<LoadDataStatus>()
//左侧看板数据 //左侧看板数据
val liveDataSignList = MutableLiveData<List<SignBean>>() val liveDataSignList = MutableLiveData<List<SignBean>>()
@ -239,11 +257,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;
init { init {
mapController.mMapView.vtmMap.events.bind(Map.UpdateListener { e, mapPosition -> mapController.mMapView.vtmMap.events.bind(Map.UpdateListener { e, mapPosition ->
@ -271,6 +292,10 @@ class MainViewModel @Inject constructor(
object : OnGeoPointClickListener { object : OnGeoPointClickListener {
override fun onMapClick(tag: String, point: GeoPoint) { override fun onMapClick(tag: String, point: GeoPoint) {
if (tag == TAG) { if (tag == TAG) {
//数据安装时不允许操作数据
if(Constant.INSTALL_DATA){
return
}
if (bMeasuringTool) { if (bMeasuringTool) {
mapController.measureLayerHandler.addPoint(measuringType, point) mapController.measureLayerHandler.addPoint(measuringType, point)
} else { } else {
@ -321,6 +346,7 @@ class MainViewModel @Inject constructor(
}) })
viewModelScope.launch(Dispatchers.IO) { viewModelScope.launch(Dispatchers.IO) {
liveDataLoadData.postValue(LoadDataStatus.LOAD_DATA_STATUS_BEGIN)
getTaskBean() getTaskBean()
//初始化选中的任务高亮高亮 //初始化选中的任务高亮高亮
if (currentTaskBean != null) { if (currentTaskBean != null) {
@ -329,6 +355,7 @@ class MainViewModel @Inject constructor(
initQsRecordData() initQsRecordData()
initNoteData() initNoteData()
initNILocationData() initNILocationData()
liveDataLoadData.postValue(LoadDataStatus.LOAD_DATA_STATUS_FISISH)
} }
sharedPreferences.registerOnSharedPreferenceChangeListener(this) sharedPreferences.registerOnSharedPreferenceChangeListener(this)
MapParamUtils.setTaskId(sharedPreferences.getInt(Constant.SELECT_TASK_ID, -1)) MapParamUtils.setTaskId(sharedPreferences.getInt(Constant.SELECT_TASK_ID, -1))
@ -336,32 +363,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)
// } }
// } }
/** /**
* 获取当前任务 * 获取当前任务
@ -403,7 +443,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
@ -415,7 +458,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?,
@ -526,7 +585,20 @@ class MainViewModel @Inject constructor(
).niLocationDao.findToTaskIdAll(id.toString()) ).niLocationDao.findToTaskIdAll(id.toString())
if (list != null) { if (list != null) {
for (location in list) { for (location in list) {
Constant.TRACE_COUNT++
if(Constant.TRACE_COUNT%Constant.TRACE_COUNT_MORE_TIME==0){
mapController.markerHandle.addNiLocationMarkerItemRough(location)
Log.e("qj","${Constant.TRACE_COUNT}===轨迹")
}
if(Constant.TRACE_COUNT%Constant.TRACE_COUNT_TIME==0){
mapController.markerHandle.addNiLocationMarkerItemSimple(location)
Log.e("qj","${Constant.TRACE_COUNT}===轨迹")
}
mapController.markerHandle.addNiLocationMarkerItem(location) mapController.markerHandle.addNiLocationMarkerItem(location)
} }
} }
} }
@ -535,6 +607,7 @@ class MainViewModel @Inject constructor(
* 初始化定位信息 * 初始化定位信息
*/ */
private fun initLocation() { private fun initLocation() {
var gson = Gson();
//用于定位点存储到数据库 //用于定位点存储到数据库
viewModelScope.launch(Dispatchers.Default) { viewModelScope.launch(Dispatchers.Default) {
@ -588,12 +661,23 @@ class MainViewModel @Inject constructor(
lastNiLocaion!!.longitude lastNiLocaion!!.longitude
) )
} }
//室内整理工具时不能进行轨迹存储判断轨迹间隔要超过2.5并小于60米 //室内整理工具时不能进行轨迹存储判断轨迹间隔要超过6并小于60米
if (Constant.INDOOR_IP.isEmpty() && (disance == 0.0 || (disance > 2.5 && disance < 60))) { if (Constant.INDOOR_IP.isEmpty() && (disance == 0.0 || (disance > 6.0 && disance < 60))) {
Log.e("jingo", "轨迹插入开始")
CMLog.writeLogtoFile(MainViewModel::class.java.name,"insertTrace","开始")
traceDataBase.niLocationDao.insert(location) traceDataBase.niLocationDao.insert(location)
mapController.markerHandle.addNiLocationMarkerItem(location) mapController.markerHandle.addNiLocationMarkerItem(location)
if(Constant.TRACE_COUNT%Constant.TRACE_COUNT_TIME==0){
mapController.markerHandle.addNiLocationMarkerItemSimple(location)
}
if(Constant.TRACE_COUNT%Constant.TRACE_COUNT_MORE_TIME==0){
mapController.markerHandle.addNiLocationMarkerItemRough(location)
}
mapController.mMapView.vtmMap.updateMap(true) mapController.mMapView.vtmMap.updateMap(true)
lastNiLocaion = location lastNiLocaion = location
CMLog.writeLogtoFile(MainViewModel::class.java.name,"insertTrace",gson.toJson(location))
Log.e("jingo", "轨迹插入结束")
} }
} }
} }
@ -786,7 +870,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>()
@ -816,8 +900,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
@ -930,7 +1018,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) {
@ -964,6 +1052,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) {
@ -980,8 +1069,9 @@ class MainViewModel @Inject constructor(
fun onClickLocationButton() { fun onClickLocationButton() {
val mapPosition: MapPosition = mapController.mMapView.vtmMap.getMapPosition() val mapPosition: MapPosition = mapController.mMapView.vtmMap.getMapPosition()
mapPosition.setBearing(0f) // 锁定角度,自动将地图旋转到正北方向 mapPosition.setBearing(0f) // 锁定角度,自动将地图旋转到正北方向
mapController.mMapView.vtmMap.setMapPosition(mapPosition) mapController.mMapView.vtmMap.mapPosition = mapPosition
mapController.locationLayerHandler.animateToCurrentPosition() mapController.locationLayerHandler.animateToCurrentPosition()
naviEngineStatus = 1
} }
/** /**
@ -1658,7 +1748,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

@ -37,6 +37,8 @@ class SignAdapter(private var listener: OnSignAdapterClickListener?) :
override fun getItemViewType(position: Int): Int { override fun getItemViewType(position: Int): Int {
if (data.isNotEmpty() && data[position].renderEntity.code == DataCodeEnum.OMDB_LANEINFO.code) { if (data.isNotEmpty() && data[position].renderEntity.code == DataCodeEnum.OMDB_LANEINFO.code) {
return 4601 return 4601
}else if (data.isNotEmpty() && data[position].renderEntity.code == DataCodeEnum.OMDB_CLM_LANEINFO.code) {
return 4602
} else if (data.isNotEmpty() && data[position].renderEntity.code == DataCodeEnum.OMDB_TOLLGATE.code) { } else if (data.isNotEmpty() && data[position].renderEntity.code == DataCodeEnum.OMDB_TOLLGATE.code) {
return 4023 return 4023
} }

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

@ -7,6 +7,7 @@ import android.net.Uri
import android.os.Build import android.os.Build
import android.os.Bundle import android.os.Bundle
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import android.widget.TimePicker import android.widget.TimePicker
@ -21,6 +22,7 @@ import com.blankj.utilcode.util.UriUtils
import com.github.k1rakishou.fsaf.FileChooser import com.github.k1rakishou.fsaf.FileChooser
import com.github.k1rakishou.fsaf.callback.FSAFActivityCallbacks import com.github.k1rakishou.fsaf.callback.FSAFActivityCallbacks
import com.github.k1rakishou.fsaf.callback.FileChooserCallback import com.github.k1rakishou.fsaf.callback.FileChooserCallback
import com.google.android.material.internal.NavigationMenuItemView
import com.google.android.material.timepicker.MaterialTimePicker import com.google.android.material.timepicker.MaterialTimePicker
import com.navinfo.collect.library.enums.DataLayerEnum import com.navinfo.collect.library.enums.DataLayerEnum
import com.navinfo.collect.library.map.NIMapController import com.navinfo.collect.library.map.NIMapController
@ -40,6 +42,7 @@ import com.permissionx.guolindev.PermissionX
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import org.oscim.core.GeoPoint import org.oscim.core.GeoPoint
import org.oscim.core.MapPosition import org.oscim.core.MapPosition
import org.oscim.utils.MinHeap.Item
import javax.inject.Inject import javax.inject.Inject
/** /**
@ -73,35 +76,35 @@ class PersonalCenterFragment(private var indoorDataListener: ((Boolean) -> Unit?
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(view, savedInstanceState)
binding.root.setNavigationItemSelectedListener { binding.root.setNavigationItemSelectedListener { it ->
when (it.itemId) { when (it.itemId) {
R.id.personal_center_menu_offline_map -> R.id.personal_center_menu_offline_map ->
findNavController().navigate(R.id.OfflineMapFragment) findNavController().navigate(R.id.OfflineMapFragment)
R.id.personal_center_menu_obtain_data -> { // 生成数据根据sqlite文件生成对应的zip文件 // R.id.personal_center_menu_obtain_data -> { // 生成数据根据sqlite文件生成对应的zip文件
fileChooser.openChooseFileDialog(object : FileChooserCallback() { // fileChooser.openChooseFileDialog(object : FileChooserCallback() {
override fun onCancel(reason: String) { // override fun onCancel(reason: String) {
} // }
//
@RequiresApi(Build.VERSION_CODES.N) // @RequiresApi(Build.VERSION_CODES.N)
override fun onResult(uri: Uri) { // override fun onResult(uri: Uri) {
val file = UriUtils.uri2File(uri) // val file = UriUtils.uri2File(uri)
// 开始导入数据 // // 开始导入数据
// 656e6372797000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 // // 656e6372797000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
CoroutineUtils.launchWithLoading( // CoroutineUtils.launchWithLoading(
requireContext(), // requireContext(),
loadingMessage = "生成数据..." // loadingMessage = "生成数据..."
) { // ) {
val importOMDBHelper: ImportOMDBHelper = // val importOMDBHelper: ImportOMDBHelper =
importOMDBHiltFactory.obtainImportOMDBHelper( // importOMDBHiltFactory.obtainImportOMDBHelper(
requireContext(), // requireContext(),
file // file
) // )
viewModel.obtainOMDBZipData(importOMDBHelper) // viewModel.obtainOMDBZipData(importOMDBHelper)
} // }
} // }
}) // })
} // }
R.id.personal_center_menu_import_data -> { // 导入zip数据 R.id.personal_center_menu_import_data -> { // 导入zip数据
fileChooser.openChooseFileDialog(object : FileChooserCallback() { fileChooser.openChooseFileDialog(object : FileChooserCallback() {
@ -151,7 +154,7 @@ class PersonalCenterFragment(private var indoorDataListener: ((Boolean) -> Unit?
val mapPosition: MapPosition = val mapPosition: MapPosition =
niMapController.mMapView.vtmMap.getMapPosition() niMapController.mMapView.vtmMap.getMapPosition()
mapPosition.setBearing(0f) // 锁定角度,自动将地图旋转到正北方向 mapPosition.setBearing(0f) // 锁定角度,自动将地图旋转到正北方向
niMapController.mMapView.vtmMap.setMapPosition(mapPosition) niMapController.mMapView.vtmMap.mapPosition = mapPosition
it.title = "开启地图旋转及视角" it.title = "开启地图旋转及视角"
} else { } else {
it.title = "锁定地图旋转及视角" it.title = "锁定地图旋转及视角"
@ -168,6 +171,17 @@ class PersonalCenterFragment(private var indoorDataListener: ((Boolean) -> Unit?
it.title = "隐藏Marker" it.title = "隐藏Marker"
} }
} }
R.id.personal_center_menu_trace -> {
Constant.MapTraceCloseEnable = !Constant.MapTraceCloseEnable
//增加开关控制
niMapController.markerHandle.setTraceMarkEnable(!Constant.MapTraceCloseEnable)
//增加开关控制
if (Constant.MapTraceCloseEnable) {
it.title = "显示轨迹"
} else {
it.title = "隐藏轨迹"
}
}
R.id.personal_center_menu_catch_all -> { R.id.personal_center_menu_catch_all -> {
Constant.CATCH_ALL = !Constant.CATCH_ALL Constant.CATCH_ALL = !Constant.CATCH_ALL
if (Constant.CATCH_ALL) { if (Constant.CATCH_ALL) {
@ -258,6 +272,13 @@ class PersonalCenterFragment(private var indoorDataListener: ((Boolean) -> Unit?
it.title = "隐藏Marker" it.title = "隐藏Marker"
} }
} }
R.id.personal_center_menu_trace -> {
if (Constant.MapTraceCloseEnable) {
it.title = "显示轨迹"
} else {
it.title = "隐藏轨迹"
}
}
} }
} }
} }

View File

@ -1,17 +1,12 @@
package com.navinfo.omqs.ui.fragment.personalcenter package com.navinfo.omqs.ui.fragment.personalcenter
import android.net.Uri import android.net.Uri
import android.os.Build
import android.util.Log import android.util.Log
import androidx.annotation.RequiresApi
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 com.blankj.utilcode.util.FileIOUtils
import com.blankj.utilcode.util.UriUtils import com.blankj.utilcode.util.UriUtils
import com.blankj.utilcode.util.ZipUtils import com.navinfo.collect.library.data.entity.TaskBean
import com.google.gson.Gson
import com.navinfo.collect.library.data.entity.*
import com.navinfo.omqs.bean.ScProblemTypeBean import com.navinfo.omqs.bean.ScProblemTypeBean
import com.navinfo.omqs.bean.ScRootCauseAnalysisBean import com.navinfo.omqs.bean.ScRootCauseAnalysisBean
import com.navinfo.omqs.bean.ScWarningCodeBean import com.navinfo.omqs.bean.ScWarningCodeBean
@ -24,7 +19,6 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import org.apache.commons.io.input.BOMInputStream import org.apache.commons.io.input.BOMInputStream
import java.io.* import java.io.*
import java.util.*
import javax.inject.Inject import javax.inject.Inject
@ -37,119 +31,119 @@ class PersonalCenterViewModel @Inject constructor(
val liveDataMessage = MutableLiveData<String>() val liveDataMessage = MutableLiveData<String>()
/** // /**
* 导入OMDB数据 // * 导入OMDB数据
* */ // * */
@RequiresApi(Build.VERSION_CODES.N) // @RequiresApi(Build.VERSION_CODES.N)
suspend fun obtainOMDBZipData(importOMDBHelper: ImportOMDBHelper) { // suspend fun obtainOMDBZipData(importOMDBHelper: ImportOMDBHelper) {
Log.d("OMQSApplication", "开始生成数据") // Log.d("OMQSApplication", "开始生成数据")
val gson = Gson() // val gson = Gson()
val hadLinkFile = File(importOMDBHelper.omdbFile.parentFile, "HAD_LINK.txt") // val hadLinkFile = File(importOMDBHelper.omdbFile.parentFile, "HAD_LINK.txt")
val hadLinkKindFile = File(importOMDBHelper.omdbFile.parentFile, "HAD_LINK_KIND.txt") // val hadLinkKindFile = File(importOMDBHelper.omdbFile.parentFile, "HAD_LINK_KIND.txt")
val hadLinkDirectFile = File(importOMDBHelper.omdbFile.parentFile, "HAD_LINK_DIRECT.txt") // val hadLinkDirectFile = File(importOMDBHelper.omdbFile.parentFile, "HAD_LINK_DIRECT.txt")
val hadSpeedLimitFile = File(importOMDBHelper.omdbFile.parentFile, "HAD_SPEEDLIMIT.txt") // val hadSpeedLimitFile = File(importOMDBHelper.omdbFile.parentFile, "HAD_SPEEDLIMIT.txt")
val hadSpeedLimitCondFile = // val hadSpeedLimitCondFile =
File(importOMDBHelper.omdbFile.parentFile, "HAD_SPEEDLIMIT_COND.txt") // File(importOMDBHelper.omdbFile.parentFile, "HAD_SPEEDLIMIT_COND.txt")
val hadSpeedLimitVarFile = // val hadSpeedLimitVarFile =
File(importOMDBHelper.omdbFile.parentFile, "HAD_SPEEDLIMIT_VAR.txt") // File(importOMDBHelper.omdbFile.parentFile, "HAD_SPEEDLIMIT_VAR.txt")
//
for (tableName in listOf<String>( // for (tableName in listOf<String>(
"HAD_LINK", "HAD_SPEEDLIMIT", "HAD_SPEEDLIMIT_COND", "HAD_SPEEDLIMIT_VAR" // "HAD_LINK", "HAD_SPEEDLIMIT", "HAD_SPEEDLIMIT_COND", "HAD_SPEEDLIMIT_VAR"
)/*listOf<String>("HAD_LINK")*/) { // )/*listOf<String>("HAD_LINK")*/) {
importOMDBHelper.getOMDBTableData(tableName).collect { // importOMDBHelper.getOMDBTableData(tableName).collect {
for (map in it) { // for (map in it) {
if ("HAD_LINK" == tableName) { // if ("HAD_LINK" == tableName) {
// 根据HAD_Link生成json文件 // // 根据HAD_Link生成json文件
val hadLink = HAD_LINK() // val hadLink = HAD_LINK()
hadLink.LINK_PID = map["LINK_PID"].toString() // hadLink.LINK_PID = map["LINK_PID"].toString()
hadLink.MESH = map["MESH"].toString() // hadLink.MESH = map["MESH"].toString()
hadLink.S_NODE_PID = map["S_NODE_PID"].toString() // hadLink.S_NODE_PID = map["S_NODE_PID"].toString()
hadLink.E_NODE_PID = map["E_NODE_PID"].toString() // hadLink.E_NODE_PID = map["E_NODE_PID"].toString()
hadLink.GEOMETRY = map["GEOMETRY"].toString() // hadLink.GEOMETRY = map["GEOMETRY"].toString()
// 将该数据写入到对应的txt文件 // // 将该数据写入到对应的txt文件
FileIOUtils.writeFileFromString( // FileIOUtils.writeFileFromString(
hadLinkFile, gson.toJson(hadLink) + "\r", true // hadLinkFile, gson.toJson(hadLink) + "\r", true
) // )
//
val hadLinkDirect = HAD_LINK_DIRECT() // val hadLinkDirect = HAD_LINK_DIRECT()
hadLinkDirect.LINK_PID = map["LINK_PID"].toString() // hadLinkDirect.LINK_PID = map["LINK_PID"].toString()
hadLinkDirect.MESH = map["MESH"].toString() // hadLinkDirect.MESH = map["MESH"].toString()
hadLinkDirect.DIRECT = map["DIRECT"].toString().toInt() // hadLinkDirect.DIRECT = map["DIRECT"].toString().toInt()
hadLinkDirect.GEOMETRY = map["GEOMETRY"].toString() // hadLinkDirect.GEOMETRY = map["GEOMETRY"].toString()
// 将该数据写入到对应的txt文件 // // 将该数据写入到对应的txt文件
FileIOUtils.writeFileFromString( // FileIOUtils.writeFileFromString(
hadLinkDirectFile, gson.toJson(hadLinkDirect) + "\r", true // hadLinkDirectFile, gson.toJson(hadLinkDirect) + "\r", true
) // )
//
val hadLinkKind = HAD_LINK_KIND() // val hadLinkKind = HAD_LINK_KIND()
hadLinkKind.LINK_PID = map["LINK_PID"].toString() // hadLinkKind.LINK_PID = map["LINK_PID"].toString()
hadLinkKind.MESH = map["MESH"].toString() // hadLinkKind.MESH = map["MESH"].toString()
hadLinkKind.KIND = map["KIND"].toString().toInt() // hadLinkKind.KIND = map["KIND"].toString().toInt()
hadLinkKind.GEOMETRY = map["GEOMETRY"].toString() // hadLinkKind.GEOMETRY = map["GEOMETRY"].toString()
// 将该数据写入到对应的txt文件 // // 将该数据写入到对应的txt文件
FileIOUtils.writeFileFromString( // FileIOUtils.writeFileFromString(
hadLinkKindFile, gson.toJson(hadLinkKind) + "\r", true // hadLinkKindFile, gson.toJson(hadLinkKind) + "\r", true
) // )
} else if ("HAD_SPEEDLIMIT" == tableName) { // } else if ("HAD_SPEEDLIMIT" == tableName) {
val hadSpeedlimit = HAD_SPEEDLIMIT() // val hadSpeedlimit = HAD_SPEEDLIMIT()
hadSpeedlimit.SPEED_ID = map["SPEED_ID"].toString() // hadSpeedlimit.SPEED_ID = map["SPEED_ID"].toString()
hadSpeedlimit.MESH = map["MESH"].toString() // hadSpeedlimit.MESH = map["MESH"].toString()
hadSpeedlimit.LINK_PID = map["LINK_PID"].toString() // hadSpeedlimit.LINK_PID = map["LINK_PID"].toString()
hadSpeedlimit.GEOMETRY = map["GEOMETRY"].toString() // hadSpeedlimit.GEOMETRY = map["GEOMETRY"].toString()
hadSpeedlimit.DIRECT = map["DIRECT"].toString().toInt() // hadSpeedlimit.DIRECT = map["DIRECT"].toString().toInt()
hadSpeedlimit.SPEED_FLAG = map["SPEED_FLAG"].toString().toInt() // hadSpeedlimit.SPEED_FLAG = map["SPEED_FLAG"].toString().toInt()
hadSpeedlimit.MAX_SPEED = map["MAX_SPEED"].toString().toInt() // hadSpeedlimit.MAX_SPEED = map["MAX_SPEED"].toString().toInt()
hadSpeedlimit.MIN_SPEED = map["MIN_SPEED"].toString().toInt() // hadSpeedlimit.MIN_SPEED = map["MIN_SPEED"].toString().toInt()
// 将该数据写入到对应的txt文件 // // 将该数据写入到对应的txt文件
FileIOUtils.writeFileFromString( // FileIOUtils.writeFileFromString(
hadSpeedLimitFile, gson.toJson(hadSpeedlimit) + "\r", true // hadSpeedLimitFile, gson.toJson(hadSpeedlimit) + "\r", true
) // )
} else if ("HAD_SPEEDLIMIT_COND" == tableName) { // } else if ("HAD_SPEEDLIMIT_COND" == tableName) {
val hadSpeedlimitCond = HAD_SPEEDLIMIT_COND() // val hadSpeedlimitCond = HAD_SPEEDLIMIT_COND()
hadSpeedlimitCond.SPEED_COND_ID = map["SPEED_COND_ID"].toString() // hadSpeedlimitCond.SPEED_COND_ID = map["SPEED_COND_ID"].toString()
hadSpeedlimitCond.MESH = map["MESH"].toString() // hadSpeedlimitCond.MESH = map["MESH"].toString()
hadSpeedlimitCond.LINK_PID = map["LINK_PID"].toString() // hadSpeedlimitCond.LINK_PID = map["LINK_PID"].toString()
hadSpeedlimitCond.GEOMETRY = map["GEOMETRY"].toString() // hadSpeedlimitCond.GEOMETRY = map["GEOMETRY"].toString()
hadSpeedlimitCond.DIRECT = map["DIRECT"].toString().toInt() // hadSpeedlimitCond.DIRECT = map["DIRECT"].toString().toInt()
hadSpeedlimitCond.SPEED_FLAG = map["SPEED_FLAG"].toString().toInt() // hadSpeedlimitCond.SPEED_FLAG = map["SPEED_FLAG"].toString().toInt()
hadSpeedlimitCond.MAX_SPEED = map["MAX_SPEED"].toString().toInt() // hadSpeedlimitCond.MAX_SPEED = map["MAX_SPEED"].toString().toInt()
hadSpeedlimitCond.SPEED_DEPENDENT = // hadSpeedlimitCond.SPEED_DEPENDENT =
map["SPEED_DEPENDENT"].toString().toInt() // map["SPEED_DEPENDENT"].toString().toInt()
hadSpeedlimitCond.VEHICLE_TYPE = map["VEHICLE_TYPE"].toString().toInt() // hadSpeedlimitCond.VEHICLE_TYPE = map["VEHICLE_TYPE"].toString().toInt()
hadSpeedlimitCond.VALID_PERIOD = map["VALID_PERIOD"].toString() // hadSpeedlimitCond.VALID_PERIOD = map["VALID_PERIOD"].toString()
// 将该数据写入到对应的txt文件 // // 将该数据写入到对应的txt文件
FileIOUtils.writeFileFromString( // FileIOUtils.writeFileFromString(
hadSpeedLimitCondFile, gson.toJson(hadSpeedlimitCond) + "\r", true // hadSpeedLimitCondFile, gson.toJson(hadSpeedlimitCond) + "\r", true
) // )
} else if ("HAD_SPEEDLIMIT_VAR" == tableName) { // } else if ("HAD_SPEEDLIMIT_VAR" == tableName) {
val hadSpeedlimitVar = HAD_SPEEDLIMIT_VAR() // val hadSpeedlimitVar = HAD_SPEEDLIMIT_VAR()
hadSpeedlimitVar.SPEED_VAR_ID = map["SPEED_ID"].toString() // hadSpeedlimitVar.SPEED_VAR_ID = map["SPEED_ID"].toString()
hadSpeedlimitVar.MESH = map["MESH"].toString() // hadSpeedlimitVar.MESH = map["MESH"].toString()
hadSpeedlimitVar.LINK_PID = map["LINK_PID"].toString() // hadSpeedlimitVar.LINK_PID = map["LINK_PID"].toString()
hadSpeedlimitVar.GEOMETRY = map["GEOMETRY"].toString() // hadSpeedlimitVar.GEOMETRY = map["GEOMETRY"].toString()
hadSpeedlimitVar.DIRECT = map["DIRECT"].toString().toInt() // hadSpeedlimitVar.DIRECT = map["DIRECT"].toString().toInt()
hadSpeedlimitVar.LOCATION = map["LOCATION"].toString() // hadSpeedlimitVar.LOCATION = map["LOCATION"].toString()
// 将该数据写入到对应的txt文件 // // 将该数据写入到对应的txt文件
FileIOUtils.writeFileFromString( // FileIOUtils.writeFileFromString(
hadSpeedLimitVarFile, gson.toJson(hadSpeedlimitVar) + "\r", true // hadSpeedLimitVarFile, gson.toJson(hadSpeedlimitVar) + "\r", true
) // )
} // }
} // }
} // }
} // }
ZipUtils.zipFiles( // ZipUtils.zipFiles(
mutableListOf( // mutableListOf(
hadLinkFile, // hadLinkFile,
hadLinkKindFile, // hadLinkKindFile,
hadLinkDirectFile, // hadLinkDirectFile,
hadSpeedLimitFile, // hadSpeedLimitFile,
hadSpeedLimitCondFile, // hadSpeedLimitCondFile,
hadSpeedLimitVarFile // hadSpeedLimitVarFile
), File(importOMDBHelper.omdbFile.parentFile, "output.zip") // ), File(importOMDBHelper.omdbFile.parentFile, "output.zip")
) // )
//
Log.d("OMQSApplication", "生成数据完成") // Log.d("OMQSApplication", "生成数据完成")
} // }
/** /**
* 导入OMDB数据 * 导入OMDB数据
@ -158,15 +152,12 @@ class PersonalCenterViewModel @Inject constructor(
viewModelScope.launch(Dispatchers.IO) { viewModelScope.launch(Dispatchers.IO) {
Log.d("OMQSApplication", "开始导入数据") Log.d("OMQSApplication", "开始导入数据")
if (task != null) { if (task != null) {
importOMDBHelper.importOmdbZipFile(importOMDBHelper.omdbFile, task).collect { importOMDBHelper.importOmdbZipFile(importOMDBHelper.omdbFile, task, this)
Log.d("importOMDBData", it)
}
} else { } else {
val newTask = TaskBean() val newTask = TaskBean()
newTask.id = -1 newTask.id = -1
importOMDBHelper.importOmdbZipFile(importOMDBHelper.omdbFile, newTask).collect { importOMDBHelper.importOmdbZipFile(importOMDBHelper.omdbFile, newTask, this)
Log.d("importOMDBData", it)
}
} }
Log.d("OMQSApplication", "导入数据完成") Log.d("OMQSApplication", "导入数据完成")
} }

View File

@ -79,7 +79,9 @@ class TaskFragment : BaseFragment() {
viewModel.liveDataAddLinkDialog.observe(viewLifecycleOwner){ viewModel.liveDataAddLinkDialog.observe(viewLifecycleOwner){
viewModel.addTaskLink(requireContext(),it) viewModel.addTaskLink(requireContext(),it)
} }
viewModel.liveDataUpdateTask.observe(viewLifecycleOwner) {
}
//注意:使用滑动菜单不能开启滑动删除,否则只有滑动删除没有滑动菜单 //注意:使用滑动菜单不能开启滑动删除,否则只有滑动删除没有滑动菜单
val mSwipeMenuCreator = SwipeMenuCreator { _, rightMenu, _ -> val mSwipeMenuCreator = SwipeMenuCreator { _, rightMenu, _ ->

View File

@ -89,8 +89,15 @@ class TaskListFragment : BaseFragment() {
deleteItem.background = requireContext().getDrawable(R.color.red) deleteItem.background = requireContext().getDrawable(R.color.red)
deleteItem.setTextColor(requireContext().resources.getColor(R.color.white)) deleteItem.setTextColor(requireContext().resources.getColor(R.color.white))
rightMenu.addMenuItem(deleteItem) rightMenu.addMenuItem(deleteItem)
}
val resetDownLoad = SwipeMenuItem(context)
resetDownLoad.height = Util.convertDpToPx(requireContext(), 60)
resetDownLoad.width = Util.convertDpToPx(requireContext(), 80)
resetDownLoad.text = "重新下载"
resetDownLoad.background = requireContext().getDrawable(R.color.btn_bg_blue)
resetDownLoad.setTextColor(requireContext().resources.getColor(R.color.white))
rightMenu.addMenuItem(resetDownLoad)
}
val layoutManager = LinearLayoutManager(context) val layoutManager = LinearLayoutManager(context)
//// 设置 RecyclerView 的固定大小,避免在滚动时重新计算视图大小和布局,提高性能 //// 设置 RecyclerView 的固定大小,避免在滚动时重新计算视图大小和布局,提高性能
@ -104,12 +111,16 @@ class TaskListFragment : BaseFragment() {
binding.taskListRecyclerview.setOnItemMenuClickListener { menuBridge, position -> binding.taskListRecyclerview.setOnItemMenuClickListener { menuBridge, position ->
menuBridge.closeMenu() menuBridge.closeMenu()
val taskBean = adapter.data[position] val taskBean = adapter.data[position]
if(menuBridge.position==0){
if (taskBean.syncStatus != FileManager.Companion.FileUploadStatus.DONE) { if (taskBean.syncStatus != FileManager.Companion.FileUploadStatus.DONE) {
Toast.makeText(context, "数据未上传,不允许关闭!", Toast.LENGTH_SHORT) Toast.makeText(context, "数据未上传,不允许关闭!", Toast.LENGTH_SHORT)
.show() .show()
} else { } else {
viewModel.removeTask(requireContext(), taskBean) viewModel.removeTask(requireContext(), taskBean)
} }
}else{
viewModel.resetDownload(requireContext(), taskBean)
}
} }
@ -134,6 +145,39 @@ class TaskListFragment : BaseFragment() {
binding.taskListRecyclerview.smoothScrollToPosition(position) binding.taskListRecyclerview.smoothScrollToPosition(position)
} }
viewModel.liveDataLoadTask.observe(viewLifecycleOwner){
when(it){
TaskLoadStatus.TASK_LOAD_STATUS_BEGIN->{
showLoadingDialog("正在切换任务")
}
TaskLoadStatus.TASK_LOAD_STATUS_FISISH->{
hideLoadingDialog()
}
}
}
viewModel.liveDataCloseTask.observe(viewLifecycleOwner){
when(it){
TaskDelStatus.TASK_DEL_STATUS_BEGIN->{
showLoadingDialog("正在重置...")
}
TaskDelStatus.TASK_DEL_STATUS_LOADING->{
showLoadingDialog("正在重置...")
}
TaskDelStatus.TASK_DEL_STATUS_SUCCESS->{
hideLoadingDialog()
Toast.makeText(context,"成功重置",Toast.LENGTH_LONG).show()
}
TaskDelStatus.TASK_DEL_STATUS_FAILED->{
hideLoadingDialog()
}
TaskDelStatus.TASK_DEL_STATUS_CANCEL->{
}
}
}
//监听并调用上传 //监听并调用上传
viewModel.liveDataTaskUpload.observe(viewLifecycleOwner) { viewModel.liveDataTaskUpload.observe(viewLifecycleOwner) {
for ((key, value) in it) { for ((key, value) in it) {

View File

@ -4,6 +4,7 @@ import android.content.Context
import android.content.SharedPreferences import android.content.SharedPreferences
import android.content.SharedPreferences.OnSharedPreferenceChangeListener import android.content.SharedPreferences.OnSharedPreferenceChangeListener
import android.os.Build import android.os.Build
import android.util.Log
import android.view.View import android.view.View
import android.widget.Toast import android.widget.Toast
import androidx.annotation.RequiresApi import androidx.annotation.RequiresApi
@ -31,6 +32,44 @@ import org.oscim.core.GeoPoint
import java.io.File import java.io.File
import javax.inject.Inject import javax.inject.Inject
enum class TaskDelStatus {
/**
* 删除开始
*/
TASK_DEL_STATUS_BEGIN,
/**
* 删除中
*/
TASK_DEL_STATUS_LOADING,
/**
* 删除成功
*/
TASK_DEL_STATUS_SUCCESS,
/**
* 删除失败
*/
TASK_DEL_STATUS_FAILED,
/**
* 取消删除
*/
TASK_DEL_STATUS_CANCEL,
}
enum class TaskLoadStatus {
/**
* 加载开始
*/
TASK_LOAD_STATUS_BEGIN,
/**
* 加载结束
*/
TASK_LOAD_STATUS_FISISH,
}
@HiltViewModel @HiltViewModel
class TaskViewModel @Inject constructor( class TaskViewModel @Inject constructor(
@ -61,7 +100,17 @@ class TaskViewModel @Inject constructor(
/** /**
* 用来确定是否关闭 * 用来确定是否关闭
*/ */
val liveDataCloseTask = MutableLiveData<Boolean>() val liveDataCloseTask = MutableLiveData<TaskDelStatus>()
/**
* 用来确定是否加载
*/
val liveDataLoadTask = MutableLiveData<TaskLoadStatus>()
/**
* 用来更新任务
*/
val liveDataUpdateTask = MutableLiveData<TaskBean>()
/** /**
* 提示信息 * 提示信息
@ -107,13 +156,14 @@ class TaskViewModel @Inject constructor(
if (currentSelectTaskBean == null) { if (currentSelectTaskBean == null) {
liveDataToastMessage.postValue("还没有开启任何任务") liveDataToastMessage.postValue("还没有开启任何任务")
} else { } else {
val links = realmOperateHelper.queryLink(realm, val links = realmOperateHelper.queryLink(
realm,
point = point, point = point,
) )
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
} }
} }
@ -125,13 +175,14 @@ class TaskViewModel @Inject constructor(
} else { } else {
viewModelScope.launch(Dispatchers.IO) { viewModelScope.launch(Dispatchers.IO) {
val realm = realmOperateHelper.getSelectTaskRealmInstance() val realm = realmOperateHelper.getSelectTaskRealmInstance()
val links = realmOperateHelper.queryLink(realm, val links = realmOperateHelper.queryLink(
realm,
point = point, point = point,
) )
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
@ -178,6 +229,13 @@ class TaskViewModel @Inject constructor(
task.fileSize = item.fileSize task.fileSize = item.fileSize
task.status = item.status task.status = item.status
task.currentSize = item.currentSize task.currentSize = item.currentSize
//增加mesh==null兼容性处理
for (hadLink in item.hadLinkDvoList) {
if (hadLink.mesh == null) {
hadLink.mesh = ""
Log.e("qj", "${task.id}==null")
}
}
task.hadLinkDvoList = item.hadLinkDvoList task.hadLinkDvoList = item.hadLinkDvoList
task.syncStatus = item.syncStatus task.syncStatus = item.syncStatus
//已上传后不在更新操作时间 //已上传后不在更新操作时间
@ -190,10 +248,15 @@ class TaskViewModel @Inject constructor(
} else { } else {
for (hadLink in task.hadLinkDvoList) { for (hadLink in task.hadLinkDvoList) {
hadLink.taskId = task.id hadLink.taskId = task.id
if (hadLink.mesh == null) {
hadLink.mesh = ""
Log.e("qj", "${task.id}==新增==null")
}
} }
//赋值时间,用于查询过滤 //赋值时间,用于查询过滤
task.operationTime = DateTimeUtil.getNowDate().time task.operationTime = DateTimeUtil.getNowDate().time
} }
Log.e("qj", "${task.id}")
realm.copyToRealmOrUpdate(task) realm.copyToRealmOrUpdate(task)
} }
} }
@ -271,7 +334,34 @@ class TaskViewModel @Inject constructor(
currentSelectTaskBean = taskBean currentSelectTaskBean = taskBean
liveDataTaskLinks.value = taskBean.hadLinkDvoList liveDataTaskLinks.value = taskBean.hadLinkDvoList
liveDataLoadTask.postValue(TaskLoadStatus.TASK_LOAD_STATUS_BEGIN)
showTaskLinks(taskBean) showTaskLinks(taskBean)
//重新加载轨迹
viewModelScope.launch(Dispatchers.IO) {
Constant.TRACE_COUNT = 0
val list: List<NiLocation>? = TraceDataBase.getDatabase(
mapController.mMapView.context, Constant.USER_DATA_PATH
).niLocationDao.findToTaskIdAll(taskBean.id.toString())
list!!.forEach {
Constant.TRACE_COUNT ++
if(Constant.TRACE_COUNT%Constant.TRACE_COUNT_MORE_TIME==0){
mapController.markerHandle.addNiLocationMarkerItemRough(it)
}
if(Constant.TRACE_COUNT%Constant.TRACE_COUNT_TIME==0){
mapController.markerHandle.addNiLocationMarkerItemSimple(it)
}
mapController.markerHandle.addNiLocationMarkerItem(it)
}
liveDataLoadTask.postValue(TaskLoadStatus.TASK_LOAD_STATUS_FISISH)
withContext(Dispatchers.Main){
MapParamUtils.setTaskId(taskBean.id) MapParamUtils.setTaskId(taskBean.id)
Constant.currentSelectTaskFolder = File(Constant.USER_DATA_PATH + "/${taskBean.id}") Constant.currentSelectTaskFolder = File(Constant.USER_DATA_PATH + "/${taskBean.id}")
Constant.currentSelectTaskConfig = Constant.currentSelectTaskConfig =
@ -282,6 +372,8 @@ class TaskViewModel @Inject constructor(
mapController.layerManagerHandler.updateOMDBVectorTileLayer() mapController.layerManagerHandler.updateOMDBVectorTileLayer()
mapController.mMapView.updateMap(true) mapController.mMapView.updateMap(true)
} }
}
}
private fun showTaskLinks(taskBean: TaskBean) { private fun showTaskLinks(taskBean: TaskBean) {
@ -410,6 +502,71 @@ 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()
}
/** /**
* 关闭任务 * 关闭任务
*/ */
@ -421,7 +578,9 @@ 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 =
@ -455,14 +614,14 @@ class TaskViewModel @Inject constructor(
FileManager.checkOMDBFileInfo(item) FileManager.checkOMDBFileInfo(item)
} }
liveDataTaskList.postValue(taskList) liveDataTaskList.postValue(taskList)
liveDataCloseTask.postValue(true) liveDataCloseTask.postValue(TaskDelStatus.TASK_DEL_STATUS_SUCCESS)
realm.close() realm.close()
} }
} }
mDialog.setNegativeButton( mDialog.setNegativeButton(
"取消" "取消"
) { _, _ -> ) { _, _ ->
liveDataCloseTask.postValue(false) liveDataCloseTask.postValue(TaskDelStatus.TASK_DEL_STATUS_CANCEL)
mDialog.dismiss() mDialog.dismiss()
} }
mDialog.show() mDialog.show()
@ -559,7 +718,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
) )
@ -572,7 +731,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) {
@ -628,7 +787,10 @@ class TaskViewModel @Inject constructor(
//重置数据为隐藏 //重置数据为隐藏
if (hadLinkDvoBean.linkStatus == 2) { if (hadLinkDvoBean.linkStatus == 2) {
realmOperateHelper.queryLinkToMutableRenderEntityList(realm,hadLinkDvoBean.linkPid) realmOperateHelper.queryLinkToMutableRenderEntityList(
realm,
hadLinkDvoBean.linkPid
)
?.forEach { renderEntity -> ?.forEach { renderEntity ->
if (renderEntity.enable == 1) { if (renderEntity.enable == 1) {
renderEntity.enable = 0 renderEntity.enable = 0

View File

@ -0,0 +1,349 @@
package com.navinfo.omqs.util;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.content.Context;
import android.util.Log;
import com.navinfo.omqs.Constant;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* 带日志文件输入的又可控开关的日志调试
*
* @author qj
* @version 1.0
* @data 2016-8-23
*/
public class CMLog {
//CrashHandler实例
/**
*
*/
private static CMLog instance;
/**
*
*/
private static Boolean MYLOG_SWITCH = true; //日志文件总开关
/**
*
*/
private static Boolean MYLOG_WRITE_TO_FILE = true;//日志写入文件开关
/**
*
*/
private static char MYLOG_TYPE = 'v';//输入日志类型w代表只输出告警信息等v代表输出所有信息
// private static String MYLOG_PATH_SDCARD_DIR = FMConstant.USER_DATA_LOG_PATH;// 日志文件在sdcard中的路径
/**
*
*/
private static int SDCARD_LOG_FILE_SAVE_DAYS = 0;// sd卡中日志文件的最多保存天数
/**
*
*/
private static String MYLOGFILEName = "Log.txt";// 本类输出的日志文件名称
/**
*
*/
private static String STACKLOGFILEName = "StackLog.txt";// 本类输出的日志文件名称
/**
*
*/
private static SimpleDateFormat myLogSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//日志的输出格式
/**
*
*/
private static SimpleDateFormat logfile = new SimpleDateFormat("yyyy-MM-dd-HH");//日志文件格式
/**
*
*/
private static Context mContext;
/**
*
*/
private static boolean flag;
/**
*
*/
private static int count = 0;
/**
*
*/
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
/**
* 获取CrashHandler实例 ,单例模式
* @return
*/
public static CMLog getInstance() {
if (instance == null)
instance = new CMLog();
return instance;
}
/**
* 初始化
* @param context
*/
public void init(Context context) {
mContext = context;
}
/**
* @param tag
* @param msg
*/
public static void w(String tag, Object msg) {//警告信息
log(tag, msg.toString(), 'w');
}
/**
* @param tag
* @param msg
*/
public static void e(String tag, Object msg) {//错误信息
log(tag, msg.toString(), 'e');
}
/**
* @param tag
* @param msg
*/
public static void d(String tag, Object msg) {//调试信息
log(tag, msg.toString(), 'd');
}
/**
* @param tag
* @param msg
*/
public static void i(String tag, Object msg) {//
log(tag, msg.toString(), 'i');
}
/**
* @param tag
* @param msg
*/
public static void v(String tag, Object msg) {
log(tag, msg.toString(), 'v');
}
/**
* @param tag
* @param text
*/
public static void w(String tag, String text) {
log(tag, text, 'w');
}
/**
* @param tag
* @param text
*/
public static void e(String tag, String text) {
log(tag, text, 'e');
}
/**
* @param tag
* @param text
*/
public static void d(String tag, String text) {
log(tag, text, 'd');
}
/**
* @param tag
* @param text
*/
public static void i(String tag, String text) {
log(tag, text, 'i');
}
/**
* @param tag
* @param text
*/
public static void v(String tag, String text) {
log(tag, text, 'v');
}
/**
* 根据tag, msg和等级输出日志
*
* @param tag
* @param msg
* @param level
* @return void
* @since v 1.0
*/
private static void log(String tag, String msg, char level) {
if (MYLOG_SWITCH) {
if ('e' == level && ('e' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) { // 输出错误信息
Log.e(tag, msg);
} else if ('w' == level && ('w' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) {
Log.w(tag, msg);
} else if ('d' == level && ('d' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) {
Log.d(tag, msg);
} else if ('i' == level && ('d' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) {
Log.i(tag, msg);
} else {
Log.v(tag, msg);
}
if (MYLOG_WRITE_TO_FILE)
writeLogtoFile(String.valueOf(level), tag, msg);
}
}
/**
* 打开日志文件并写入日志
*
* @param mylogtype
* @param tag
* @param text
**/
public static void writeLogtoFile(String mylogtype, String tag, String text) {
if (!flag&&MYLOG_WRITE_TO_FILE) {
flag = true;
try {
Log.e("qj", "日志写入0");
// 新建或打开日志文件
Date nowtime = new Date();
String needWriteFiel = logfile.format(nowtime);
// String needWriteMessage = myLogSdf.format(nowtime) + " " + mylogtype
String needWriteMessage = simpleDateFormat.format(nowtime) + " " + mylogtype
+ " " + count + " " + tag + " " + text + "\r\n";
//输出内存使用情况
ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
MemoryInfo memoryInfo = new MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);
/* needWriteMessage += " 系统剩余内存: " + (memoryInfo.availMem / 1024) + "(KB)\n";
needWriteMessage += " 系统是否处于低内存运行: " + memoryInfo.lowMemory + "\n";
needWriteMessage += " 当系统剩余内存低于: " + (memoryInfo.threshold / 1024) + "(KB)\n";*/
if (new File(Constant.USER_DATA_LOG_PATH).exists() == false) {
new File(Constant.USER_DATA_LOG_PATH).mkdirs();
}
File file = new File(Constant.USER_DATA_LOG_PATH, needWriteFiel + MYLOGFILEName);
Log.e("qj", "日志写入1");
if (!file.exists())
file.createNewFile();
Log.e("qj", "日志写入2");
FileWriter filerWriter = new FileWriter(file, true);//后面这个参数代表是不是要接上文件中原来的数据不进行覆盖
BufferedWriter bufWriter = new BufferedWriter(filerWriter);
bufWriter.write(needWriteMessage);
bufWriter.newLine();
bufWriter.close();
filerWriter.close();
Log.e("qj", "日志写入结束");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
flag = false;
}
}
count ++;
if(count>10000){
count = 0;
}
}
/**
* 写入调用栈的信息包括文件名行号接口名称
*
* @param extMsg 扩展信息如果不为NULL则输出到栈信息之前
*/
public static void writeStackLogtoFile(String extMsg) {// 新建或打开日志文件
StackTraceElement[] eles = Thread.currentThread().getStackTrace();
Date nowtime = new Date();
String needWriteFiel = logfile.format(nowtime);
String needWriteMessage = "[Java Stack]:" + myLogSdf.format(nowtime) + "\n";
if(eles!=null&&eles.length>3){
needWriteMessage += "\t file name :" + eles[3].getFileName() + "\n";
needWriteMessage += "\t line num :" + eles[3].getLineNumber() + "\n";
needWriteMessage += "\t class name:" + eles[3].getClassName() + "\n";
needWriteMessage += "\t method :" + eles[3].getMethodName() + "\n";
}
if (extMsg != null && extMsg.length() > 0) {
needWriteMessage += "\t extMsg :" + extMsg + "\n";
}
if (new File(Constant.USER_DATA_LOG_PATH).exists() == false) {
new File(Constant.USER_DATA_LOG_PATH).mkdirs();
}
File file = new File(Constant.USER_DATA_LOG_PATH, needWriteFiel
+ STACKLOGFILEName);
try {
FileWriter filerWriter = new FileWriter(file, true);//后面这个参数代表是不是要接上文件中原来的数据不进行覆盖
BufferedWriter bufWriter = new BufferedWriter(filerWriter);
bufWriter.write(needWriteMessage);
bufWriter.newLine();
bufWriter.close();
filerWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 删除制定的日志文件
*/
public static void delFile() {// 删除日志文件
String needDelFiel = logfile.format(getDateBefore());
File file = new File(Constant.USER_DATA_LOG_PATH, needDelFiel + MYLOGFILEName);
if (file.exists()) {
file.delete();
}
}
/**
* 得到现在时间前的几天日期用来得到需要删除的日志文件名
* @return
*/
private static Date getDateBefore() {
Date nowtime = new Date();
Calendar now = Calendar.getInstance();
now.setTime(nowtime);
now.set(Calendar.DATE, now.get(Calendar.DATE)
- SDCARD_LOG_FILE_SAVE_DAYS);
return now.getTime();
}
//输出错误日志
/**
* 得到现在时间前的几天日期用来得到需要删除的日志文件名
* @param e
* @param TAG
*/
public static void writeStackLogtoFile(Exception e, String TAG) {
String errorInfo = "";
for (int i = 0; i < e.getStackTrace().length; i++) {
errorInfo += e.getStackTrace()[i];
}
writeLogtoFile("异常崩溃", "异常", "异常信息:" + errorInfo);
}
/**
* @param mylogWriteToFile
*/
public static void setMylogWriteToFile(Boolean mylogWriteToFile) {
MYLOG_WRITE_TO_FILE = mylogWriteToFile;
}
}

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 {
@ -73,6 +75,7 @@ class NaviEngine(
DataCodeEnum.OMDB_TRAFFICLIGHT.name, DataCodeEnum.OMDB_TRAFFICLIGHT.name,
// DataCodeEnum.OMDB_RESTRICTION.name, // DataCodeEnum.OMDB_RESTRICTION.name,
DataCodeEnum.OMDB_LANEINFO.name, DataCodeEnum.OMDB_LANEINFO.name,
DataCodeEnum.OMDB_CLM_LANEINFO.name,
DataCodeEnum.OMDB_TRAFFIC_SIGN.name, DataCodeEnum.OMDB_TRAFFIC_SIGN.name,
DataCodeEnum.OMDB_WARNINGSIGN.name, DataCodeEnum.OMDB_WARNINGSIGN.name,
DataCodeEnum.OMDB_TOLLGATE.name DataCodeEnum.OMDB_TOLLGATE.name
@ -205,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(
@ -217,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
@ -255,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
} }
@ -346,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
@ -356,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,84 @@
package com.navinfo.omqs.util
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.GeometryTools
import com.navinfo.omqs.db.RealmOperateHelper
import io.realm.Realm
import org.oscim.core.GeoPoint
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
) {
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(
@ -107,7 +107,7 @@ class SignUtil {
//物理车道数OMDB_PHY_LANENUM //物理车道数OMDB_PHY_LANENUM
DataCodeEnum.OMDB_LANE_NUM.code, DataCodeEnum.OMDB_LANE_NUM.code,
DataCodeEnum.OMDB_PHY_LANENUM.code -> { DataCodeEnum.OMDB_PHY_LANENUM.code -> {
"${data.properties["laneNum"]}|${data.properties["laneS2e"]}|${data.properties["laneE2s"]}" "${data.properties["laneS2e"]}|${data.properties["laneE2s"]}"
} }
//常规点限速,条件点限速 //常规点限速,条件点限速
@ -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 {
@ -286,11 +286,11 @@ class SignUtil {
//车道数//增加物理车道数DataCodeEnum.OMDB_PHY_LANENUM.code //车道数//增加物理车道数DataCodeEnum.OMDB_PHY_LANENUM.code
DataCodeEnum.OMDB_PHY_LANENUM.code, DataCodeEnum.OMDB_PHY_LANENUM.code,
DataCodeEnum.OMDB_LANE_NUM.code -> { DataCodeEnum.OMDB_LANE_NUM.code -> {
list.add( /* list.add(
TwoItemAdapterItem( TwoItemAdapterItem(
title = "车道总数", text = "${data.properties["laneNum"]}" title = "车道总数", text = "${data.properties["laneNum"]}"
) )
) )*/
list.add( list.add(
TwoItemAdapterItem( TwoItemAdapterItem(
title = "顺方向车道数", text = "${data.properties["laneS2e"]}" title = "顺方向车道数", text = "${data.properties["laneS2e"]}"
@ -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)
@ -1426,14 +1426,14 @@ class SignUtil {
) )
DataCodeEnum.OMDB_RD_LINK_KIND.code -> stringBuffer.append("种别${item.iconText},") DataCodeEnum.OMDB_RD_LINK_KIND.code -> stringBuffer.append("种别${item.iconText},")
DataCodeEnum.OMDB_LINK_DIRECT.code -> stringBuffer.append("${item.iconText},") DataCodeEnum.OMDB_LINK_DIRECT.code -> stringBuffer.append("${item.iconText},")
DataCodeEnum.OMDB_PHY_LANENUM.code,//物理车道数 /* DataCodeEnum.OMDB_PHY_LANENUM.code,//物理车道数
DataCodeEnum.OMDB_LANE_NUM.code -> stringBuffer.append( DataCodeEnum.OMDB_LANE_NUM.code -> stringBuffer.append(
"${ "${
item.iconText.substringBefore( item.iconText.substringBefore(
"|" "|"
) )
}车道" }车道"
) )*/
} }
} }
return stringBuffer.toString() return stringBuffer.toString()

View File

@ -48,12 +48,17 @@
android:title="锁定地图旋转及视角" /> android:title="锁定地图旋转及视角" />
<item <item
android:id="@+id/personal_center_menu_marker" android:id="@+id/personal_center_menu_marker"
android:icon="@drawable/baseline_person_24" android:icon="@drawable/baseline_map_24"
android:visible="true" android:visible="true"
android:title="隐藏Marker" /> android:title="隐藏Marker" />
<item
android:id="@+id/personal_center_menu_trace"
android:icon="@drawable/baseline_map_24"
android:visible="true"
android:title="隐藏轨迹" />
<item <item
android:id="@+id/personal_center_menu_catch_all" android:id="@+id/personal_center_menu_catch_all"
android:icon="@drawable/baseline_person_24" android:icon="@drawable/baseline_map_24"
android:visible="true" android:visible="true"
android:title="全要素捕捉" /> android:title="全要素捕捉" />
<item <item

View File

@ -120,6 +120,7 @@ dependencies {
api 'org.locationtech.jts:jts-core:1.19.0' api 'org.locationtech.jts:jts-core:1.19.0'
implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.11' implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.11'
implementation 'com.squareup.okio:okio:3.3.0' implementation 'com.squareup.okio:okio:3.3.0'
implementation 'com.alibaba:fastjson:1.2.73'
implementation "com.fasterxml.jackson.core:jackson-annotations:2.9.9" implementation "com.fasterxml.jackson.core:jackson-annotations:2.9.9"
implementation "com.fasterxml.jackson.core:jackson-core:2.9.9" implementation "com.fasterxml.jackson.core:jackson-core:2.9.9"

View File

@ -1558,7 +1558,6 @@
<symbol repeat="false" repeat-start="0" repeat-gap="2000" <symbol repeat="false" repeat-start="0" repeat-gap="2000"
src="@symbol" symbol-height="24" degree="90"></symbol> src="@symbol" symbol-height="24" degree="90"></symbol>
</m> </m>
<!-- 杆状物 --> <!-- 杆状物 -->
<m v="OMDB_POLE"> <m v="OMDB_POLE">
<symbol src="assets:omdb/icon_pole_3006.svg" symbol-height="56" symbol-width="56"></symbol> <symbol src="assets:omdb/icon_pole_3006.svg" symbol-height="56" symbol-width="56"></symbol>
@ -1720,22 +1719,22 @@
<m k="markType" v="6"> <m k="markType" v="6">
<!--其他|实线--> <!--其他|实线-->
<m k="markColor" v="1"> <m k="markColor" v="1">
<symbol repeat="true" repeat-start="0" repeat-gap="24" src="assets:omdb/icon_2013_1.svg"/> <symbol repeat="true" repeat-start="0" repeat-gap="32" symbol-height="8" symbol-width="8" src="assets:omdb/icon_2013_1.svg"/>
</m> </m>
<m k="markColor" v="2"> <m k="markColor" v="2">
<symbol repeat="true" repeat-start="0" repeat-gap="24" src="assets:omdb/icon_2013_2.svg"></symbol> <symbol repeat="true" repeat-start="0" repeat-gap="32" symbol-height="8" symbol-width="8" src="assets:omdb/icon_2013_2.svg"></symbol>
</m> </m>
<m k="markColor" v="6"> <m k="markColor" v="6">
<symbol repeat="true" repeat-start="0" repeat-gap="24" src="assets:omdb/icon_2013_6.svg"></symbol> <symbol repeat="true" repeat-start="0" repeat-gap="32" symbol-height="8" symbol-width="8" src="assets:omdb/icon_2013_6.svg"></symbol>
</m> </m>
<m k="markColor" v="7"> <m k="markColor" v="7">
<symbol repeat="true" repeat-start="0" repeat-gap="24" src="assets:omdb/icon_2013_7.svg"></symbol> <symbol repeat="true" repeat-start="0" repeat-gap="32" symbol-height="8" symbol-width="8" src="assets:omdb/icon_2013_7.svg"></symbol>
</m> </m>
<m k="markColor" v="0|9"> <m k="markColor" v="0|9">
<symbol repeat="true" repeat-start="0" repeat-gap="24" src="assets:omdb/icon_2013_0.svg"></symbol> <symbol repeat="true" repeat-start="0" repeat-gap="32" symbol-height="8" symbol-width="8" src="assets:omdb/icon_2013_0.svg"></symbol>
</m> </m>
</m> </m>
</m> </m>

View File

@ -1,11 +1,10 @@
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" <?xml version="1.0" encoding="UTF-8"?>
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg id="b" xmlns="http://www.w3.org/2000/svg" width="136.1" height="113.4"
<svg t="1695622778812" class="icon" viewBox="0 0 1024 1024" version="1.1" viewBox="0 0 136.1 113.4">
xmlns="http://www.w3.org/2000/svg" p-id="8830" xmlns:xlink="http://www.w3.org/1999/xlink" <g id="c">
width="48" height="48"> <g>
<path <rect width="136.1" height="113.4" style="fill:none;" />
d="M284.444444 227.555556h739.555556L739.555556 796.444444H0L284.444444 227.555556z m26.368 42.666666l-241.777777 483.555556h644.152889l241.777777-483.555556H310.812444z" <polygon points="109.7 56.7 0 56.7 26.4 0 136.1 0 109.7 56.7" style="fill:#8e44ad;" />
fill="#8e44ad" p-id="8831"></path> </g>
<path d="M310.812444 270.222222l-241.777777 483.555556h644.152889l241.777777-483.555556z" </g>
fill="#8e44ad" fill-opacity=".99" p-id="8832"></path>
</svg> </svg>

Before

Width:  |  Height:  |  Size: 730 B

After

Width:  |  Height:  |  Size: 369 B

View File

@ -1,11 +1,10 @@
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" <?xml version="1.0" encoding="UTF-8"?>
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg id="b" xmlns="http://www.w3.org/2000/svg" width="136.1" height="113.4"
<svg t="1695622778812" class="icon" viewBox="0 0 1024 1024" version="1.1" viewBox="0 0 136.1 113.4">
xmlns="http://www.w3.org/2000/svg" p-id="8830" xmlns:xlink="http://www.w3.org/1999/xlink" <g id="c">
width="48" height="48"> <g>
<path <rect width="136.1" height="113.4" style="fill:none;" />
d="M284.444444 227.555556h739.555556L739.555556 796.444444H0L284.444444 227.555556z m26.368 42.666666l-241.777777 483.555556h644.152889l241.777777-483.555556H310.812444z" <polygon points="109.7 56.7 0 56.7 26.4 0 136.1 0 109.7 56.7" style="fill:#fff;" />
fill="#ffffff" p-id="8831"></path> </g>
<path d="M310.812444 270.222222l-241.777777 483.555556h644.152889l241.777777-483.555556z" </g>
fill="#ffffff" fill-opacity=".99" p-id="8832"></path>
</svg> </svg>

Before

Width:  |  Height:  |  Size: 730 B

After

Width:  |  Height:  |  Size: 366 B

View File

@ -1,11 +1,10 @@
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" <?xml version="1.0" encoding="UTF-8"?>
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg id="b" xmlns="http://www.w3.org/2000/svg" width="136.1" height="113.4"
<svg t="1695622778812" class="icon" viewBox="0 0 1024 1024" version="1.1" viewBox="0 0 136.1 113.4">
xmlns="http://www.w3.org/2000/svg" p-id="8830" xmlns:xlink="http://www.w3.org/1999/xlink" <g id="c">
width="48" height="48"> <g>
<path <rect width="136.1" height="113.4" style="fill:none;" />
d="M284.444444 227.555556h739.555556L739.555556 796.444444H0L284.444444 227.555556z m26.368 42.666666l-241.777777 483.555556h644.152889l241.777777-483.555556H310.812444z" <polygon points="109.7 56.7 0 56.7 26.4 0 136.1 0 109.7 56.7" style="fill:#eccc68;" />
fill="#eccc68" p-id="8831"></path> </g>
<path d="M310.812444 270.222222l-241.777777 483.555556h644.152889l241.777777-483.555556z" </g>
fill="#eccc68" fill-opacity=".99" p-id="8832"></path>
</svg> </svg>

Before

Width:  |  Height:  |  Size: 730 B

After

Width:  |  Height:  |  Size: 369 B

View File

@ -1,11 +1,10 @@
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" <?xml version="1.0" encoding="UTF-8"?>
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg id="b" xmlns="http://www.w3.org/2000/svg" width="136.1" height="113.4"
<svg t="1695622778812" class="icon" viewBox="0 0 1024 1024" version="1.1" viewBox="0 0 136.1 113.4">
xmlns="http://www.w3.org/2000/svg" p-id="8830" xmlns:xlink="http://www.w3.org/1999/xlink" <g id="c">
width="48" height="48"> <g>
<path <rect width="136.1" height="113.4" style="fill:none;" />
d="M284.444444 227.555556h739.555556L739.555556 796.444444H0L284.444444 227.555556z m26.368 42.666666l-241.777777 483.555556h644.152889l241.777777-483.555556H310.812444z" <polygon points="109.7 56.7 0 56.7 26.4 0 136.1 0 109.7 56.7" style="fill:#0000ff;" />
fill="#0000ff" p-id="8831"></path> </g>
<path d="M310.812444 270.222222l-241.777777 483.555556h644.152889l241.777777-483.555556z" </g>
fill="#0000ff" fill-opacity=".99" p-id="8832"></path>
</svg> </svg>

Before

Width:  |  Height:  |  Size: 730 B

After

Width:  |  Height:  |  Size: 369 B

View File

@ -1,11 +1,10 @@
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" <?xml version="1.0" encoding="UTF-8"?>
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg id="b" xmlns="http://www.w3.org/2000/svg" width="136.1" height="113.4"
<svg t="1695622778812" class="icon" viewBox="0 0 1024 1024" version="1.1" viewBox="0 0 136.1 113.4">
xmlns="http://www.w3.org/2000/svg" p-id="8830" xmlns:xlink="http://www.w3.org/1999/xlink" <g id="c">
width="48" height="48"> <g>
<path <rect width="136.1" height="113.4" style="fill:none;" />
d="M284.444444 227.555556h739.555556L739.555556 796.444444H0L284.444444 227.555556z m26.368 42.666666l-241.777777 483.555556h644.152889l241.777777-483.555556H310.812444z" <polygon points="109.7 56.7 0 56.7 26.4 0 136.1 0 109.7 56.7" style="fill:#00ff00;" />
fill="#00ff00" p-id="8831"></path> </g>
<path d="M310.812444 270.222222l-241.777777 483.555556h644.152889l241.777777-483.555556z" </g>
fill="#00ff00" fill-opacity=".99" p-id="8832"></path>
</svg> </svg>

Before

Width:  |  Height:  |  Size: 730 B

After

Width:  |  Height:  |  Size: 369 B

View File

@ -1,5 +1,7 @@
package com.navinfo.collect.library.data.entity package com.navinfo.collect.library.data.entity
import com.navinfo.collect.library.utils.GeometryTools
import com.navinfo.collect.library.utils.GeometryToolsKt
import io.realm.RealmObject import io.realm.RealmObject
import io.realm.annotations.PrimaryKey import io.realm.annotations.PrimaryKey
@ -12,11 +14,13 @@ open class HadLinkDvoBean @JvmOverloads constructor(
* 图幅号 * 图幅号
*/ */
var mesh: String = "", var mesh: String = "",
/** /**
* linkPid * linkPid
*/ */
@PrimaryKey @PrimaryKey
var linkPid: String = "", var linkPid: String = "",
/** /**
* (几何)加偏后 * (几何)加偏后
*/ */
@ -31,10 +35,12 @@ open class HadLinkDvoBean @JvmOverloads constructor(
* 1:源库link2选择link 3现场新增 * 1:源库link2选择link 3现场新增
*/ */
var linkStatus: Int = 1, var linkStatus: Int = 1,
/** /**
* 详细属性 * 详细属性
*/ */
var linkInfo: LinkInfoBean? = null, var linkInfo: LinkInfoBean? = null,
/** /**
* 长度 * 长度
*/ */

View File

@ -0,0 +1,30 @@
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 {
@Index
var linkPid:String = ""
@Index
var sNodeId: String? = null
@Index
var eNodeId: String? = null
}

View File

@ -1,7 +1,12 @@
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.DeflaterUtil
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 +19,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 +49,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 +76,26 @@ open class ReferenceEntity() : RealmObject() {
} }
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(DeflaterUtil.unzipString(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,59 @@
package com.navinfo.collect.library.data.entity package com.navinfo.collect.library.data.entity
import android.os.Parcelable import android.os.Parcelable
import com.navinfo.collect.library.system.Constant import android.util.Log
import com.alibaba.fastjson.JSON
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.navinfo.collect.library.utils.DeflaterUtil
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.PrimaryKey import io.realm.annotations.Index
import kotlinx.parcelize.Parcelize import kotlinx.parcelize.Parcelize
import org.locationtech.jts.geom.Coordinate
import org.locationtech.jts.geom.Geometry import org.locationtech.jts.geom.Geometry
import org.oscim.core.MercatorProjection
import java.util.*
/** /**
* 渲染要素对应的实体 * 渲染要素对应的实体
* */ * */
@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 +69,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(DeflaterUtil.unzipString(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捕捉
@Index
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

@ -81,6 +81,7 @@ enum class DataCodeEnum(var tableName: String, var code: String) {
OMDB_TRAFFICLIGHT("交通灯", "4022"), OMDB_TRAFFICLIGHT("交通灯", "4022"),
OMDB_TOLLGATE("收费站", "4023"), OMDB_TOLLGATE("收费站", "4023"),
OMDB_LANEINFO("车信", "4601"), OMDB_LANEINFO("车信", "4601"),
OMDB_CLM_LANEINFO("车信CLM", "4602"),
OMDB_LANE_LINK_LG("车道中心线", "5001"); OMDB_LANE_LINK_LG("车道中心线", "5001");
companion object { companion object {

View File

@ -608,6 +608,7 @@ public final class NIMapView extends RelativeLayout {
LABEL(4)/*图标,文字图层*/, LABEL(4)/*图标,文字图层*/,
OPERATE_LINE(5)/*操作图层组*/, OPERATE_LINE(5)/*操作图层组*/,
OPERATE_MARKER(6)/*操作图层组*/; OPERATE_MARKER(6)/*操作图层组*/;
int groupIndex; int groupIndex;
LAYER_GROUPS(int groupIndex) { LAYER_GROUPS(int groupIndex) {

View File

@ -171,7 +171,7 @@ class LocationLayerHandler(context: AppCompatActivity, mapView: NIMapView) :
mCurrentLocation?.run { mCurrentLocation?.run {
val mapPosition = mMapView.vtmMap.mapPosition val mapPosition = mMapView.vtmMap.mapPosition
mapPosition.setPosition(this.latitude, this.longitude) mapPosition.setPosition(this.latitude, this.longitude)
mMapView.vtmMap.animator().animateTo(300, mapPosition) mMapView.vtmMap.animator().animateTo(800, mapPosition)
} }
} }
@ -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

@ -28,6 +28,8 @@ import org.oscim.backend.canvas.Paint
import org.oscim.core.GeoPoint import org.oscim.core.GeoPoint
import org.oscim.layers.marker.* import org.oscim.layers.marker.*
import org.oscim.layers.marker.ItemizedLayer.OnItemGestureListener import org.oscim.layers.marker.ItemizedLayer.OnItemGestureListener
import org.oscim.layers.tile.vector.VectorTileLayer
import org.oscim.layers.vector.VectorLayer
import org.oscim.layers.vector.geometries.* import org.oscim.layers.vector.geometries.*
import org.oscim.map.Map import org.oscim.map.Map
import java.util.* import java.util.*
@ -43,8 +45,17 @@ class MarkHandler(context: AppCompatActivity, mapView: NIMapView) :
*/ */
private val mDefaultTextColor = "#4E55AF" private val mDefaultTextColor = "#4E55AF"
/**
* 默认Marker可用状态
*/
private var markerEnable = true private var markerEnable = true
/**
* 默认轨迹可用状态
*/
private var traceMarkerEnable = true
/** /**
* 文字画笔 * 文字画笔
*/ */
@ -179,6 +190,68 @@ class MarkHandler(context: AppCompatActivity, mapView: NIMapView) :
layer layer
} }
/**
* 评测精简数据marker 图层
*/
private val niLocationItemizedLayerRough: ItemizedLayer by lazy {
val symbol = MarkerSymbol(niLocationBitmap, MarkerSymbol.HotspotPlace.CENTER)
val layerRough = ItemizedLayer(
mapView.vtmMap,
symbol,
)
layerRough.setOnItemGestureListener(object : OnItemGestureListener<MarkerInterface> {
override fun onItemSingleTapUp(index: Int, item: MarkerInterface?): Boolean {
val tag = mMapView.listenerTagList.last()
val listenerList = mMapView.listenerList[tag]
if (listenerList != null) {
for (listener in listenerList) {
}
}
return true
}
override fun onItemLongPress(index: Int, item: MarkerInterface?): Boolean {
return true
}
})
layerRough.isEnabled = false
addLayer(layerRough, NIMapView.LAYER_GROUPS.OPERATE_MARKER)
layerRough
}
/**
* 评测精简数据marker 图层
*/
private val niLocationItemizedLayerSimple: ItemizedLayer by lazy {
val symbol = MarkerSymbol(niLocationBitmap, MarkerSymbol.HotspotPlace.CENTER)
val layerSimple = ItemizedLayer(
mapView.vtmMap,
symbol,
)
layerSimple.setOnItemGestureListener(object : OnItemGestureListener<MarkerInterface> {
override fun onItemSingleTapUp(index: Int, item: MarkerInterface?): Boolean {
val tag = mMapView.listenerTagList.last()
val listenerList = mMapView.listenerList[tag]
if (listenerList != null) {
for (listener in listenerList) {
}
}
return true
}
override fun onItemLongPress(index: Int, item: MarkerInterface?): Boolean {
return true
}
})
addLayer(layerSimple, NIMapView.LAYER_GROUPS.OPERATE_MARKER)
layerSimple
}
/** /**
* 评测数据marker 图层 * 评测数据marker 图层
*/ */
@ -213,7 +286,7 @@ class MarkHandler(context: AppCompatActivity, mapView: NIMapView) :
} }
}) })
layer.isEnabled = false
addLayer(layer, NIMapView.LAYER_GROUPS.OPERATE_MARKER) addLayer(layer, NIMapView.LAYER_GROUPS.OPERATE_MARKER)
layer layer
} }
@ -282,8 +355,15 @@ class MarkHandler(context: AppCompatActivity, mapView: NIMapView) :
} else { } else {
qsRecordItemizedLayer.isEnabled = false qsRecordItemizedLayer.isEnabled = false
} }
if (traceMarkerEnable) {
niLocationItemizedLayer.isEnabled = mapPosition.getZoomLevel() >= 12 niLocationItemizedLayer.isEnabled = mapPosition.getZoomLevel() in 18..20
niLocationItemizedLayerSimple.isEnabled = mapPosition.getZoomLevel() in 14..17
niLocationItemizedLayerRough.isEnabled = mapPosition.getZoomLevel() in 12..13
} else {
niLocationItemizedLayer.isEnabled = false
niLocationItemizedLayerSimple.isEnabled = false
niLocationItemizedLayerRough.isEnabled = false
}
} }
}) })
} }
@ -379,6 +459,9 @@ class MarkHandler(context: AppCompatActivity, mapView: NIMapView) :
mMapView.updateMap(true) mMapView.updateMap(true)
} }
/**
* Marker是否显示
*/
fun setQsRecordMarkEnable(enable: Boolean) { fun setQsRecordMarkEnable(enable: Boolean) {
qsRecordItemizedLayer.isEnabled = enable qsRecordItemizedLayer.isEnabled = enable
markerEnable = enable markerEnable = enable
@ -386,6 +469,20 @@ class MarkHandler(context: AppCompatActivity, mapView: NIMapView) :
mMapView.updateMap(true) mMapView.updateMap(true)
} }
/**
* 轨迹是否显示
*/
fun setTraceMarkEnable(enable: Boolean) {
niLocationItemizedLayer.isEnabled = enable
niLocationItemizedLayerSimple.isEnabled = enable
niLocationItemizedLayerRough.isEnabled = enable
traceMarkerEnable = enable
niLocationItemizedLayer.populate()
niLocationItemizedLayerSimple.populate()
niLocationItemizedLayerRough.populate()
mMapView.updateMap(true)
}
/** /**
* 增加或更新便签 * 增加或更新便签
@ -520,11 +617,27 @@ class MarkHandler(context: AppCompatActivity, mapView: NIMapView) :
* 添加质检数据marker * 添加质检数据marker
*/ */
fun addNiLocationMarkerItem(niLocation: NiLocation) { fun addNiLocationMarkerItem(niLocation: NiLocation) {
synchronized(this) {
var geoMarkerItem = createNILocationBitmap(niLocation) var geoMarkerItem = createNILocationBitmap(niLocation)
niLocationItemizedLayer.addItem(geoMarkerItem) niLocationItemizedLayer.addItem(geoMarkerItem)
niLocationItemizedLayer.update() niLocationItemizedLayer.update()
} }
/**
* 添加质检数据marker
*/
fun addNiLocationMarkerItemSimple(niLocation: NiLocation) {
var geoMarkerItem = createNILocationBitmap(niLocation)
niLocationItemizedLayerSimple.addItem(geoMarkerItem)
niLocationItemizedLayerSimple.update()
}
/**
* 添加质检数据marker
*/
fun addNiLocationMarkerItemRough(niLocation: NiLocation) {
var geoMarkerItem = createNILocationBitmap(niLocation)
niLocationItemizedLayerRough.addItem(geoMarkerItem)
niLocationItemizedLayerRough.update()
} }
private fun createNILocationBitmap(niLocation: NiLocation): MarkerItem { private fun createNILocationBitmap(niLocation: NiLocation): MarkerItem {
@ -791,6 +904,10 @@ class MarkHandler(context: AppCompatActivity, mapView: NIMapView) :
fun clearNiLocationLayer() { fun clearNiLocationLayer() {
niLocationItemizedLayer.removeAllItems() niLocationItemizedLayer.removeAllItems()
niLocationItemizedLayer.update() niLocationItemizedLayer.update()
niLocationItemizedLayerSimple.removeAllItems()
niLocationItemizedLayerSimple.update()
niLocationItemizedLayerRough.removeAllItems()
niLocationItemizedLayerRough.update()
} }
/** /**
@ -805,6 +922,30 @@ class MarkHandler(context: AppCompatActivity, mapView: NIMapView) :
return niLocationItemizedLayer.itemList.size return niLocationItemizedLayer.itemList.size
} }
fun getNILocationItemizedLayerSimpleSize(): Int {
return niLocationItemizedLayerSimple.itemList.size
}
fun getNILocationSimple(index: Int): NiLocation? {
return if (index > -1 && index < getNILocationItemizedLayerSimpleSize()) {
((niLocationItemizedLayerSimple.itemList[index]) as MarkerItem).uid as NiLocation
} else {
null
}
}
fun getNILocationItemizedLayerRoughSize(): Int {
return niLocationItemizedLayerRough.itemList.size
}
fun getNILocationRough(index: Int): NiLocation? {
return if (index > -1 && index < getNILocationItemizedLayerRoughSize()) {
((niLocationItemizedLayerRough.itemList[index]) as MarkerItem).uid as NiLocation
} else {
null
}
}
fun getNILocation(index: Int): NiLocation? { fun getNILocation(index: Int): NiLocation? {
return if (index > -1 && index < getNILocationItemizedLayerSize()) { return if (index > -1 && index < getNILocationItemizedLayerSize()) {
((niLocationItemizedLayer.itemList[index]) as MarkerItem).uid as NiLocation ((niLocationItemizedLayer.itemList[index]) as MarkerItem).uid as NiLocation
@ -833,6 +974,27 @@ class MarkHandler(context: AppCompatActivity, mapView: NIMapView) :
return -1 return -1
} }
fun getNILocationSimpleIndex(niLocation: NiLocation): Int? {
var list = niLocationItemizedLayerSimple.itemList
if (niLocation != null && list.isNotEmpty()) {
var index = -1
list.forEach {
index += 1
if (((it as MarkerItem).uid as NiLocation).id.equals(niLocation.id)) {
return index
}
}
}
return -1
}
} }
interface OnQsRecordItemClickListener : BaseClickListener { interface OnQsRecordItemClickListener : BaseClickListener {

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

@ -4,10 +4,13 @@ import static org.oscim.core.MercatorProjection.latitudeToY;
import static org.oscim.core.MercatorProjection.longitudeToX; import static org.oscim.core.MercatorProjection.longitudeToX;
import android.os.Build; import android.os.Build;
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.enums.DataCodeEnum;
import com.navinfo.collect.library.utils.GeometryTools;
import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.Geometry;
@ -100,7 +103,14 @@ public class OMDBReferenceDecoder extends TileDecoder {
processCoordinateArray(multiPoint.getGeometryN(i).getCoordinates(), false); processCoordinateArray(multiPoint.getGeometryN(i).getCoordinates(), false);
} }
} else if (geometry instanceof LineString) { } else if (geometry instanceof LineString) {
//将车道中心进行转化面渲染
if(layerName!=null&&layerName.equals(DataCodeEnum.OMDB_LANE_LINK_LG.name())){
Log.e("qj","车道中心线转化开始");
processPolygon((Polygon)GeometryTools.createGeometry(GeometryTools.computeLine(0.000035,0.000035,geometry.toString())));
Log.e("qj","车道中心线转化结束");
}else{
processLineString((LineString) geometry); processLineString((LineString) geometry);
}
} else if (geometry instanceof MultiLineString) { } else if (geometry instanceof MultiLineString) {
MultiLineString multiLineString = (MultiLineString) geometry; MultiLineString multiLineString = (MultiLineString) geometry;
for (int i = 0; i < multiLineString.getNumGeometries(); i++) { for (int i = 0; i < multiLineString.getNumGeometries(); i++) {

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,202 @@
package com.navinfo.collect.library.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import org.apache.commons.net.util.Base64;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
/**
* DeflaterUtils 压缩字符串
*/
public class DeflaterUtil{
private DeflaterUtil() {
}
private static final int BUFFER_SIZE = 8192;
/**
* 压缩
*/
public static String zipString(String unzipString) {
/*
* https://www.yiibai.com/javazip/javazip_deflater.html#article-start
* 0 ~ 9 压缩等级 低到高
* public static final int BEST_COMPRESSION = 9; 最佳压缩的压缩级别
* public static final int BEST_SPEED = 1; 压缩级别最快的压缩
* public static final int DEFAULT_COMPRESSION = -1; 默认压缩级别
* public static final int DEFAULT_STRATEGY = 0; 默认压缩策略
* public static final int DEFLATED = 8; 压缩算法的压缩方法(目前唯一支持的压缩方法)
* public static final int FILTERED = 1; 压缩策略最适用于大部分数值较小且数据分布随机分布的数据
* public static final int FULL_FLUSH = 3; 压缩刷新模式用于清除所有待处理的输出并重置拆卸器
* public static final int HUFFMAN_ONLY = 2; 仅用于霍夫曼编码的压缩策略
* public static final int NO_COMPRESSION = 0; 不压缩的压缩级别
* public static final int NO_FLUSH = 0; 用于实现最佳压缩结果的压缩刷新模式
* public static final int SYNC_FLUSH = 2; 用于清除所有未决输出的压缩刷新模式; 可能会降低某些压缩算法的压缩率
*/
//使用指定的压缩级别创建一个新的压缩器
Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
//设置压缩输入数据
deflater.setInput(unzipString.getBytes(StandardCharsets.UTF_8));
//当被调用时表示压缩应该以输入缓冲区的当前内容结束
deflater.finish();
final byte[] bytes = new byte[256];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(256);
while (!deflater.finished()) {
//压缩输入数据并用压缩数据填充指定的缓冲区
int length = deflater.deflate(bytes);
outputStream.write(bytes, 0, length);
}
deflater.end();
return Base64.encodeBase64String(outputStream.toByteArray());
}
/**
* 解压缩
*/
public static String unzipString(String zipString) {
byte[] decode = Base64.decodeBase64(zipString);
//创建一个新的解压缩器 https://www.yiibai.com/javazip/javazip_inflater.html
Inflater inflater = new Inflater();
//设置解压缩的输入数据
inflater.setInput(decode);
final byte[] bytes = new byte[256];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(256);
try {
//finished() 如果已到达压缩数据流的末尾则返回true
while (!inflater.finished()) {
//将字节解压缩到指定的缓冲区中
int length = inflater.inflate(bytes);
outputStream.write(bytes, 0, length);
}
} catch (DataFormatException e) {
e.printStackTrace();
return null;
} finally {
//关闭解压缩器并丢弃任何未处理的输入
inflater.end();
}
try {
return outputStream.toString("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
public static byte[] compress(byte[] bytes) {
if (bytes == null) {
throw new NullPointerException("bytes is null");
}
int lenght = 0;
Deflater deflater = new Deflater();
deflater.setInput(bytes);
deflater.finish();
byte[] outputBytes = new byte[BUFFER_SIZE];
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
while (!deflater.finished()) {
lenght = deflater.deflate(outputBytes);
bos.write(outputBytes, 0, lenght);
}
deflater.end();
return bos.toByteArray();
} catch (IOException e) {
throw new RuntimeException("Deflater compress error", e);
}
}
public static byte[] decompress(byte[] bytes) {
if (bytes == null) {
throw new NullPointerException("bytes is null");
}
int length = 0;
Inflater inflater = new Inflater();
inflater.setInput(bytes);
byte[] outputBytes = new byte[BUFFER_SIZE];
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();) {
while (!inflater.finished()) {
length = inflater.inflate(outputBytes);
if (length == 0) {
break;
}
bos.write(outputBytes, 0, length);
}
inflater.end();
return bos.toByteArray();
} catch (Exception e) {
throw new RuntimeException("Deflater decompress error", e);
}
}
}

View File

@ -49,7 +49,6 @@ class GeometryToolsKt {
} }
} }
} }
println("YGeometry-time:" + (System.currentTimeMillis() - startTime))
} }
/** /**
@ -93,7 +92,6 @@ class GeometryToolsKt {
} }
} }
} }
println("XGeometry-time:" + (System.currentTimeMillis() - startTime))
} }
fun getMasterPoint(wkt: String): String { fun getMasterPoint(wkt: String): String {

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()
}
}