fix: 增加文件选择功能

This commit is contained in:
xiaoyan 2023-03-29 17:49:41 +08:00
commit b927edb67c
56 changed files with 2691 additions and 1693 deletions

View File

@ -24,8 +24,8 @@ android {
} }
} }
compileOptions { compileOptions {
sourceCompatibility JavaVersion.VERSION_11 sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_11 targetCompatibility JavaVersion.VERSION_1_8
} }
kotlinOptions { kotlinOptions {
jvmTarget = '1.8' jvmTarget = '1.8'

View File

@ -1,7 +1,31 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"> xmlns:tools="http://schemas.android.com/tools"
package="com.navinfo.omqs">
<!-- 这个权限用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- 这个权限用于访问GPS定位-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- 用于访问wifi网络信息wifi信息会用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- 获取运营商信息,用于支持提供运营商信息相关的接口-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- 这个权限用于获取wifi的获取权限wifi信息会用来进行网络定位-->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<!-- 写入扩展存储,向扩展卡写入数据,用于写入离线定位数据-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- 访问网络,网络定位需要上网 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 允许访问振动设备 -->
<uses-permission android:name="android.permission.VIBRATE" />
<!-- 允许使用PowerManager的 WakeLocks保持进程在休眠时从屏幕消失 -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- android 9.0上使用前台服务,需要添加权限 -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<!-- 用于读取手机当前的状态 -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- 读取缓存数据 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application <application
android:allowBackup="true" android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules" android:dataExtractionRules="@xml/data_extraction_rules"
@ -12,8 +36,9 @@
android:theme="@style/Theme.OMQualityInspection" android:theme="@style/Theme.OMQualityInspection"
android:requestLegacyExternalStorage="true"> android:requestLegacyExternalStorage="true">
<activity <activity
android:name=".ui.MainActivity" android:name=".ui.activity.LoginActivity"
android:exported="true" android:exported="true"
android:screenOrientation="landscape"
android:label="@string/app_name" android:label="@string/app_name"
android:theme="@style/Theme.OMQualityInspection"> android:theme="@style/Theme.OMQualityInspection">
<intent-filter> <intent-filter>
@ -22,6 +47,16 @@
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
</activity> </activity>
<activity
android:name=".ui.activity.MainActivity"
android:screenOrientation="landscape"
android:exported="true"
android:theme="@style/Theme.OMQualityInspection"></activity>
<activity
android:name=".ui.activity.MapTestActivity"
android:screenOrientation="landscape"
android:exported="true"
android:theme="@style/Theme.OMQualityInspection"></activity>
</application> </application>
</manifest> </manifest>

View File

@ -0,0 +1,95 @@
# coding:utf-8
# 合并指定目录下的omdbsqlite数据
import os
import sys
import json
import sqlite3
# 定义遍历目录的函数
def traverse_dir(path):
fileList = list()
for root, dirs, files in os.walk(path):
for file in files:
if str(file).endswith(".omdb"):
# 文件的完整路径
file_path = os.path.join(root, file)
# 处理文件,例如读取文件内容等
print(file_path)
fileList.append(file_path)
return fileList
# 打开配置文件,读取用户配置的
def openConfigJson(path):
# 读取json配置获取要抽取的表名
with open(path, "r") as f:
configMap = json.load(f)
return configMap
# 按照tableList中指定的表名合并多个源数据库到指定目标数据库中
def mergeSqliteData(originSqliteList, destSqlite, tableList):
destConn = sqlite3.connect(destSqlite)
destCursor = destConn.cursor()
for originSqlite in originSqliteList:
originConn = sqlite3.connect(originSqlite)
originCursor = originConn.cursor()
# 从源数据库中遍历取出表list中的数据
for table in tableList:
# 检查目标数据库中是否存在指定的表
containsTable = destCursor.execute(
"SELECT sql FROM sqlite_master WHERE type='table' AND name='%s'" % (table)).fetchall()
if not containsTable or len(containsTable) <= 0:
# 复制表结构
originCursor.execute("SELECT sql FROM sqlite_master WHERE type='table' AND name='%s'" % (table))
createTableSql = originCursor.fetchone()[0]
destCursor.execute(createTableSql)
destConn.commit()
originCursor.execute("Select * From " + table)
# 获取到源数据库中该表的所有数据
originData = originCursor.fetchall()
# 获取一行数据中包含多少列以此动态设置sql语句中的个数
if originData and len(originData)>0:
num_cols = len(originData[0])
placeholders = ",".join(["?"] * num_cols)
for row in originData:
destCursor.execute("INSERT INTO "+table+" VALUES ({})".format(placeholders), row)
print("{}数据已导入!".format(originSqlite))
originCursor.close()
originConn.close()
destConn.commit()
destCursor.close()
destConn.close()
if __name__ == '__main__':
params = sys.argv[1:] # 截取参数
if params:
if not params[0]:
print("请输入要合并的omdb数据的文件夹")
raise AttributeError("请输入要合并的omdb数据的文件夹")
# 获取导出文件的表配置
jsonPath = params[0] + "/config.json"
if not os.path.exists(jsonPath):
raise AttributeError("指定目录下缺少config.json配置文件")
omdbDir = params[0]
originSqliteList = traverse_dir(omdbDir) # 获取到所有的omdb数据库的路径
tableNameList = list()
configMap = openConfigJson(jsonPath)
if configMap["tables"] and len(configMap["tables"]) > 0:
for tableName in set(configMap["tables"]):
tableNameList.append(tableName)
print(tableNameList)
else:
raise AttributeError("config.json文件中没有配置抽取数据的表名")
# 开始分别连接Sqlite数据库按照指定表名合并数据
mergeSqliteData(originSqliteList, params[0]+"/output.sqlite", tableNameList)
else:
raise AttributeError("缺少参数请输入要合并的omdb数据的文件夹")

View File

@ -0,0 +1,10 @@
package com.navinfo.omqs
import android.app.Application
class QAApplication: Application() {
override fun onCreate() {
super.onCreate()
}
}

View File

@ -0,0 +1,6 @@
package com.navinfo.omqs.model
data class LoginUser(
var username: String = "",
var password: String = ""
)

View File

@ -1,30 +0,0 @@
package com.navinfo.omqs.ui
import android.os.Bundle
import android.os.PersistableBundle
import androidx.activity.viewModels
import com.navinfo.omqs.databinding.ActivityLoginBinding
class LoginActivity : PermissionsActivity() {
private lateinit var binding: ActivityLoginBinding
private val viewModel by viewModels<LoginActivityViewModel>()
override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
super.onCreate(savedInstanceState, persistentState)
binding = ActivityLoginBinding.inflate(layoutInflater)
setContentView(binding.root)
}
override fun onPermissionsGranted() {
initView()
}
private fun initView() {
}
override fun onPermissionsDenied() {
}
}

View File

@ -1,7 +0,0 @@
package com.navinfo.omqs.ui
import androidx.lifecycle.ViewModel
class LoginActivityViewModel : ViewModel() {
}

View File

@ -1,11 +1,7 @@
package com.navinfo.omqs.ui package com.navinfo.omqs.ui
import android.content.Intent import android.content.Intent
import android.net.Uri
import android.os.Bundle import android.os.Bundle
import android.os.FileUtils
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowCompat import androidx.core.view.WindowCompat
import androidx.navigation.findNavController import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.AppBarConfiguration
@ -13,20 +9,11 @@ import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupActionBarWithNavController
import android.view.Menu import android.view.Menu
import android.view.MenuItem import android.view.MenuItem
import android.widget.Toast
import androidx.core.net.toFile
import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.UriUtils
import com.github.k1rakishou.fsaf.FileChooser import com.github.k1rakishou.fsaf.FileChooser
import com.github.k1rakishou.fsaf.FileManager
import com.github.k1rakishou.fsaf.callback.FSAFActivityCallbacks import com.github.k1rakishou.fsaf.callback.FSAFActivityCallbacks
import com.github.k1rakishou.fsaf.callback.FileChooserCallback
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.navinfo.omqs.R import com.navinfo.omqs.R
import com.navinfo.omqs.databinding.ActivityMainBinding import com.navinfo.omqs.databinding.ActivityMainBinding
import java.io.File import com.navinfo.omqs.ui.activity.PermissionsActivity
class MainActivity : PermissionsActivity(), FSAFActivityCallbacks { class MainActivity : PermissionsActivity(), FSAFActivityCallbacks {
@ -41,29 +28,27 @@ class MainActivity : PermissionsActivity(), FSAFActivityCallbacks {
binding = ActivityMainBinding.inflate(layoutInflater) binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root) setContentView(binding.root)
setSupportActionBar(binding.toolbar)
val navController = findNavController(R.id.nav_host_fragment_content_main) val navController = findNavController(R.id.nav_host_fragment_content_main)
appBarConfiguration = AppBarConfiguration(navController.graph) appBarConfiguration = AppBarConfiguration(navController.graph)
setupActionBarWithNavController(navController, appBarConfiguration) setupActionBarWithNavController(navController, appBarConfiguration)
fileChooser.setCallbacks(this@MainActivity) fileChooser.setCallbacks(this@MainActivity)
binding.fab.setOnClickListener { view -> // binding.fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) // Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAnchorView(R.id.fab) // .setAnchorView(R.id.fab)
.setAction("Action", null).show() // .setAction("Action", null).show()
// 开始数据导入功能 // // 开始数据导入功能
fileChooser.openChooseFileDialog(object: FileChooserCallback() { // fileChooser.openChooseFileDialog(object: FileChooserCallback() {
override fun onCancel(reason: String) { // override fun onCancel(reason: String) {
} // }
//
override fun onResult(uri: Uri) { // override fun onResult(uri: Uri) {
val file = UriUtils.uri2File(uri) // val file = UriUtils.uri2File(uri)
Snackbar.make(view, "文件大小为:${file.length()}", Snackbar.LENGTH_LONG) // Snackbar.make(view, "文件大小为:${file.length()}", Snackbar.LENGTH_LONG)
.show() // .show()
} // }
}) // })
} // }
} }
override fun onPermissionsGranted() { override fun onPermissionsGranted() {

View File

@ -0,0 +1,16 @@
package com.navinfo.omqs.ui.activity
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.os.PersistableBundle
import androidx.appcompat.app.AppCompatActivity
/**
* 基类
*/
open class BaseActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE//横屏
super.onCreate(savedInstanceState)
}
}

View File

@ -0,0 +1,40 @@
package com.navinfo.omqs.ui.activity
import android.content.Intent
import android.os.Bundle
import androidx.activity.viewModels
import androidx.databinding.DataBindingUtil
import com.navinfo.omqs.R
import com.navinfo.omqs.databinding.ActivityLoginBinding
/**
* 登陆页面
*/
class LoginActivity : PermissionsActivity() {
private lateinit var binding: ActivityLoginBinding
private val viewModel by viewModels<LoginViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_login)
binding.loginUserModel = viewModel
binding.lifecycleOwner = this
binding.activity = this
}
override fun onPermissionsGranted() {
}
override fun onPermissionsDenied() {
}
/**
* 处理登录按钮
*/
fun onClickLoginButton() {
val intent = Intent(this@LoginActivity, MainActivity::class.java)
startActivity(intent)
finish()
}
}

View File

@ -0,0 +1,23 @@
package com.navinfo.omqs.ui.activity
import android.view.View
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.navinfo.omqs.model.LoginUser
class LoginViewModel : ViewModel() {
val loginUser: MutableLiveData<LoginUser> = MutableLiveData()
init {
loginUser.value = LoginUser(username = "admin", password = "123456")
}
/**
* 处理注册按钮
*/
fun onClick(view: View) {
loginUser.value!!.username = "admin2"
loginUser.postValue(loginUser.value)
}
}

View File

@ -0,0 +1,45 @@
package com.navinfo.omqs.ui.activity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.core.view.WindowCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.navinfo.omqs.R
import com.navinfo.omqs.databinding.ActivityMainBinding
/**
* 地图主页面
*/
class MainActivity : BaseActivity() {
private lateinit var binding: ActivityMainBinding
private val viewModel by viewModels<MainViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
//关联生命周期
binding.lifecycleOwner = this
//给xml转递对象
binding.mainActivity = this
//给xml传递viewModel对象
binding.viewModel = viewModel
//初始化地图
viewModel.initMap(this, binding.mapView.mainActivityMap)
//让viewModel监听activity生命周期
lifecycle.addObserver(viewModel)
}
/**
* 打开个人中菜单
*/
fun openMenu() {
binding.mainActivityDrawer.open()
}
}

View File

@ -0,0 +1,53 @@
package com.navinfo.omqs.ui.activity
import android.app.Application
import android.content.Context
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModel
import com.navinfo.collect.library.map.NIMapController
import com.navinfo.collect.library.map.NIMapView
class MainViewModel(val app: Application) : AndroidViewModel(app), DefaultLifecycleObserver {
/**
* 地图控制器
*/
private lateinit var mapController: NIMapController
/**
* 初始化地图
*/
fun initMap(context: Context, mapView: NIMapView) {
mapController = NIMapController(context = app, mapView = mapView)
}
override fun onStart(owner: LifecycleOwner) {
super.onStart(owner)
//开启定位
mapController.locationLayerHandler.startLocation()
}
override fun onPause(owner: LifecycleOwner) {
mapController.mMapView.onPause()
}
override fun onDestroy(owner: LifecycleOwner) {
mapController.mMapView.onDestroy()
//结束定位
mapController.locationLayerHandler.stopLocation()
}
override fun onResume(owner: LifecycleOwner) {
mapController.mMapView.onResume()
}
/**
* 点击我的位置回到我的位置
*/
fun onClickLocationButton() {
mapController.locationLayerHandler.animateToCurrentPosition()
}
}

View File

@ -0,0 +1,16 @@
package com.navinfo.omqs.ui.activity
import android.os.Bundle
import com.navinfo.collect.library.map.NIMapController
import com.navinfo.collect.library.map.NIMapView
import com.navinfo.omqs.R
class MapTestActivity: BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_map_test)
val mapController = NIMapController(context = this, mapView = findViewById<NIMapView>(R.id.main_activity_map1))
mapController.locationLayerHandler.startLocation()
}
}

View File

@ -1,9 +1,8 @@
package com.navinfo.omqs.ui package com.navinfo.omqs.ui.activity
import android.os.Build
import android.os.Bundle import android.os.Bundle
import android.os.PersistableBundle
import android.widget.Toast import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.hjq.permissions.OnPermissionCallback import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions import com.hjq.permissions.XXPermissions
@ -11,18 +10,31 @@ import com.hjq.permissions.XXPermissions
/** /**
* 权限申请Activity * 权限申请Activity
*/ */
abstract class PermissionsActivity : AppCompatActivity() { open class PermissionsActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
val permissionList = mutableListOf<String>()
if (applicationInfo.targetSdkVersion >= Build.VERSION_CODES.TIRAMISU) {
//文件读写
// permissionList.add(Permission.READ_MEDIA_IMAGES)
// permissionList.add(Permission.READ_MEDIA_AUDIO)
// permissionList.add(Permission.READ_MEDIA_VIDEO)
permissionList.add(Permission.MANAGE_EXTERNAL_STORAGE)
} else {
//文件读写
permissionList.add(Permission.WRITE_EXTERNAL_STORAGE)
permissionList.add(Permission.READ_EXTERNAL_STORAGE)
permissionList.add(Permission.READ_MEDIA_VIDEO)
}
//定位权限
permissionList.add(Permission.ACCESS_FINE_LOCATION)
permissionList.add(Permission.ACCESS_COARSE_LOCATION)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
permissionList.add(Permission.ACCESS_BACKGROUND_LOCATION)
}
XXPermissions.with(this) XXPermissions.with(this)
// 申请单个权限 // 申请单个权限
// .permission(Permission.WRITE_EXTERNAL_STORAGE) .permission(permissionList)
// .permission(Permission.READ_EXTERNAL_STORAGE)
// .permission(Permission.READ_MEDIA_IMAGES)
// .permission(Permission.READ_MEDIA_AUDIO)
// .permission(Permission.READ_MEDIA_VIDEO)
.permission(Permission.MANAGE_EXTERNAL_STORAGE)
// 设置权限请求拦截器(局部设置) // 设置权限请求拦截器(局部设置)
//.interceptor(new PermissionInterceptor()) //.interceptor(new PermissionInterceptor())
// 设置不触发错误检测机制(局部设置) // 设置不触发错误检测机制(局部设置)
@ -39,6 +51,8 @@ abstract class PermissionsActivity : AppCompatActivity() {
.show() .show()
onPermissionsGranted() onPermissionsGranted()
return return
} else {
onPermissionsDenied()
} }
// 在SD卡创建项目目录 // 在SD卡创建项目目录
} }
@ -55,11 +69,23 @@ abstract class PermissionsActivity : AppCompatActivity() {
XXPermissions.startPermissionActivity(this@PermissionsActivity, permissions) XXPermissions.startPermissionActivity(this@PermissionsActivity, permissions)
onPermissionsDenied() onPermissionsDenied()
} else { } else {
onPermissionsDenied()
} }
} }
}) })
} }
abstract fun onPermissionsGranted() /**
abstract fun onPermissionsDenied() * 权限全部同意
*/
open fun onPermissionsGranted() {
}
/**
* 权限
*/
open fun onPermissionsDenied() {
}
} }

View File

@ -1,4 +1,4 @@
package com.navinfo.omqs package com.navinfo.omqs.ui.fragment
import android.os.Bundle import android.os.Bundle
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
@ -6,6 +6,7 @@ import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.findNavController
import com.navinfo.omqs.R
import com.navinfo.omqs.databinding.FragmentFirstBinding import com.navinfo.omqs.databinding.FragmentFirstBinding
/** /**

View File

@ -1,4 +1,4 @@
package com.navinfo.omqs package com.navinfo.omqs.ui.fragment
import android.os.Bundle import android.os.Bundle
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
@ -6,6 +6,7 @@ import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.findNavController
import com.navinfo.omqs.R
import com.navinfo.omqs.databinding.FragmentSecondBinding import com.navinfo.omqs.databinding.FragmentSecondBinding
/** /**
@ -22,7 +23,7 @@ class SecondFragment : Fragment() {
override fun onCreateView( override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle? savedInstanceState: Bundle?
): View? { ): View {
_binding = FragmentSecondBinding.inflate(inflater, container, false) _binding = FragmentSecondBinding.inflate(inflater, container, false)
return binding.root return binding.root

View File

@ -0,0 +1,5 @@
<vector android:height="24dp" android:tint="#18FD00"
android:viewportHeight="24" android:viewportWidth="24"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="@android:color/white" android:pathData="M12,8c-2.21,0 -4,1.79 -4,4s1.79,4 4,4 4,-1.79 4,-4 -1.79,-4 -4,-4zM20.94,11c-0.46,-4.17 -3.77,-7.48 -7.94,-7.94L13,1h-2v2.06C6.83,3.52 3.52,6.83 3.06,11L1,11v2h2.06c0.46,4.17 3.77,7.48 7.94,7.94L11,23h2v-2.06c4.17,-0.46 7.48,-3.77 7.94,-7.94L23,13v-2h-2.06zM12,19c-3.87,0 -7,-3.13 -7,-7s3.13,-7 7,-7 7,3.13 7,7 -3.13,7 -7,7z"/>
</vector>

View File

@ -0,0 +1,5 @@
<vector android:height="24dp" android:tint="#18FD00"
android:viewportHeight="24" android:viewportWidth="24"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="@android:color/white" android:pathData="M12,12c2.21,0 4,-1.79 4,-4s-1.79,-4 -4,-4 -4,1.79 -4,4 1.79,4 4,4zM12,14c-2.67,0 -8,1.34 -8,4v2h16v-2c0,-2.66 -5.33,-4 -8,-4z"/>
</vector>

View File

@ -1,9 +1,101 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" <layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" tools:context=".ui.activity.LoginActivity">
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".ui.LoginActivity">
</androidx.constraintlayout.widget.ConstraintLayout> <data>
<variable
name="activity"
type="com.navinfo.omqs.ui.activity.LoginActivity" />
<variable
name="loginUserModel"
type="com.navinfo.omqs.ui.activity.LoginViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ImageView
android:id="@+id/login_fragment_logo"
android:layout_width="100dp"
android:layout_height="100dp"
android:contentDescription="@string/imagedescription"
android:scaleType="fitXY"
android:src="@mipmap/ic_launcher"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.1"
app:roundPercent="0.2" />
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/login_fragment_user_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:scrollbarAlwaysDrawHorizontalTrack="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.4">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/login_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/input_user_name"
android:text="@{loginUserModel.loginUser.username}" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
app:layout_constraintTop_toBottomOf="@id/login_fragment_user_layout">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/login_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/input_password"
android:inputType="textPassword"
android:text="@{loginUserModel.loginUser.password}" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
android:id="@+id/login_fragment_register_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="@{(view)->loginUserModel.onClick(view)}"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="@string/logon"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_chainStyle="spread"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf="@id/login_activity_login_button"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.8" />
<com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
android:id="@+id/login_activity_login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="@{()->activity.onClickLoginButton()}"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="@string/login"
app:layout_constraintBaseline_toBaselineOf="@id/login_fragment_register_button"
app:layout_constraintLeft_toRightOf="@id/login_fragment_register_button"
app:layout_constraintRight_toRightOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>

View File

@ -1,34 +1,41 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout <layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" tools:context=".ui.activity.MainActivity">
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".ui.MainActivity">
<com.google.android.material.appbar.AppBarLayout <data>
<variable
name="mainActivity"
type="com.navinfo.omqs.ui.activity.MainActivity" />
<variable
name="viewModel"
type="com.navinfo.omqs.ui.activity.MainViewModel" />
</data>
<androidx.drawerlayout.widget.DrawerLayout
android:id="@+id/main_activity_drawer"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="match_parent"
android:fitsSystemWindows="true"> android:fitsSystemWindows="true">
<com.google.android.material.appbar.MaterialToolbar <include
android:id="@+id/toolbar" android:id="@+id/map_view"
layout="@layout/map_view"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize" /> android:layout_height="match_parent"
app:mainActivity="@{mainActivity}"
app:viewModel="@{viewModel}"/>
</com.google.android.material.appbar.AppBarLayout> <com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
<include layout="@layout/content_main" /> android:layout_width="wrap_content"
android:layout_height="match_parent"
<com.google.android.material.floatingactionbutton.FloatingActionButton android:layout_gravity="left"
android:id="@+id/fab" android:fitsSystemWindows="true"
android:layout_width="wrap_content" app:headerLayout="@layout/nav_header_main"
android:layout_height="wrap_content" app:menu="@menu/activity_main_drawer" />
android:layout_gravity="bottom|end" </androidx.drawerlayout.widget.DrawerLayout>
android:layout_marginEnd="@dimen/fab_margin" </layout>
android:layout_marginBottom="16dp"
app:srcCompat="@android:drawable/ic_dialog_email" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.navinfo.collect.library.map.NIMapView
android:id="@+id/main_activity_map1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

View File

@ -4,7 +4,7 @@
xmlns:tools="http://schemas.android.com/tools" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
tools:context=".FirstFragment"> tools:context=".ui.fragment.FirstFragment">
<androidx.constraintlayout.widget.ConstraintLayout <androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent" android:layout_width="match_parent"

View File

@ -4,7 +4,7 @@
xmlns:tools="http://schemas.android.com/tools" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
tools:context=".SecondFragment"> tools:context=".ui.fragment.SecondFragment">
<androidx.constraintlayout.widget.ConstraintLayout <androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent" android:layout_width="match_parent"

View File

@ -0,0 +1,48 @@
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="mainActivity"
type="com.navinfo.omqs.ui.activity.MainActivity" />
<variable
name="viewModel"
type="com.navinfo.omqs.ui.activity.MainViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.activity.MainActivity">
<com.navinfo.collect.library.map.NIMapView
android:id="@+id/main_activity_map"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageButton
android:id="@+id/main_activity_person_center"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:onClick="@{()->mainActivity.openMenu()}"
android:src="@drawable/baseline_person_24"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="@+id/main_activity_location"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginLeft="20dp"
android:layout_marginBottom="80dp"
android:onClick="@{()->viewModel.onClickLocationButton()}"
android:src="@drawable/baseline_my_location_24"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>

View File

@ -0,0 +1,35 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height"
android:background="@color/default_blue"
android:gravity="bottom"
android:orientation="vertical"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/nav_header_desc"
android:paddingTop="@dimen/nav_header_vertical_spacing"
app:srcCompat="@mipmap/ic_launcher_round" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:text="@string/nav_header_title"
android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/nav_header_subtitle" />
</LinearLayout>

View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_home"
android:icon="@drawable/icon_map_zoom_in"
android:title="menu_home" />
<item
android:id="@+id/nav_gallery"
android:icon="@drawable/icon_map_zoom_in"
android:title="menu_gallery" />
<item
android:id="@+id/nav_slideshow"
android:icon="@drawable/icon_map_zoom_in"
android:title="menu_slideshow" />
</group>
</menu>

View File

@ -1,7 +1,7 @@
<menu xmlns:android="http://schemas.android.com/apk/res/android" <menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" xmlns:tools="http://schemas.android.com/tools"
tools:context="com.navinfo.omqs.ui.MainActivity"> tools:context="com.navinfo.omqs.ui.activity.MainActivity">
<item <item
android:id="@+id/action_settings" android:id="@+id/action_settings"
android:orderInCategory="100" android:orderInCategory="100"

View File

@ -7,7 +7,7 @@
<fragment <fragment
android:id="@+id/FirstFragment" android:id="@+id/FirstFragment"
android:name="com.navinfo.omqs.FirstFragment" android:name="com.navinfo.omqs.ui.fragment.FirstFragment"
android:label="@string/first_fragment_label" android:label="@string/first_fragment_label"
tools:layout="@layout/fragment_first"> tools:layout="@layout/fragment_first">
@ -17,7 +17,7 @@
</fragment> </fragment>
<fragment <fragment
android:id="@+id/SecondFragment" android:id="@+id/SecondFragment"
android:name="com.navinfo.omqs.SecondFragment" android:name="com.navinfo.omqs.ui.fragment.SecondFragment"
android:label="@string/second_fragment_label" android:label="@string/second_fragment_label"
tools:layout="@layout/fragment_second"> tools:layout="@layout/fragment_second">

View File

@ -1,3 +1,8 @@
<resources> <resources>
<dimen name="fab_margin">16dp</dimen> <dimen name="fab_margin">16dp</dimen>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
<dimen name="nav_header_vertical_spacing">8dp</dimen>
<dimen name="nav_header_height">176dp</dimen>
</resources> </resources>

View File

@ -43,4 +43,18 @@
libero vel nunc consequat, quis tincidunt nisl eleifend. Cras bibendum enim a justo luctus libero vel nunc consequat, quis tincidunt nisl eleifend. Cras bibendum enim a justo luctus
vestibulum. Fusce dictum libero quis erat maximus, vitae volutpat diam dignissim. vestibulum. Fusce dictum libero quis erat maximus, vitae volutpat diam dignissim.
</string> </string>
<string name="input_user_name">请输入用户名</string>
<string name="input_password">请输入密码</string>
<string name="login">登录</string>
<string name="logon">注册</string>
<string name="imagedescription">imageDescription</string>
<string name="navigation_drawer_open">Open navigation drawer</string>
<string name="navigation_drawer_close">Close navigation drawer</string>
<string name="nav_header_title">Android Studio</string>
<string name="nav_header_subtitle">android.studio@android.com</string>
<string name="nav_header_desc">Navigation header</string>
<string name="menu_home">Home</string>
<string name="menu_gallery">Gallery</string>
<string name="menu_slideshow">Slideshow</string>
</resources> </resources>

View File

@ -56,7 +56,7 @@ android {
dependencies { dependencies {
api fileTree(dir: 'libs', include: ['*.jar', '*.aar']) api fileTree(dir: 'libs', include: ['*.jar', '*.aar'])
api files('libs/BaiduLBS_AndroidSDK_Lib.aar')
implementation "androidx.appcompat:appcompat:$appcompatVersion" implementation "androidx.appcompat:appcompat:$appcompatVersion"
implementation "com.google.android.material:material:$materialVersion" implementation "com.google.android.material:material:$materialVersion"
testImplementation 'junit:junit:4.13.2' testImplementation 'junit:junit:4.13.2'
@ -106,11 +106,10 @@ dependencies {
implementation "androidx.sqlite:sqlite:2.0.1" implementation "androidx.sqlite:sqlite:2.0.1"
implementation "androidx.room:room-runtime:2.1.0" implementation "androidx.room:room-runtime:2.1.0"
annotationProcessor "androidx.room:room-compiler:2.1.0" annotationProcessor "androidx.room:room-compiler:2.1.0"
kapt 'android.arch.persistence.room:compiler:1.1.1' // compiler room
kapt "androidx.room:room-compiler:2.1.0" kapt "androidx.room:room-compiler:2.1.0"
androidTestImplementation "android.arch.persistence.room:testing:1.1.1" androidTestImplementation 'androidx.room:room-testing:2.0.0'
implementation "android.arch.lifecycle:extensions:1.1.1" implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'
kapt "android.arch.lifecycle:compiler:1.1.1" kapt 'androidx.lifecycle:lifecycle-compiler:2.0.0'
implementation 'com.tencent.wcdb:wcdb-android:1.0.0' implementation 'com.tencent.wcdb:wcdb-android:1.0.0'
implementation "androidx.core:core-ktx:1.8.0" implementation "androidx.core:core-ktx:1.8.0"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

Binary file not shown.

View File

@ -8,13 +8,14 @@
<data android:mimeType="*/*"/> <data android:mimeType="*/*"/>
</intent> </intent>
</queries> </queries>
<!-- AK鉴权 -->
<!-- <application--> <meta-data
<!-- android:allowBackup="true"--> android:name="com.baidu.lbsapi.API_KEY"
<!-- >--> android:value="IxQi4mZGTlfv6Z9M2GRdqn4KKRbOATUU" />
<!-- <activity--> <application
<!-- android:name="com.navinfo.ocr.CameraActivity"--> android:allowBackup="true"
<!-- android:exported="true"/>--> android:networkSecurityConfig="@xml/network_security_config"
<!-- </application>--> >
</application>
</manifest> </manifest>

View File

@ -1,111 +1,117 @@
package com.navinfo.collect; //package com.navinfo.collect;
//
import android.Manifest; //import android.Manifest;
import android.content.DialogInterface; //import android.content.DialogInterface;
import android.content.Intent; //import android.content.Intent;
import android.content.pm.PackageManager; //import android.content.pm.PackageManager;
import android.os.Build; //import android.os.Build;
import android.os.Bundle; //import android.os.Bundle;
import android.os.Environment; //import android.os.Environment;
import android.provider.Settings; //import android.provider.Settings;
//
import androidx.annotation.NonNull; //import androidx.annotation.NonNull;
import androidx.annotation.Nullable; //import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog; //import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity; //import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat; //import androidx.core.app.ActivityCompat;
import androidx.core.content.PermissionChecker; //import androidx.core.content.PermissionChecker;
//
/** //import com.baidu.ai.edge.core.base.Consts;
* Created by linyiran on 6/16/22. //
*/ //
public abstract class BaseActivity extends AppCompatActivity { ///**
private static final int REQUEST_PERMISSION = 1; // * Created by linyiran on 6/16/22.
// */
protected boolean allPermissionsGranted; //public abstract class BaseActivity extends AppCompatActivity {
// private static final int REQUEST_PERMISSION = 1;
@Override //
protected void onCreate(@Nullable Bundle savedInstanceState) { // protected boolean allPermissionsGranted;
super.onCreate(savedInstanceState); //
setLayout(); // @Override
requestPermission(); // protected void onCreate(@Nullable Bundle savedInstanceState) {
onActivityCreated(savedInstanceState); // super.onCreate(savedInstanceState);
} // setLayout();
// requestPermission();
protected abstract void setLayout(); // onActivityCreated(savedInstanceState);
// }
protected abstract void onActivityCreated(Bundle savedInstanceState); //
// protected abstract void setLayout();
private void requestPermission() { //
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // protected abstract void onActivityCreated(Bundle savedInstanceState);
String[] permissions = new String[]{ //
Manifest.permission.WRITE_EXTERNAL_STORAGE, // private void requestPermission() {
Manifest.permission.INTERNET, // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Manifest.permission.ACCESS_NETWORK_STATE, // String[] permissions = new String[]{
Manifest.permission.READ_PHONE_STATE, // Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA // Manifest.permission.INTERNET,
}; // Manifest.permission.ACCESS_NETWORK_STATE,
allPermissionsGranted = true; // Manifest.permission.READ_PHONE_STATE,
for (String perm : permissions) { // Manifest.permission.CAMERA
if ((PermissionChecker.checkSelfPermission(this, perm) != PermissionChecker.PERMISSION_GRANTED)) { // };
allPermissionsGranted = false; // allPermissionsGranted = true;
break; // for (String perm : permissions) {
} // if ((PermissionChecker.checkSelfPermission(this, perm) != PermissionChecker.PERMISSION_GRANTED)) {
} // allPermissionsGranted = false;
if (!allPermissionsGranted) { // break;
ActivityCompat.requestPermissions(BaseActivity.this, permissions, REQUEST_PERMISSION); // }
} else { // }
requestAllFilesAccess(); // if (!allPermissionsGranted) {
} // ActivityCompat.requestPermissions(BaseActivity.this, permissions, REQUEST_PERMISSION);
} else { // } else {
allPermissionsGranted = true; // requestAllFilesAccess();
} // }
} // } else {
// allPermissionsGranted = true;
@Override // }
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, // }
@NonNull int[] grantResults) { //
if (requestCode == REQUEST_PERMISSION) { // @Override
allPermissionsGranted = true; // public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
for (int grantRes : grantResults) { // @NonNull int[] grantResults) {
if (grantRes != PackageManager.PERMISSION_GRANTED) { // if (requestCode == REQUEST_PERMISSION) {
allPermissionsGranted = false; // allPermissionsGranted = true;
break; // for (int grantRes : grantResults) {
} // if (grantRes != PackageManager.PERMISSION_GRANTED) {
} // allPermissionsGranted = false;
if (allPermissionsGranted) { // break;
requestAllFilesAccess(); // }
} // }
} // if (allPermissionsGranted) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults); // requestAllFilesAccess();
} // }
// }
/** // super.onRequestPermissionsResult(requestCode, permissions, grantResults);
* Android 11 跳转到设置获取SD卡根目录写入权限 // }
*/ //
private void requestAllFilesAccess() { // /**
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()) { // * Android 11 跳转到设置获取SD卡根目录写入权限
allPermissionsGranted = false; // */
// private void requestAllFilesAccess() {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(BaseActivity.this, // if (!Consts.AUTH_REQUIRE_SDCARD) {
androidx.appcompat.R.style.Theme_AppCompat_Light_Dialog_Alert); // return;
alertBuilder.setMessage("需授权访问SD卡文件"); // }
alertBuilder.setCancelable(false); // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()) {
alertBuilder.setPositiveButton("去设置", new DialogInterface.OnClickListener() { // allPermissionsGranted = false;
@Override //
public void onClick(DialogInterface dialog, int which) { // AlertDialog.Builder alertBuilder = new AlertDialog.Builder(BaseActivity.this,
Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION); // androidx.appcompat.R.style.Theme_AppCompat_Light_Dialog_Alert);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // alertBuilder.setMessage("需授权访问SD卡文件");
startActivity(intent); // alertBuilder.setCancelable(false);
} // alertBuilder.setPositiveButton("去设置", new DialogInterface.OnClickListener() {
}); // @Override
alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() { // public void onClick(DialogInterface dialog, int which) {
@Override // Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
public void onClick(DialogInterface dialog, int which) { // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
dialog.dismiss(); // startActivity(intent);
} // }
}); // });
alertBuilder.show(); // alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
} // @Override
} // public void onClick(DialogInterface dialog, int which) {
} // dialog.dismiss();
// }
// });
// alertBuilder.show();
// }
// }
//}

View File

@ -0,0 +1,43 @@
//package com.navinfo.collect
//
//import android.content.Intent
//import android.util.Log
//import com.baidu.ai.edge.ui.view.model.BasePolygonResultModel
//import com.navinfo.collect.library.map.flutter.plugin.FlutterMapViewFactory
//import com.navinfo.collect.library.map.flutter.plugin.FlutterMapViewFlutterPlugin
//import io.flutter.embedding.android.FlutterActivity
//import io.flutter.embedding.engine.FlutterEngine
//import kotlinx.coroutines.CoroutineScope
//import kotlinx.coroutines.MainScope
//import kotlinx.coroutines.cancel
//
//abstract class FlutterBaseActivity : FlutterActivity(), CoroutineScope by MainScope() {
// lateinit var factory: FlutterMapViewFactory
// override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
// super.configureFlutterEngine(flutterEngine)
// factory = FlutterMapViewFlutterPlugin.registerWith(flutterEngine, this);
//// FlutterNiMapCopyViewFlutterPlugin.registerWith(flutterEngine, this);
// }
//
// override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
// super.onActivityResult(requestCode, resultCode, data)
// if (resultCode == 0x10 && data != null) {
// val path = data.getStringExtra("photo_path")
// val list = data.getParcelableArrayListExtra<BasePolygonResultModel>("result_list")
// Log.e("jingo","OCR java 返回的数据:"+ path + list.toString());
// if (path != null && list != null) {
// factory.dataController.flutterDataCameraHandler.sendOcrResults(
// path,
// list as List<BasePolygonResultModel>
// )
// }
// }
// }
//
// override fun onDestroy() {
// super.onDestroy()
// //协程销毁
// cancel()
// }
//
//}

View File

@ -6,7 +6,6 @@ import android.util.Log;
import com.google.protobuf.GeneratedMessageV3; import com.google.protobuf.GeneratedMessageV3;
import com.navinfo.collect.library.data.entity.GeometryFeatureEntity; import com.navinfo.collect.library.data.entity.GeometryFeatureEntity;
import com.navinfo.collect.library.data.entity.LayerEntity; import com.navinfo.collect.library.data.entity.LayerEntity;
import com.navinfo.collect.library.map.NILayerManager;
import com.navinfo.collect.library.utils.GeometryTools; import com.navinfo.collect.library.utils.GeometryTools;
import com.navinfo.onemap.det.sdkpbf.proto.crowdsource.Hadlanelink; import com.navinfo.onemap.det.sdkpbf.proto.crowdsource.Hadlanelink;
import com.navinfo.onemap.det.sdkpbf.proto.crowdsource.Hadlanemarklink; import com.navinfo.onemap.det.sdkpbf.proto.crowdsource.Hadlanemarklink;
@ -48,7 +47,7 @@ public class RealmUtils {
private static RealmUtils instance; private static RealmUtils instance;
private Realm realm; private Realm realm;
private RealmConfiguration realmConfiguration; private RealmConfiguration realmConfiguration;
private String defaultDir = NILayerManager.defaultDir; private String defaultDir = "";//NILayerManager.defaultDir;
private String realmName; private String realmName;
private final String NAME = "name"; private final String NAME = "name";

View File

@ -0,0 +1,223 @@
//package com.navinfo.collect.library.data.handler
//
//import android.content.Context
//import android.graphics.Bitmap
//import android.graphics.BitmapFactory
//import android.media.ExifInterface
//import android.util.Log
//import com.baidu.ai.edge.ui.util.ImageUtil
//import com.baidu.ai.edge.ui.view.model.OcrViewResultModel
//import com.navinfo.collect.FlutterBaseActivity
//import com.navinfo.collect.library.data.dao.impl.MapLifeDataBase
//import com.navinfo.ocr.OCRManager
//import kotlinx.coroutines.Dispatchers
//import kotlinx.coroutines.launch
//import kotlinx.coroutines.withContext
//import java.io.*
//import java.util.*
//
//interface OnOCRBatchListener {
// fun onProgress(total: Int, current: Int)
// suspend fun onResult(list: List<Map<String, Any>>)
//}
//
//open class DataCameraHandler(
// context: Context,
// activity: FlutterBaseActivity,
// dataBase: MapLifeDataBase
//) :
// BaseDataHandler(context, dataBase) {
//
// private val mActivity: FlutterBaseActivity = activity
//
// init {
// OCRManager.instance.init(activity)
// }
//
// fun openCamera() {
// OCRManager.instance.openCamera(mActivity)
// }
//
// /**
// * 批量OCR识别
// */
// fun ocrBatch(filePath: String, listener: OnOCRBatchListener) {
// mActivity.launch(Dispatchers.IO) {
// Log.e("jingo", "OCRManager 线程开始 ${Thread.currentThread().name}")
// val file = File(filePath)
// val resultList = mutableListOf<Map<String, Any>>()
// if (file.isDirectory) {
// val fileList = file.listFiles()
// val bitmapList = mutableListOf<String>()
// for (item in fileList!!) {
// if (item.isFile) {
// if (checkIsImageFile(item.name)) {
// bitmapList.add(item.path)
// }
// }
// }
// val bfw: BufferedWriter
// val csvFile = File("$filePath/ocr.csv")
// val out: FileOutputStream
// val osw: OutputStreamWriter
// try {
// out = FileOutputStream(csvFile)
// //用excel打开中文会乱码所以用GBK编译
// osw = OutputStreamWriter(out, "GBK")
// bfw = BufferedWriter(osw)
// //第一行表头数据
// bfw.write("图片路径和名称,")
// bfw.write("识别结果序号,")
// bfw.write("识别结果内容,")
// bfw.write("置信度,")
// bfw.write("识别面积,")
// bfw.write("图片大小,")
// bfw.write("识别区域,")
// //写好表头后换行
// bfw.newLine()
// for (i in 0 until bitmapList.size) {
// val path = bitmapList[i]
//
// val bitmap: Bitmap? = readFile(path)
// var exif = ExifInterface(path)
// val exifRotation = exif.getAttributeInt(
// ExifInterface.TAG_ORIENTATION,
// ExifInterface.ORIENTATION_NORMAL
// )
// val rotation = ImageUtil.exifToDegrees(exifRotation)
// val rotateBitmap = ImageUtil.createRotateBitmap(bitmap, rotation)
// val list = OCRManager.instance.ocr(rotateBitmap)
//
//
//// val list = ocrBitmap(path)
// if (list != null) {
// for (o in list) {
// bfw.write("$path,")
// bfw.write("${o.index},")
// bfw.write("${o.name},")
// bfw.write("${o.confidence.toString()},")
// val pointList = o.bounds
// bfw.write("${(pointList[3].y - pointList[0].y) * (pointList[2].x - pointList[0].x)},")
// bfw.write("${rotateBitmap.width} ${rotateBitmap.height},")
// bfw.write("${o.bounds[0].x} ${o.bounds[0].y};${o.bounds[1].x} ${o.bounds[1].y};${o.bounds[2].x} ${o.bounds[2].y};${o.bounds[3].x} ${o.bounds[3].y},")
// bfw.newLine()
// }
// bfw.newLine()
// withContext(Dispatchers.Main) {
// listener.onProgress(bitmapList.size, i)
// }
// val m1 = mutableMapOf<String, Any>();
// m1["data"] = list;
// m1["width"] = rotateBitmap.width
// m1["height"] = rotateBitmap.height
// m1["path"] = path
// resultList.add(m1)
// }
// rotateBitmap.recycle()
// }
//
// //将缓存数据写入文件
// bfw.flush()
// //释放缓存
// bfw.close()
// osw.close()
// out.close()
// } catch (e: Throwable) {
//
// }
// //将缓存数据写入文件
//
// withContext(Dispatchers.Main) {
// Log.e("jingo", "OCRManager 线程名称2 ${Thread.currentThread().name}")
// listener.onResult(resultList)
// }
// } else if (file.isFile && checkIsImageFile(file.name)) {
// val list = ocrBitmap(filePath)
// if (list != null) {
// withContext(Dispatchers.Main) {
// Log.e("jingo", "OCRManager 线程名称2 ${Thread.currentThread().name}")
// listener.onProgress(1, 1)
// }
// val m = mutableMapOf<String, List<OcrViewResultModel>>()
// m[file.name] = list
// resultList.add(m)
// }
// withContext(Dispatchers.Main) {
// Log.e("jingo", "OCRManager 线程名称2 ${Thread.currentThread().name}")
// listener.onResult(resultList)
// }
// }
//
// }
// }
//
// private fun ocrBitmap(path: String): List<OcrViewResultModel>? {
// try {
// val bitmap: Bitmap? = readFile(path)
// var exif = ExifInterface(path)
// val exifRotation = exif.getAttributeInt(
// ExifInterface.TAG_ORIENTATION,
// ExifInterface.ORIENTATION_NORMAL
// )
// val rotation = ImageUtil.exifToDegrees(exifRotation)
// val rotateBitmap = ImageUtil.createRotateBitmap(bitmap, rotation)
// val res = OCRManager.instance.ocr(rotateBitmap)
// rotateBitmap.recycle()
// return res
// } catch (e: IOException) {
// Log.e("jingo", "图像识别,获取图像信息失败 ${e.printStackTrace()}")
// }
// return null
// }
//
// /**
// * 检查是不是bitmap文件
// */
// private fun checkIsImageFile(fName: String): Boolean {
// val isImageFile: Boolean
// // 获取扩展名
// val fileEnd = fName.substring(
// fName.lastIndexOf(".") + 1,
// fName.length
// ).lowercase(Locale.getDefault())
// isImageFile =
// fileEnd == "jpg" || fileEnd == "png" || fileEnd == "webp" || fileEnd == "jpeg" || fileEnd == "bmp"
// return isImageFile
// }
//
// /**
// * 读取bitmap文件
// */
// private fun readFile(path: String): Bitmap? {
// var stream: FileInputStream? = null
// try {
// stream = FileInputStream(path)
// return BitmapFactory.decodeStream(stream)
// } catch (e: FileNotFoundException) {
// e.printStackTrace()
// } finally {
// if (stream != null) {
// try {
// stream.close()
// } catch (e: IOException) {
// e.printStackTrace()
// }
// }
// }
// return null
// }
//
//// private fun onOcrBitmap(
//// bitmap, confidence,
//// object: OcrListener {
//// override fun onResult(models: List<BasePolygonResultModel>) {
//// if (models == null) {
//// listener.onResult(null)
//// return
//// }
//// ocrResultModelCache = models
//// listener.onResult(models)
//// }
//// })
//
//}

View File

@ -1,331 +1,331 @@
package com.navinfo.collect.library.map; //package com.navinfo.collect.library.map;
//
import android.app.Activity; //import android.app.Activity;
import android.content.Context; //import android.content.Context;
import android.graphics.BitmapFactory; //import android.graphics.BitmapFactory;
import android.graphics.Color; //import android.graphics.Color;
import android.location.Location; //import android.location.Location;
import android.os.Environment; //import android.os.Environment;
import android.text.TextPaint; //import android.text.TextPaint;
import android.util.Log; //import android.util.Log;
import android.widget.TextView; //import android.widget.TextView;
import android.widget.Toast; //import android.widget.Toast;
//
import com.badlogic.gdx.maps.MapGroupLayer; //import com.badlogic.gdx.maps.MapGroupLayer;
import com.navinfo.collect.library.R; //import com.navinfo.collect.library.R;
import com.navinfo.collect.library.map.layers.NIPolygonLayer; //import com.navinfo.collect.library.map.layers.NIPolygonLayer;
import com.navinfo.collect.library.map.source.NavinfoMapRastorTileSource; //import com.navinfo.collect.library.map.source.NavinfoMapRastorTileSource;
import com.navinfo.collect.library.map.source.NavinfoMultiMapFileTileSource; //import com.navinfo.collect.library.map.source.NavinfoMultiMapFileTileSource;
import com.navinfo.collect.library.utils.DistanceUtil; //import com.navinfo.collect.library.utils.DistanceUtil;
import com.navinfo.collect.library.utils.GeometryTools; //import com.navinfo.collect.library.utils.GeometryTools;
import com.navinfo.collect.library.utils.StringUtil; //import com.navinfo.collect.library.utils.StringUtil;
//
import org.locationtech.jts.geom.Geometry; //import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.Polygon; //import org.locationtech.jts.geom.Polygon;
import org.oscim.android.canvas.AndroidBitmap; //import org.oscim.android.canvas.AndroidBitmap;
import org.oscim.backend.CanvasAdapter; //import org.oscim.backend.CanvasAdapter;
import org.oscim.backend.canvas.Bitmap; //import org.oscim.backend.canvas.Bitmap;
import org.oscim.core.GeoPoint; //import org.oscim.core.GeoPoint;
import org.oscim.core.MapPosition; //import org.oscim.core.MapPosition;
import org.oscim.event.Event; //import org.oscim.event.Event;
import org.oscim.layers.Layer; //import org.oscim.layers.Layer;
import org.oscim.layers.LocationLayer; //import org.oscim.layers.LocationLayer;
import org.oscim.layers.marker.ItemizedLayer; //import org.oscim.layers.marker.ItemizedLayer;
import org.oscim.layers.marker.MarkerInterface; //import org.oscim.layers.marker.MarkerInterface;
import org.oscim.layers.marker.MarkerItem; //import org.oscim.layers.marker.MarkerItem;
import org.oscim.layers.marker.MarkerSymbol; //import org.oscim.layers.marker.MarkerSymbol;
import org.oscim.layers.tile.bitmap.BitmapTileLayer; //import org.oscim.layers.tile.bitmap.BitmapTileLayer;
import org.oscim.layers.tile.vector.VectorTileLayer; //import org.oscim.layers.tile.vector.VectorTileLayer;
import org.oscim.layers.vector.geometries.Drawable; //import org.oscim.layers.vector.geometries.Drawable;
import org.oscim.layers.vector.geometries.PointDrawable; //import org.oscim.layers.vector.geometries.PointDrawable;
import org.oscim.layers.vector.geometries.PolygonDrawable; //import org.oscim.layers.vector.geometries.PolygonDrawable;
import org.oscim.layers.vector.PathLayer; //import org.oscim.layers.vector.PathLayer;
import org.oscim.layers.vector.geometries.Style; //import org.oscim.layers.vector.geometries.Style;
import org.oscim.map.Map; //import org.oscim.map.Map;
import org.oscim.tiling.source.OkHttpEngine; //import org.oscim.tiling.source.OkHttpEngine;
//
import java.io.File; //import java.io.File;
import java.math.BigDecimal; //import java.math.BigDecimal;
import java.util.ArrayList; //import java.util.ArrayList;
import java.util.HashMap; //import java.util.HashMap;
import java.util.List; //import java.util.List;
//
import okhttp3.Cache; //import okhttp3.Cache;
import okhttp3.OkHttpClient; //import okhttp3.OkHttpClient;
//
public class NILayerManager implements ItemizedLayer.OnItemGestureListener { //public class NILayerManager implements ItemizedLayer.OnItemGestureListener {
private Map vtmMap; // private Map vtmMap;
public static String defaultDir = Environment.getExternalStorageDirectory() + "/" + "NavinfoCollect"; // public static String defaultDir = Environment.getExternalStorageDirectory() + "/" + "NavinfoCollect";
private String defaultLocalMapPath = defaultDir + "/maps/"; // private String defaultLocalMapPath = defaultDir + "/maps/";
//图层管理 // //图层管理
private java.util.Map<String, Layer> layersMap = new HashMap<String, Layer>(); // private java.util.Map<String, Layer> layersMap = new HashMap<String, Layer>();
//默认marker图层 // //默认marker图层
private ItemizedLayer mDefaultMarkerLayer; // private ItemizedLayer mDefaultMarkerLayer;
//定位图层 // //定位图层
private LocationLayer mLocationLayer; // private LocationLayer mLocationLayer;
private NIPolygonLayer mPolygonLayer; // private NIPolygonLayer mPolygonLayer;
private List<MarkerItem> mPathMakers = new ArrayList<>(); // private List<MarkerItem> mPathMakers = new ArrayList<>();
private Location mCurrentLocation; // 当前位置信息 // private Location mCurrentLocation; // 当前位置信息
//
public static final String MARQUEE_MARKER_LAYER = "MarqueeMarker"; // public static final String MARQUEE_MARKER_LAYER = "MarqueeMarker";
//
private Context mCon; // private Context mCon;
//
private java.util.Map<String, Layer> vectorLayerMap; // 维护vector图层的map数据key为图层名称一般对应为矢量数据的数据源value为图层 // private java.util.Map<String, Layer> vectorLayerMap; // 维护vector图层的map数据key为图层名称一般对应为矢量数据的数据源value为图层
//
public NILayerManager(Context context, Map vtmMap) { // public NILayerManager(Context context, Map vtmMap) {
this.vtmMap = vtmMap; // this.vtmMap = vtmMap;
this.mCon = context; // this.mCon = context;
//
//新增marker图标样式 // //新增marker图标样式
AndroidBitmap mDefaultBitmap = // AndroidBitmap mDefaultBitmap =
new AndroidBitmap(BitmapFactory.decodeResource(context.getResources(), R.mipmap.marker)); // new AndroidBitmap(BitmapFactory.decodeResource(context.getResources(), R.mipmap.marker));
MarkerSymbol markerSymbol = new MarkerSymbol(mDefaultBitmap, MarkerSymbol.HotspotPlace.BOTTOM_CENTER); // MarkerSymbol markerSymbol = new MarkerSymbol(mDefaultBitmap, MarkerSymbol.HotspotPlace.BOTTOM_CENTER);
//新增marker图层 // //新增marker图层
mDefaultMarkerLayer = new ItemizedLayer( // mDefaultMarkerLayer = new ItemizedLayer(
vtmMap, // vtmMap,
new ArrayList<MarkerInterface>(), // new ArrayList<MarkerInterface>(),
markerSymbol, // markerSymbol,
this // this
); // );
addLayer("defaultMarkerLayer", mDefaultMarkerLayer, NIMapView.LAYER_GROUPS.VECTOR.ordinal()); // addLayer("defaultMarkerLayer", mDefaultMarkerLayer, NIMapView.LAYER_GROUPS.VECTOR.ordinal());
//
//定位图层 // //定位图层
mLocationLayer = new LocationLayer(vtmMap); // mLocationLayer = new LocationLayer(vtmMap);
addLayer("locationLayer", mLocationLayer, NIMapView.LAYER_GROUPS.ALLWAYS_SHOW_GROUP.ordinal()); // addLayer("locationLayer", mLocationLayer, NIMapView.LAYER_GROUPS.ALLWAYS_SHOW_GROUP.ordinal());
//
if (this.vectorLayerMap == null) { // if (this.vectorLayerMap == null) {
this.vectorLayerMap = new HashMap<>(); // this.vectorLayerMap = new HashMap<>();
} // }
} // }
//
public Layer getRasterTileLayer(Context mContext, String url, String tilePath, boolean useCache) { // public Layer getRasterTileLayer(Context mContext, String url, String tilePath, boolean useCache) {
if (this.vtmMap == null) { // if (this.vtmMap == null) {
throw new IllegalStateException("无法获取到map对象"); // throw new IllegalStateException("无法获取到map对象");
} // }
OkHttpClient.Builder builder = new OkHttpClient.Builder(); // OkHttpClient.Builder builder = new OkHttpClient.Builder();
NavinfoMapRastorTileSource mTileSource = NavinfoMapRastorTileSource.builder(url).tilePath(tilePath).httpFactory(new OkHttpEngine.OkHttpFactory(builder)).build(); // NavinfoMapRastorTileSource mTileSource = NavinfoMapRastorTileSource.builder(url).tilePath(tilePath).httpFactory(new OkHttpEngine.OkHttpFactory(builder)).build();
// 如果使用缓存 // // 如果使用缓存
if (useCache) { // if (useCache) {
File cacheDirectory = new File(defaultDir, "tiles-raster"); // File cacheDirectory = new File(defaultDir, "tiles-raster");
int cacheSize = 300 * 1024 * 1024; // 300 MB // int cacheSize = 300 * 1024 * 1024; // 300 MB
Cache cache = new Cache(cacheDirectory, cacheSize); // Cache cache = new Cache(cacheDirectory, cacheSize);
builder.cache(cache); // builder.cache(cache);
} // }
//
// mTileSource.setHttpEngine(new OkHttpEngine.OkHttpFactory(builder)); //// mTileSource.setHttpEngine(new OkHttpEngine.OkHttpFactory(builder));
// mTileSource.setHttpRequestHeaders(Collections.singletonMap("User-Agent", "vtm-android-example")); //// mTileSource.setHttpRequestHeaders(Collections.singletonMap("User-Agent", "vtm-android-example"));
// mTileSource.setCache(new TileCache(mContext, defaultDir, url.substring(url.indexOf(":")+1))); //// mTileSource.setCache(new TileCache(mContext, defaultDir, url.substring(url.indexOf(":")+1)));
//
BitmapTileLayer rasterLayer = new BitmapTileLayer(this.vtmMap, mTileSource); // BitmapTileLayer rasterLayer = new BitmapTileLayer(this.vtmMap, mTileSource);
return rasterLayer; // return rasterLayer;
} // }
//
// 初始化请求在线底图数据 // // 初始化请求在线底图数据
public Layer getDefaultVectorLayer(boolean useCache) { // public Layer getDefaultVectorLayer(boolean useCache) {
OkHttpClient.Builder builder = new OkHttpClient.Builder(); // OkHttpClient.Builder builder = new OkHttpClient.Builder();
if (useCache) { // if (useCache) {
// Cache the tiles into file system // // Cache the tiles into file system
File cacheDirectory = new File(defaultDir, "tiles-vector"); // File cacheDirectory = new File(defaultDir, "tiles-vector");
int cacheSize = 200 * 1024 * 1024; // 200 MB // int cacheSize = 200 * 1024 * 1024; // 200 MB
Cache cache = new Cache(cacheDirectory, cacheSize); // Cache cache = new Cache(cacheDirectory, cacheSize);
builder.cache(cache); // builder.cache(cache);
} // }
//
NavinfoMultiMapFileTileSource tileSource = NavinfoMultiMapFileTileSource.builder() // NavinfoMultiMapFileTileSource tileSource = NavinfoMultiMapFileTileSource.builder()
.apiKey("4wTLZyXcQym31pxC_HGy7Q") // Put a proper API key // .apiKey("4wTLZyXcQym31pxC_HGy7Q") // Put a proper API key
.httpFactory(new OkHttpEngine.OkHttpFactory(builder)) // .httpFactory(new OkHttpEngine.OkHttpFactory(builder))
//.locale("en") // //.locale("en")
.build(); // .build();
HashMap<String, String> headerMap = new HashMap<>(); // HashMap<String, String> headerMap = new HashMap<>();
headerMap.put("token", "eyJhbGciOiJIUzI1NiJ9.eyJjbGllbnRJZCI6MTAzLCJ1c2VyTmFtZSI6ImFkbWluIiwidXNlcklkIjoxLCJ1c2VyR3JvdXAiOiLnoJTlj5Hpg6giLCJvcmdJZCI6MSwiaWF0IjoxNjMwOTk4MzI5LCJleHAiOjE2MzEwODQ3Mjl9.0wFm8mAA9dCC2FmZj-u1dhxTFDRYx8AqVnh2C88hitk"); // headerMap.put("token", "eyJhbGciOiJIUzI1NiJ9.eyJjbGllbnRJZCI6MTAzLCJ1c2VyTmFtZSI6ImFkbWluIiwidXNlcklkIjoxLCJ1c2VyR3JvdXAiOiLnoJTlj5Hpg6giLCJvcmdJZCI6MSwiaWF0IjoxNjMwOTk4MzI5LCJleHAiOjE2MzEwODQ3Mjl9.0wFm8mAA9dCC2FmZj-u1dhxTFDRYx8AqVnh2C88hitk");
tileSource.setHttpRequestHeaders(headerMap); // tileSource.setHttpRequestHeaders(headerMap);
VectorTileLayer l = new VectorTileLayer(this.vtmMap, tileSource); // VectorTileLayer l = new VectorTileLayer(this.vtmMap, tileSource);
return l; // return l;
} // }
//
public void addLayer(String tag, Layer layer) { // public void addLayer(String tag, Layer layer) {
if (!layersMap.containsKey(tag)) { // if (!layersMap.containsKey(tag)) {
layersMap.put(tag, layer); // layersMap.put(tag, layer);
vtmMap.layers().add(layer); // vtmMap.layers().add(layer);
} // }
} // }
//
//
public void addLayer(String tag, Layer layer, int group) { // public void addLayer(String tag, Layer layer, int group) {
if (!layersMap.containsKey(tag)) { // if (!layersMap.containsKey(tag)) {
layersMap.put(tag, layer); // layersMap.put(tag, layer);
vtmMap.layers().add(layer, group); // vtmMap.layers().add(layer, group);
} // }
} // }
//
public void addLayer(int index, String tag, Layer layer) { // public void addLayer(int index, String tag, Layer layer) {
if (!layersMap.containsKey(tag)) { // if (!layersMap.containsKey(tag)) {
layersMap.put(tag, layer); // layersMap.put(tag, layer);
vtmMap.layers().add(index, layer); // vtmMap.layers().add(index, layer);
} // }
} // }
//
public boolean containsLayer(String tag) { // public boolean containsLayer(String tag) {
return layersMap.containsKey(tag); // return layersMap.containsKey(tag);
} // }
//
public Layer getLayer(String tag) { // public Layer getLayer(String tag) {
return layersMap.get(tag); // return layersMap.get(tag);
} // }
//
public void removeLayer(String tag) { // public void removeLayer(String tag) {
if (layersMap.containsKey(tag)) { // if (layersMap.containsKey(tag)) {
Layer layer = layersMap.remove(tag); // Layer layer = layersMap.remove(tag);
vtmMap.layers().remove(layer); // vtmMap.layers().remove(layer);
} // }
} // }
//
/** // /**
* 返回默认marker图层 // * 返回默认marker图层
* // *
* @return mDefaultMarkerLayer // * @return mDefaultMarkerLayer
*/ // */
public ItemizedLayer getDefaultMarkerLayer() { // public ItemizedLayer getDefaultMarkerLayer() {
return mDefaultMarkerLayer; // return mDefaultMarkerLayer;
} // }
//
/** // /**
* 返回定位图层 // * 返回定位图层
* // *
* @return mLocationLayer // * @return mLocationLayer
*/ // */
public LocationLayer getLocationLayer() { // public LocationLayer getLocationLayer() {
return mLocationLayer; // return mLocationLayer;
} // }
//
//
@Override // @Override
public boolean onItemSingleTapUp(int index, Object item) { // public boolean onItemSingleTapUp(int index, Object item) {
return false; // return false;
} // }
//
@Override // @Override
public boolean onItemLongPress(int index, Object item) { // public boolean onItemLongPress(int index, Object item) {
return false; // return false;
} // }
//
/** // /**
* 定位 // * 定位
* @param lon // * @param lon
* @param lat // * @param lat
* @param time // * @param time
*/ // */
public void jumpToPosition(double lon, double lat, long time) { // public void jumpToPosition(double lon, double lat, long time) {
MapPosition mapPosition = vtmMap.getMapPosition(); // MapPosition mapPosition = vtmMap.getMapPosition();
mapPosition.setPosition(lat, lon); // mapPosition.setPosition(lat, lon);
vtmMap.animator().animateTo(time, mapPosition); // vtmMap.animator().animateTo(time, mapPosition);
} // }
//
/** // /**
* 定位 // * 定位
* @param lon // * @param lon
* @param lat // * @param lat
* @param zoomLevel // * @param zoomLevel
*/ // */
public void jumpToPosition(double lon, double lat, int zoomLevel) { // public void jumpToPosition(double lon, double lat, int zoomLevel) {
MapPosition mapPosition = vtmMap.getMapPosition(); // MapPosition mapPosition = vtmMap.getMapPosition();
if (mapPosition.getZoomLevel() < zoomLevel) { // if (mapPosition.getZoomLevel() < zoomLevel) {
mapPosition.setZoomLevel(zoomLevel); // mapPosition.setZoomLevel(zoomLevel);
} // }
mapPosition.setPosition(lat, lon); // mapPosition.setPosition(lat, lon);
vtmMap.animator().animateTo(300, mapPosition); // vtmMap.animator().animateTo(300, mapPosition);
} // }
//
public void addMarker2MarkerLayer(MarkerInterface markerItem, Bitmap defaultBitmap, String layerName, int layerGroup) { // public void addMarker2MarkerLayer(MarkerInterface markerItem, Bitmap defaultBitmap, String layerName, int layerGroup) {
if (markerItem == null) { // if (markerItem == null) {
return; // return;
} // }
if (vectorLayerMap != null) { // if (vectorLayerMap != null) {
if (!vectorLayerMap.containsKey(layerName) || vectorLayerMap.get(layerName) == null) { // if (!vectorLayerMap.containsKey(layerName) || vectorLayerMap.get(layerName) == null) {
MarkerSymbol symbol = new MarkerSymbol(defaultBitmap, MarkerSymbol.HotspotPlace.BOTTOM_CENTER); // MarkerSymbol symbol = new MarkerSymbol(defaultBitmap, MarkerSymbol.HotspotPlace.BOTTOM_CENTER);
vectorLayerMap.put(layerName, new ItemizedLayer(vtmMap, symbol)); // vectorLayerMap.put(layerName, new ItemizedLayer(vtmMap, symbol));
} // }
//
ItemizedLayer itemizedLayer = (ItemizedLayer) vectorLayerMap.get(layerName); // ItemizedLayer itemizedLayer = (ItemizedLayer) vectorLayerMap.get(layerName);
itemizedLayer.addItem(markerItem); // itemizedLayer.addItem(markerItem);
if (!vtmMap.layers().contains(itemizedLayer)) { // if (!vtmMap.layers().contains(itemizedLayer)) {
vtmMap.layers().add(itemizedLayer, layerGroup); // vtmMap.layers().add(itemizedLayer, layerGroup);
} // }
itemizedLayer.update(); // itemizedLayer.update();
} // }
} // }
//
public void addMarker2MarkerLayer(MarkerInterface markerItem, Bitmap defaultBitmap, String layerName, int layerGroup, ItemizedLayer.OnItemGestureListener listener) { // public void addMarker2MarkerLayer(MarkerInterface markerItem, Bitmap defaultBitmap, String layerName, int layerGroup, ItemizedLayer.OnItemGestureListener listener) {
if (markerItem == null) { // if (markerItem == null) {
return; // return;
} // }
if (vectorLayerMap != null) { // if (vectorLayerMap != null) {
if (!vectorLayerMap.containsKey(layerName) || vectorLayerMap.get(layerName) == null) { // if (!vectorLayerMap.containsKey(layerName) || vectorLayerMap.get(layerName) == null) {
MarkerSymbol symbol = new MarkerSymbol(defaultBitmap, MarkerSymbol.HotspotPlace.BOTTOM_CENTER); // MarkerSymbol symbol = new MarkerSymbol(defaultBitmap, MarkerSymbol.HotspotPlace.BOTTOM_CENTER);
vectorLayerMap.put(layerName, new ItemizedLayer(vtmMap, new ArrayList<MarkerInterface>(), symbol, listener)); // vectorLayerMap.put(layerName, new ItemizedLayer(vtmMap, new ArrayList<MarkerInterface>(), symbol, listener));
} // }
//
ItemizedLayer itemizedLayer = (ItemizedLayer) vectorLayerMap.get(layerName); // ItemizedLayer itemizedLayer = (ItemizedLayer) vectorLayerMap.get(layerName);
itemizedLayer.addItem(markerItem); // itemizedLayer.addItem(markerItem);
if (!vtmMap.layers().contains(itemizedLayer)) { // if (!vtmMap.layers().contains(itemizedLayer)) {
vtmMap.layers().add(itemizedLayer, layerGroup); // vtmMap.layers().add(itemizedLayer, layerGroup);
} // }
itemizedLayer.update(); // itemizedLayer.update();
} // }
} // }
//
//删除marker // //删除marker
public void removeMarker(MarkerItem markerItem) { // public void removeMarker(MarkerItem markerItem) {
if (vectorLayerMap != null && vectorLayerMap.containsKey("Marker")) { // if (vectorLayerMap != null && vectorLayerMap.containsKey("Marker")) {
ItemizedLayer itemizedLayer = (ItemizedLayer) vectorLayerMap.get("Marker"); // ItemizedLayer itemizedLayer = (ItemizedLayer) vectorLayerMap.get("Marker");
if (itemizedLayer.getItemList() != null && itemizedLayer.getItemList().size() > 0) { // if (itemizedLayer.getItemList() != null && itemizedLayer.getItemList().size() > 0) {
itemizedLayer.removeItem(markerItem); // itemizedLayer.removeItem(markerItem);
} // }
} // }
} // }
//
/** // /**
* @param markerItem marker // * @param markerItem marker
* @param layerName 图层 // * @param layerName 图层
*/ // */
public void removeMarker(MarkerItem markerItem, String layerName) { // public void removeMarker(MarkerItem markerItem, String layerName) {
if (vectorLayerMap != null && layerName != null && vectorLayerMap.containsKey(layerName)) { // if (vectorLayerMap != null && layerName != null && vectorLayerMap.containsKey(layerName)) {
ItemizedLayer itemizedLayer = (ItemizedLayer) vectorLayerMap.get(layerName); // ItemizedLayer itemizedLayer = (ItemizedLayer) vectorLayerMap.get(layerName);
if (itemizedLayer.getItemList() != null && itemizedLayer.getItemList().size() > 0) { // if (itemizedLayer.getItemList() != null && itemizedLayer.getItemList().size() > 0) {
itemizedLayer.removeItem(markerItem); // itemizedLayer.removeItem(markerItem);
} // }
} // }
} // }
//
//
/** // /**
* 在地图中心增加marker // * 在地图中心增加marker
*/ // */
public void showEditMapGraphical(String geometry, int type) { // public void showEditMapGraphical(String geometry, int type) {
//
} // }
//
//增加marker // //增加marker
public MarkerItem addMarker(GeoPoint geopoint, Bitmap bitmap) { // public MarkerItem addMarker(GeoPoint geopoint, Bitmap bitmap) {
if (geopoint != null && bitmap != null) { // if (geopoint != null && bitmap != null) {
//
MarkerItem markerItem = new MarkerItem(StringUtil.Companion.createUUID(), "", geopoint.getLatitude() + "," + geopoint.getLongitude(), geopoint); // MarkerItem markerItem = new MarkerItem(StringUtil.Companion.createUUID(), "", geopoint.getLatitude() + "," + geopoint.getLongitude(), geopoint);
//
MarkerSymbol markerSymbol = new MarkerSymbol(bitmap, MarkerSymbol.HotspotPlace.BOTTOM_CENTER); // MarkerSymbol markerSymbol = new MarkerSymbol(bitmap, MarkerSymbol.HotspotPlace.BOTTOM_CENTER);
//
markerItem.setMarker(markerSymbol); // markerItem.setMarker(markerSymbol);
//
addMarker2MarkerLayer(markerItem, bitmap, "", NIMapView.LAYER_GROUPS.OTHER.ordinal()); // addMarker2MarkerLayer(markerItem, bitmap, "", NIMapView.LAYER_GROUPS.OTHER.ordinal());
//
return markerItem; // return markerItem;
} // }
//
return null; // return null;
} // }
//
public Location getCurrentLocation() { // public Location getCurrentLocation() {
return mCurrentLocation; // return mCurrentLocation;
} // }
//
} //}

View File

@ -1,8 +0,0 @@
package com.navinfo.collect.library.map
import android.location.Location
class NILocation(provider: String) : Location(provider) {
var radius = 0f
}

View File

@ -1,386 +1,330 @@
package com.navinfo.collect.library.map; //package com.navinfo.collect.library.map;
//
import android.graphics.Bitmap; //import android.graphics.Bitmap;
import android.graphics.Rect; //import android.graphics.Rect;
import android.view.MotionEvent; //import android.view.View;
import android.view.View; //
//import com.navinfo.collect.library.utils.CacheTileProgress;
import com.navinfo.collect.library.utils.CacheTileProgress; //import com.navinfo.collect.library.utils.TileDownloader;
import com.navinfo.collect.library.utils.TileDownloader; //import com.yanzhenjie.kalle.download.Download;
import com.yanzhenjie.kalle.Kalle; //
import com.yanzhenjie.kalle.download.Download; //import org.oscim.core.GeoPoint;
//import org.oscim.core.MapPosition;
import org.oscim.core.GeoPoint; //import org.oscim.layers.Layer;
import org.oscim.core.MapPosition; //import org.oscim.layers.tile.bitmap.BitmapTileLayer;
import org.oscim.layers.Layer; //import org.oscim.map.Map;
import org.oscim.layers.tile.bitmap.BitmapTileLayer; //import org.oscim.tiling.source.UrlTileSource;
import org.oscim.map.Map; //
import org.oscim.tiling.source.UrlTileSource; //import java.util.ArrayList;
//import java.util.List;
import java.util.ArrayList; //import java.util.concurrent.Callable;
import java.util.List; //import java.util.concurrent.Executors;
import java.util.concurrent.Callable; //import java.util.concurrent.FutureTask;
import java.util.concurrent.Executors; //import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.FutureTask; //
import java.util.concurrent.ScheduledExecutorService; ///**
// * 定义 NavinfoMap 地图对象的操作方法与接口
/** // */
* 定义 NavinfoMap 地图对象的操作方法与接口 //public class NIMap {
*/ // /**
public class NIMap { // *
/** // */
* // private Map map;
*/ // /**
private Map map; // * 地图控件
/** // */
* 地图控件 // private NIMapView mMapView;
*/ // /**
private NIMapView mMapView; // * 指北针显隐
/** // */
* 指北针显隐 // private boolean enableCompassImage = true;
*/ //
private boolean enableCompassImage = true; // /**
// * 用户位置显示图层
/** // * */
* 用户位置显示图层 //// private NaviLocationLayer locationLayer;
* */ //
// private NaviLocationLayer locationLayer; // /**
/** // * 构造函数
* 构造函数 // */
*/ // public NIMap(NIMapView niMapView) {
public NIMap(NIMapView niMapView) { // this.mMapView = niMapView;
this.mMapView = niMapView; // this.map = mMapView.getVtmMap();
this.map = mMapView.getVtmMap();
}
/**
* 获取地图的当前状态
*
* @return
*/
public Map getVtmMap() {
return map;
}
/**
* 获取地图最大缩放级别
*
* @return
*/
public float getMaxZoomLevel() {
return map.viewport().getMaxZoomLevel();
}
/**
* 获取地图最小缩放级别
*
* @return
*/
public float getMinZoomLevel() {
return map.viewport().getMinZoomLevel();
}
/**
* 设置指南针是否显示
*
* @param enable
*/
public void setCompassEnable(boolean enable) {
this.enableCompassImage = enable;
if (mMapView != null && mMapView.getCompassImage() != null) {
mMapView.getCompassImage().setVisibility(enable ? View.VISIBLE : View.GONE);
mMapView.getCompassImage().setEnabled(enable);
}
}
/**
* 获取指北针显隐控制
*
* @return true 显示 false 隐藏
*/
public boolean isEnableCompassImage() {
return enableCompassImage;
}
/**
* 设置指南针自定义图标
*
* @param icon
*/
public void setCompassIcon(Bitmap icon) {
if (mMapView != null && mMapView.getCompassImage() != null) {
mMapView.getCompassImage().setImageBitmap(icon);
}
}
/**
* 设置地图显示大小等级
*
* @param level
*/
public void setFontSizeLevel(int level) {
}
/**
* 设置地图最大以及最小缩放级别
*
* @param max
* @param min
*/
public void setMaxAndMinZoomLevel(int max, int min) {
map.viewport().setMaxZoomLevel(max);
map.viewport().setMinZoomLevel(min);
}
/**
* 放大
*
* @param animate 是否动画过渡
*/
public void zoomIn(boolean animate) {
MapPosition mapPosition = map.getMapPosition();
mapPosition.setZoom(mapPosition.getZoom() + 1);
if (animate) {
map.animator().animateTo(mapPosition);
} else {
map.setMapPosition(mapPosition);
}
}
/**
* 缩小地图
*
* @param animate 是否动画过渡
*/
public void zoomOut(boolean animate) {
MapPosition mapPosition = map.getMapPosition();
mapPosition.setZoom(mapPosition.getZoom() - 1);
if (animate) {
map.animator().animateTo(mapPosition);
} else {
map.setMapPosition(mapPosition);
}
}
/**
* 设置定位数据, 只有先允许定位图层后设置数据才会生效参见 setMyLocationEnabled(boolean)
*
* @param data
*/
// public void setMyLocationData(Location data) {
// if (locationLayer == null) {
// return;
// }
// locationLayer.setPosition(data.getLatitude(), data.getLongitude(), data.getAccuracy());
// } // }
//
// public void setMyLocationData(double lat, double lon, float accuracy) { // /**
// if (locationLayer == null) { // * 获取地图的当前状态
// return; // *
// } // * @return
// locationLayer.setPosition(lat, lon, accuracy); // */
// public Map getVtmMap() {
// return map;
// } // }
//
/** // /**
* 设置是否允许定位图层 // * 获取地图最大缩放级别
* // *
* @param enabled // * @return
*/ // */
// public void setMyLocationEnabled(Context mContext, boolean enabled) { // public float getMaxZoomLevel() {
// initLocaitonLayer(mContext); // return map.viewport().getMaxZoomLevel();
// locationLayer.setEnabled(enabled);
// } // }
//
// private void initLocaitonLayer(Context mContext) { // /**
// if (map == null) { // * 获取地图最小缩放级别
// throw new IllegalStateException("map不可用无法显示当前位置"); // *
// } // * @return
// if (locationLayer == null) { // */
// locationLayer = new NaviLocationLayer(mContext, map); // public float getMinZoomLevel() {
//
// return map.viewport().getMinZoomLevel();
// }
//
// /**
// * 设置指南针是否显示
// *
// * @param enable
// */
// public void setCompassEnable(boolean enable) {
// this.enableCompassImage = enable;
// if (mMapView != null && mMapView.getCompassImage() != null) {
// mMapView.getCompassImage().setVisibility(enable ? View.VISIBLE : View.GONE);
// mMapView.getCompassImage().setEnabled(enable);
// } // }
// } // }
//
/** // /**
* 设置地图 // * 获取指北针显隐控制
* */ // *
public void setMapPosition(double latitude, double longitude, int zoomLevel) { // * @return true 显示 false 隐藏
double scale = 1 << zoomLevel; // */
getVtmMap().setMapPosition(latitude, longitude, scale); // public boolean isEnableCompassImage() {
} // return enableCompassImage;
// }
public void animateMapPosition(double latitude, double longitude, int zoomLevel, int duration) { //
if (duration < 0) { // /**
duration = 500; // * 设置指南针自定义图标
} // *
if (zoomLevel <= 0) { // * @param icon
zoomLevel = getVtmMap().getMapPosition().zoomLevel; // */
} // public void setCompassIcon(Bitmap icon) {
double scale = 1 << zoomLevel; // if (mMapView != null && mMapView.getCompassImage() != null) {
MapPosition mapPosition = new MapPosition(latitude, longitude, scale); // mMapView.getCompassImage().setImageBitmap(icon);
getVtmMap().animator().animateTo(duration, mapPosition); // }
} // }
//
/** //
* 下载离线矢量地图 // /**
* */ // * 设置地图显示大小等级
public void downloadVectorMap(String url, DownloadProgress downloadProgress) { // *
Kalle.Download.get(url).directory(NILayerManager.defaultDir).onProgress(new Download.ProgressBar() { // * @param level
@Override // */
public void onProgress(int progress, long byteCount, long speed) { // public void setFontSizeLevel(int level) {
downloadProgress.onProgress(progress, byteCount, speed); //
} // }
}); //
} // /**
// * 设置地图最大以及最小缩放级别
/** // *
* 缓存urlTilesource对应的数据 // * @param max
* */ // * @param min
public List<FutureTask> cacheUrlTileMap(Rect rect, int minZoomLevel, int maxZoomLevel, CacheTileProgress progress) { // */
List<Layer> layerList = getVtmMap().layers(); // public void setMaxAndMinZoomLevel(int max, int min) {
List<UrlTileSource> urlTileSourceList = new ArrayList<>(); // map.viewport().setMaxZoomLevel(max);
if (layerList!=null&&!layerList.isEmpty()) { // map.viewport().setMinZoomLevel(min);
for (int i = 0; i < layerList.size(); i++) { // }
Layer layer = layerList.get(i); //
if (layer instanceof BitmapTileLayer && ((BitmapTileLayer) layer).getTileSource() instanceof UrlTileSource) { // /**
UrlTileSource urlTileSource = (UrlTileSource) ((BitmapTileLayer) layer).getTileSource(); // * 放大
urlTileSourceList.add(urlTileSource); // *
} // * @param animate 是否动画过渡
} // */
} // public void zoomIn(boolean animate) {
// 根据rect获取对应的地理坐标 // MapPosition mapPosition = map.getMapPosition();
GeoPoint leftTopGeoPoint = map.viewport().fromScreenPoint(rect.left, rect.top); // mapPosition.setZoom(mapPosition.getZoom() + 1);
GeoPoint rightBottomGeoPoint = map.viewport().fromScreenPoint(rect.right, rect.bottom); // if (animate) {
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); // map.animator().animateTo(mapPosition);
List<FutureTask> futureTaskList = new ArrayList<>(); // } else {
progress.setLayerCount(urlTileSourceList.size()); // map.setMapPosition(mapPosition);
for (int i = 0; i < urlTileSourceList.size(); i++) { // }
UrlTileSource urlTileSource = urlTileSourceList.get(i); // }
int finalI = i; //
progress.setLayerId(i); // /**
Callable callable = TileDownloader.getInstance().downloadRasterTile(urlTileSource, leftTopGeoPoint, rightBottomGeoPoint, (byte) minZoomLevel, (byte) maxZoomLevel, progress); // * 缩小地图
FutureTask futureTask = new FutureTask(callable); // *
futureTaskList.add(futureTask); // * @param animate 是否动画过渡
} // */
// public void zoomOut(boolean animate) {
if (futureTaskList!=null&&!futureTaskList.isEmpty()){ // MapPosition mapPosition = map.getMapPosition();
for (int i = 0; i < futureTaskList.size(); i++) { // mapPosition.setZoom(mapPosition.getZoom() - 1);
scheduledExecutorService.submit(futureTaskList.get(i)); // if (animate) {
} // map.animator().animateTo(mapPosition);
scheduledExecutorService.shutdown(); // } else {
} // map.setMapPosition(mapPosition);
return futureTaskList; // }
} // }
//
public void cancelCacheTileMap() { // /**
TileDownloader.getInstance().setCanDownloadRasterTile(false); // * 设置定位数据, 只有先允许定位图层后设置数据才会生效参见 setMyLocationEnabled(boolean)
} // *
// * @param data
public interface DownloadProgress { // */
//// public void setMyLocationData(Location data) {
Download.ProgressBar DEFAULT = new Download.ProgressBar() { //// if (locationLayer == null) {
@Override //// return;
public void onProgress(int progress, long byteCount, long speed) { //// }
} //// locationLayer.setPosition(data.getLatitude(), data.getLongitude(), data.getAccuracy());
}; //// }
//
/** //// public void setMyLocationData(double lat, double lon, float accuracy) {
* Download onProgress changes. //// if (locationLayer == null) {
*/ //// return;
void onProgress(int progress, long byteCount, long speed); //// }
} //// locationLayer.setPosition(lat, lon, accuracy);
//// }
/** //
* 设置地图单击事件监听者 // /**
* // * 设置是否允许定位图层
* @param listener // *
*/ // * @param enabled
public void setOnMapClickListener(OnMapClickListener listener) { // */
mMapView.setOnMapClickListener(listener); //// public void setMyLocationEnabled(Context mContext, boolean enabled) {
} //// initLocaitonLayer(mContext);
//// locationLayer.setEnabled(enabled);
/** //// }
* 设置地图双击事件监听者 //
* //// private void initLocaitonLayer(Context mContext) {
* @param listener //// if (map == null) {
*/ //// throw new IllegalStateException("map不可用无法显示当前位置");
public void setOnMapDoubleClickListener(OnMapDoubleClickListener listener) { //// }
mMapView.setOnMapDoubleClickListener(listener); //// if (locationLayer == null) {
} //// locationLayer = new NaviLocationLayer(mContext, map);
//// }
/** //// }
* 设置地图长按事件监听者 //
* // /**
* @param listener // * 设置地图
*/ // */
public void setOnMapLongClickListener(OnMapLongClickListener listener) { // public void setMapPosition(double latitude, double longitude, int zoomLevel) {
mMapView.setOnMapLongClickListener(listener); // double scale = 1 << zoomLevel;
} // getVtmMap().setMapPosition(latitude, longitude, scale);
// }
/** //
* @param listener // public void animateMapPosition(double latitude, double longitude, int zoomLevel, int duration) {
*/ // if (duration < 0) {
public void setOnMapTouchListener(OnMapTouchListener listener) { // duration = 500;
mMapView.setOnMapTouchListener(listener); // }
} // if (zoomLevel <= 0) {
// zoomLevel = getVtmMap().getMapPosition().zoomLevel;
/** // }
* 地图单击事件监听接口 // double scale = 1 << zoomLevel;
*/ // MapPosition mapPosition = new MapPosition(latitude, longitude, scale);
public static interface OnMapClickListener { // getVtmMap().animator().animateTo(duration, mapPosition);
/** // }
* 地图单击事件回调函数 //
* //// /**
* @param point //// * 下载离线矢量地图
*/ //// * */
void onMapClick(GeoPoint point); //// public void downloadVectorMap(String url, DownloadProgress downloadProgress) {
//// Kalle.Download.get(url).directory(NILayerManager.defaultDir).onProgress(new Download.ProgressBar() {
/** //// @Override
* 地图内 Poi 单击事件回调函数 //// public void onProgress(int progress, long byteCount, long speed) {
* //// downloadProgress.onProgress(progress, byteCount, speed);
* @param poi //// }
*/ //// });
void onMapPoiClick(GeoPoint poi); //// }
} //
// /**
/** // * 缓存urlTilesource对应的数据
* 地图双击事件监听接口 // */
*/ // public List<FutureTask> cacheUrlTileMap(Rect rect, int minZoomLevel, int maxZoomLevel, CacheTileProgress progress) {
public static interface OnMapDoubleClickListener { // List<Layer> layerList = getVtmMap().layers();
// List<UrlTileSource> urlTileSourceList = new ArrayList<>();
/** // if (layerList != null && !layerList.isEmpty()) {
* 地图双击事件监听回调函数 // for (int i = 0; i < layerList.size(); i++) {
* // Layer layer = layerList.get(i);
* @param point // if (layer instanceof BitmapTileLayer && ((BitmapTileLayer) layer).getTileSource() instanceof UrlTileSource) {
*/ // UrlTileSource urlTileSource = (UrlTileSource) ((BitmapTileLayer) layer).getTileSource();
void onMapDoubleClick(GeoPoint point); // urlTileSourceList.add(urlTileSource);
// }
} // }
// }
/** // // 根据rect获取对应的地理坐标
* 地图长按事件监听接口 // GeoPoint leftTopGeoPoint = map.viewport().fromScreenPoint(rect.left, rect.top);
*/ // GeoPoint rightBottomGeoPoint = map.viewport().fromScreenPoint(rect.right, rect.bottom);
public static interface OnMapLongClickListener { // ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
/** // List<FutureTask> futureTaskList = new ArrayList<>();
* 地图长按事件监听回调函数 // progress.setLayerCount(urlTileSourceList.size());
* // for (int i = 0; i < urlTileSourceList.size(); i++) {
* @param point // UrlTileSource urlTileSource = urlTileSourceList.get(i);
*/ // int finalI = i;
void onMapLongClick(GeoPoint point); // progress.setLayerId(i);
} // Callable callable = TileDownloader.getInstance().downloadRasterTile(urlTileSource, leftTopGeoPoint, rightBottomGeoPoint, (byte) minZoomLevel, (byte) maxZoomLevel, progress);
// FutureTask futureTask = new FutureTask(callable);
/** // futureTaskList.add(futureTask);
* 用户触摸地图时回调接口 // }
*/ //
public static interface OnMapTouchListener { // if (futureTaskList != null && !futureTaskList.isEmpty()) {
/** // for (int i = 0; i < futureTaskList.size(); i++) {
* 当用户触摸地图时回调函数 // scheduledExecutorService.submit(futureTaskList.get(i));
* // }
* @param event // scheduledExecutorService.shutdown();
*/ // }
void onTouch(MotionEvent event); // return futureTaskList;
} // }
//
} // public void cancelCacheTileMap() {
// TileDownloader.getInstance().setCanDownloadRasterTile(false);
// }
//
// public interface DownloadProgress {
//
// Download.ProgressBar DEFAULT = new Download.ProgressBar() {
// @Override
// public void onProgress(int progress, long byteCount, long speed) {
// }
// };
//
// /**
// * Download onProgress changes.
// */
// void onProgress(int progress, long byteCount, long speed);
// }
//
// /**
// * 设置地图单击事件监听者
// *
// * @param listener
// */
// public void setOnMapClickListener(OnMapClickListener listener) {
// mMapView.setOnMapClickListener(listener);
// }
//
// /**
// * 设置地图双击事件监听者
// *
// * @param listener
// */
// public void setOnMapDoubleClickListener(OnMapDoubleClickListener listener) {
// mMapView.setOnMapDoubleClickListener(listener);
// }
//
// /**
// * 设置地图长按事件监听者
// *
// * @param listener
// */
// public void setOnMapLongClickListener(OnMapLongClickListener listener) {
// mMapView.setOnMapLongClickListener(listener);
// }
//
// /**
// * @param listener
// */
// public void setOnMapTouchListener(OnMapTouchListener listener) {
// mMapView.setOnMapTouchListener(listener);
// }
//
//
//
//}

View File

@ -1,6 +1,7 @@
package com.navinfo.collect.library.map package com.navinfo.collect.library.map
import android.content.Context import android.content.Context
import com.navinfo.collect.library.data.entity.LayerManager
import com.navinfo.collect.library.map.handler.* import com.navinfo.collect.library.map.handler.*
import com.navinfo.collect.library.map.maphandler.MeasureLayerHandler import com.navinfo.collect.library.map.maphandler.MeasureLayerHandler
import com.navinfo.collect.library.map.handler.ViewportHandler import com.navinfo.collect.library.map.handler.ViewportHandler
@ -15,35 +16,16 @@ open class NIMapController(
mapView: NIMapView? = null, mapView: NIMapView? = null,
) { ) {
private val mContext = context private val mContext = context
internal var mMapView: NIMapView = var mMapView: NIMapView = mapView ?: NIMapView(mContext, options)
mapView ?: NIMapView(mContext, options)
val animationHandler: AnimationHandler by lazy { AnimationHandler(mContext, mMapView) } val layerManagerHandler = LayerManagerHandler(mContext, mMapView)
val markerHandle: MarkHandler by lazy { MarkHandler(mContext, mMapView) } val locationLayerHandler by lazy { LocationLayerHandler(mContext, mMapView) }
val locationLayerHandler: LocationLayerHandler by lazy { val animationHandler by lazy { AnimationHandler(mContext, mMapView) }
LocationLayerHandler( val markerHandle by lazy { MarkHandler(mContext, mMapView) }
mContext, val lineHandler by lazy { LineHandler(mContext, mMapView) }
mMapView val polygonHandler by lazy { PolygonHandler(mContext, mMapView) }
) val viewportHandler by lazy { ViewportHandler(mContext, mMapView) }
}; val measureLayerHandler by lazy { MeasureLayerHandler(mContext, mMapView) }
val lineHandler: LineHandler by lazy { LineHandler(mContext, mMapView) };
val polygonHandler: PolygonHandler by lazy { PolygonHandler(mContext, mMapView) };
val viewportHandler: ViewportHandler by lazy { ViewportHandler(mContext, mMapView) }
val measureLayerHandler: MeasureLayerHandler by lazy { MeasureLayerHandler(mContext, mMapView) };
/**
* 刷新地图
*/
fun upDateMap(redraw: Boolean = true) {
if (redraw) {
mMapView.vtmMap.events.fire(org.oscim.map.Map.CLEAR_EVENT, mMapView.vtmMap.mapPosition)
}
mMapView.vtmMap.updateMap(redraw)
}
open fun release() {
mMapView.onDestroy()
}
} }

View File

@ -47,6 +47,8 @@ import org.oscim.tiling.source.mapfile.MultiMapFileTileSource;
import java.io.File; import java.io.File;
/** /**
* 一个显示地图的视图View它负责从服务端获取地图数据它将会捕捉屏幕触控手势事件 * 一个显示地图的视图View它负责从服务端获取地图数据它将会捕捉屏幕触控手势事件
*/ */
@ -93,14 +95,82 @@ public final class NIMapView extends RelativeLayout {
/** /**
* 地图图层管理器 * 地图图层管理器
*/ */
private NILayerManager mLayerManager; // private NILayerManager mLayerManager;
private Layer baseRasterLayer, defaultVectorTileLayer, defaultVectorLabelLayer, gridLayer; // private Layer baseRasterLayer, defaultVectorTileLayer, defaultVectorLabelLayer, gridLayer;
/**
* 地图网格图层
*/
// private Layer gridLayer;
protected Context mContext; protected Context mContext;
/**
* 地图状态信息
*/
private MapPreferences mPrefs; private MapPreferences mPrefs;
protected String mapFilePath = Constant.ROOT_PATH+"/map"; // protected String mapFilePath = Constant.ROOT_PATH + "/map";
protected GroupLayer baseGroupLayer; // 用于盛放所有基础底图的图层组便于统一管理 protected GroupLayer baseGroupLayer; // 用于盛放所有基础底图的图层组便于统一管理
/**
* 地图单击事件监听接口
*/
public interface OnMapClickListener {
/**
* 地图单击事件回调函数
*
* @param point
*/
void onMapClick(GeoPoint point);
/**
* 地图内 Poi 单击事件回调函数
*
* @param poi
*/
void onMapPoiClick(GeoPoint poi);
}
/**
* 地图双击事件监听接口
*/
public interface OnMapDoubleClickListener {
/**
* 地图双击事件监听回调函数
*
* @param point
*/
void onMapDoubleClick(GeoPoint point);
}
/**
* 地图长按事件监听接口
*/
public interface OnMapLongClickListener {
/**
* 地图长按事件监听回调函数
*
* @param point
*/
void onMapLongClick(GeoPoint point);
}
/**
* 用户触摸地图时回调接口
*/
public interface OnMapTouchListener {
/**
* 当用户触摸地图时回调函数
*
* @param event
*/
void onTouch(MotionEvent event);
}
public NIMapView(Context context, NIMapOptions options) { public NIMapView(Context context, NIMapOptions options) {
this(context, null, 0); this(context, null, 0);
this.options = options; this.options = options;
@ -110,22 +180,22 @@ public final class NIMapView extends RelativeLayout {
/** /**
* 地图的单击事件监听 * 地图的单击事件监听
*/ */
private NIMap.OnMapClickListener mapClickListener; private OnMapClickListener mapClickListener;
/** /**
* 地图的双击事件监听 * 地图的双击事件监听
*/ */
private NIMap.OnMapDoubleClickListener mapDoubleClickListener; private OnMapDoubleClickListener mapDoubleClickListener;
/** /**
* 地图的长按事件监听 * 地图的长按事件监听
*/ */
private NIMap.OnMapLongClickListener mapLongClickListener; private OnMapLongClickListener mapLongClickListener;
/** /**
* 地图的触摸事件 * 地图的触摸事件
*/ */
private NIMap.OnMapTouchListener touchListener; private OnMapTouchListener touchListener;
public NIMapView(Context context, AttributeSet attrs) { public NIMapView(Context context, AttributeSet attrs) {
this(context, attrs, 0); this(context, attrs, 0);
@ -148,8 +218,7 @@ public final class NIMapView extends RelativeLayout {
// map = new NIMap(this); // map = new NIMap(this);
compassImage = rootView.findViewById(R.id.navinfo_map_compass); compassImage = rootView.findViewById(R.id.navinfo_map_compass);
initMapGroup(); // 初始化图层组 initMapGroup(); // 初始化图层组
// mLayerManager = new NILayerManager(context, getVtmMap());
mLayerManager = new NILayerManager(context, getVtmMap());
logoImage = rootView.findViewById(R.id.navinfo_map_logo); logoImage = rootView.findViewById(R.id.navinfo_map_logo);
mRotateAnimation = new NIRotateAnimation(compassImage); mRotateAnimation = new NIRotateAnimation(compassImage);
@ -183,11 +252,11 @@ public final class NIMapView extends RelativeLayout {
NaviMapScaleBar naviMapScaleBar = new NaviMapScaleBar(getVtmMap()); NaviMapScaleBar naviMapScaleBar = new NaviMapScaleBar(getVtmMap());
naviMapScaleBar.initScaleBarLayer(GLViewport.Position.BOTTOM_LEFT, 25, 60); naviMapScaleBar.initScaleBarLayer(GLViewport.Position.BOTTOM_LEFT, 25, 60);
if (gridLayer == null) { // if (gridLayer == null) {
gridLayer = new TileGridLayer(getVtmMap()); // gridLayer = new TileGridLayer(getVtmMap());
getVtmMap().layers().add(gridLayer, LAYER_GROUPS.ALLWAYS_SHOW_GROUP.groupIndex); // getVtmMap().layers().add(gridLayer, LAYER_GROUPS.NAVIGATION.groupIndex);
gridLayer.setEnabled(false); //// gridLayer.setEnabled(true);
} // }
compassImage.setOnClickListener(new OnClickListener() { compassImage.setOnClickListener(new OnClickListener() {
@Override @Override
@ -229,9 +298,53 @@ public final class NIMapView extends RelativeLayout {
}); });
zoomLayout = rootView.findViewById(R.id.navinfo_map_zoom_layer); zoomLayout = rootView.findViewById(R.id.navinfo_map_zoom_layer);
initMap(); switchTileVectorLayerTheme(MAP_THEME.DEFAULT);
} }
/**
* 切换 矢量图层 style
*/
public void switchTileVectorLayerTheme(MAP_THEME styleId) {
// 如果不包含vectorlayer则设置theme无效
boolean bHis = false;
for (Layer layer : getVtmMap().layers()) {
if (layer instanceof VectorTileLayer) {
bHis = true;
break;
}
}
if (!bHis) {
updateMap(true);
return;
}
if (styleId == null) {
getVtmMap().setTheme(new AssetsRenderTheme(mContext.getAssets(), "", "navdefault.xml"), true);
} else {
switch (styleId) {
case NEWTRON:
getVtmMap().setTheme(VtmThemes.NEWTRON, true);
break;
case OSMAGRAY:
getVtmMap().setTheme(VtmThemes.OSMAGRAY, true);
break;
case OSMARENDER:
getVtmMap().setTheme(VtmThemes.OSMARENDER, true);
break;
case TRONRENDER:
getVtmMap().setTheme(VtmThemes.TRONRENDER, true);
break;
default:
getVtmMap().setTheme(new AssetsRenderTheme(mContext.getAssets(), "", "editormarker.xml"), true);
break;
}
}
updateMap();
}
/** /**
* 地图初始化参数 * 地图初始化参数
*/ */
@ -250,197 +363,177 @@ public final class NIMapView extends RelativeLayout {
} }
/** // /**
* 初始化地图 // * 增加作业渲染
*/ // */
private void initMap() { // LabelLayer labelLayer;
switchBaseMapType(BASE_MAP_TYPE.CYCLE_MAP); // /**
switchTileVectorLayerTheme(MAP_THEME.DEFAULT); // * 作业数据图层
initVectorTileLayer(); // */
initMapLifeSource(); // VectorTileLayer vectorTileLayer;
} // /**
// * 作业数据渲染图层
// */
// MapLifeDBTileSource mapLifeDBTileSource;
// /**
// * 轨迹渲染图层
// */
// MapLifeNiLocationTileSource mapLifeNiLocationTileSource;
// /**
// * 轨迹数据图层
// */
// VectorTileLayer vectorNiLocationTileLayer;
// /**
// * 增加作业渲染
// */
// LabelLayer labelNiLocationLayer;
// public void initMapLifeSource() {
// mapLifeDBTileSource = new MapLifeDBTileSource(this.mContext, Constant.ROOT_PATH + "/coremap.db");
// mapLifeNiLocationTileSource = new MapLifeNiLocationTileSource(this.mContext, Constant.ROOT_PATH + "/coremap.db");
// vectorTileLayer = new VectorTileLayer(mapView.map(), mapLifeDBTileSource);
// vectorNiLocationTileLayer = new VectorTileLayer(mapView.map(), mapLifeNiLocationTileSource);
// mapView.map().layers().add(vectorNiLocationTileLayer, LAYER_GROUPS.VECTOR_TILE.groupIndex);
// mapView.map().layers().add(vectorTileLayer, LAYER_GROUPS.VECTOR_TILE.groupIndex);
// labelLayer = new LabelLayer(mapView.map(), vectorTileLayer, new LabelTileLoaderHook(), 15);
// mapView.map().layers().add(labelLayer, LAYER_GROUPS.VECTOR_TILE.groupIndex);
// labelNiLocationLayer = new LabelLayer(mapView.map(), vectorNiLocationTileLayer, new LabelTileLoaderHook(), 15);
// mapView.map().layers().add(labelNiLocationLayer, LAYER_GROUPS.VECTOR_TILE.groupIndex);
//
// switchTileVectorLayerTheme(null);
// mapView.map().updateMap(true);
// MapPosition mapPosition = new MapPosition();
// mapPosition.setZoomLevel(18);
// mapPosition.setPosition(40.091692296269144, 116.26712172082546);
// //116.26712172082546 40.091692296269144
// mapView.map().animator().animateTo(mapPosition);
// }
//
// public void dataLayerUpdate() {
// switchTileVectorLayerTheme(null);
// }
/** /**
* 增加作业渲染 * 初始化地图图层分组
*/ */
LabelLayer labelLayer;
/**
* 作业数据图层
*/
VectorTileLayer vectorTileLayer;
/**
* 作业数据渲染图层
*/
MapLifeDBTileSource mapLifeDBTileSource;
/**
* 轨迹渲染图层
*/
MapLifeNiLocationTileSource mapLifeNiLocationTileSource;
/**
* 轨迹数据图层
*/
VectorTileLayer vectorNiLocationTileLayer;
/**
* 增加作业渲染
*/
LabelLayer labelNiLocationLayer;
public void initMapLifeSource() {
mapLifeDBTileSource = new MapLifeDBTileSource(this.mContext, Constant.ROOT_PATH + "/coremap.db");
mapLifeNiLocationTileSource = new MapLifeNiLocationTileSource(this.mContext,Constant.ROOT_PATH + "/coremap.db");
vectorTileLayer = new VectorTileLayer(mapView.map(), mapLifeDBTileSource);
vectorNiLocationTileLayer = new VectorTileLayer(mapView.map(),mapLifeNiLocationTileSource);
mapView.map().layers().add(vectorNiLocationTileLayer,LAYER_GROUPS.VECTOR_TILE.groupIndex);
mapView.map().layers().add(vectorTileLayer,LAYER_GROUPS.VECTOR_TILE.groupIndex);
labelLayer = new LabelLayer(mapView.map(), vectorTileLayer, new LabelTileLoaderHook(), 15);
mapView.map().layers().add(labelLayer,LAYER_GROUPS.VECTOR_TILE.groupIndex);
labelNiLocationLayer = new LabelLayer(mapView.map(), vectorNiLocationTileLayer, new LabelTileLoaderHook(), 15);
mapView.map().layers().add(labelNiLocationLayer,LAYER_GROUPS.VECTOR_TILE.groupIndex);
switchTileVectorLayerTheme(null);
mapView.map().updateMap(true);
MapPosition mapPosition = new MapPosition();
mapPosition.setZoomLevel(18);
mapPosition.setPosition(40.091692296269144, 116.26712172082546);
//116.26712172082546 40.091692296269144
mapView.map().animator().animateTo(mapPosition);
}
public void dataLayerUpdate() {
switchTileVectorLayerTheme(null);
}
private void initMapGroup() { private void initMapGroup() {
for (LAYER_GROUPS groups : LAYER_GROUPS.values()) { for (LAYER_GROUPS groups : LAYER_GROUPS.values()) {
getVtmMap().layers().addGroup(groups.groupIndex); getVtmMap().layers().addGroup(groups.groupIndex);
} }
} }
/**
* 切换基础底图样式
*/
public void switchBaseMapType(BASE_MAP_TYPE type) {
if (baseRasterLayer != null) {
getVtmMap().layers().remove(baseRasterLayer);
baseRasterLayer = null;
getVtmMap().updateMap();
}
baseRasterLayer = mLayerManager.getRasterTileLayer(mContext, type.url, type.tilePath, true);
getVtmMap().layers().add(baseRasterLayer, LAYER_GROUPS.BASE_RASTER.groupIndex);
getVtmMap().updateMap();
}
/** // /**
* 移除基础底图样式 // * 移除基础底图样式
*/ // */
public void removeBaseMap() { // public void removeBaseMap() {
if (baseRasterLayer != null) { // if (baseRasterLayer != null) {
getVtmMap().layers().remove(baseRasterLayer); // getVtmMap().layers().remove(baseRasterLayer);
baseRasterLayer = null; // baseRasterLayer = null;
getVtmMap().updateMap(); // getVtmMap().updateMap();
} // }
} // }
public void initVectorTileLayer(){ // private void initVectorTileLayer() {
if (baseGroupLayer == null) { // if (baseGroupLayer == null) {
baseGroupLayer = new GroupLayer(getVtmMap()); // baseGroupLayer = new GroupLayer(getVtmMap());
} // }
for (Layer layer : baseGroupLayer.layers) { // for (Layer layer : baseGroupLayer.layers) {
getVtmMap().layers().remove(layer); // getVtmMap().layers().remove(layer);
} // }
baseGroupLayer.layers.clear(); // baseGroupLayer.layers.clear();
//
// File baseMapFolder = new File(mapFilePath);
// if (!baseMapFolder.exists()) {
// return;
// }
//
// File[] mapFileList = baseMapFolder.listFiles();
//
// if (mapFileList != null && mapFileList.length > 0) {
//
// MultiMapFileTileSource multiMapFileTileSource = new MultiMapFileTileSource();
//
// for (File mapFile : mapFileList) {
//
// if (!mapFile.exists() || !mapFile.getName().endsWith(".map")) {
// continue;
// }
//
// MapFileTileSource mTileSource = new MapFileTileSource();
//
// mTileSource.setPreferredLanguage("zh");
//
// if (mTileSource.setMapFile(mapFile.getAbsolutePath())) {
// multiMapFileTileSource.add(mTileSource);
// }
//
// }
//
// VectorTileLayer baseMapLayer = new OsmTileLayer(getVtmMap());
// baseMapLayer.setTileSource(multiMapFileTileSource);
//
// baseGroupLayer.layers.add(baseMapLayer);
//
// if (getTheme(null) != null)
// baseMapLayer.setTheme(getTheme(null));
//
// baseGroupLayer.layers.add(new BuildingLayer(getVtmMap(), baseMapLayer));
// baseGroupLayer.layers.add(new LabelLayer(getVtmMap(), baseMapLayer));
//
// for (Layer layer : baseGroupLayer.layers) {
// if (layer instanceof LabelLayer) {
// getVtmMap().layers().add(layer, LAYER_GROUPS.VECTOR.groupIndex);
// } else {
// getVtmMap().layers().add(layer, LAYER_GROUPS.BASE_VECTOR.groupIndex);
// }
// }
// }
// }
File baseMapFolder = new File(mapFilePath); // //获取渲染资源
if (!baseMapFolder.exists()) { // public IRenderTheme getTheme(final String styleId) {
return; // AssetsRenderTheme theme = new AssetsRenderTheme(mContext.getAssets(), null, "default.xml");
} // if (styleId == null || "".equals(styleId.trim())) {
// switch (2) {
// case 0:
// theme = new AssetsRenderTheme(mContext.getAssets(), null, "default.xml");
// break;
// case 1:
// theme = new AssetsRenderTheme(mContext.getAssets(), null, "osmarender.xml");
// break;
// case 2:
// theme = new AssetsRenderTheme(mContext.getAssets(), null, "tronrender.xml");
// break;
// }
//
// }
//
// return ThemeLoader.load(theme);
// }
File[] mapFileList = baseMapFolder.listFiles(); // public void addDefaultVectorTileLayer(MAP_THEME theme) {
// if (defaultVectorTileLayer != null) {
// getVtmMap().layers().remove(defaultVectorTileLayer);
// defaultVectorTileLayer = null;
// getVtmMap().updateMap();
// }
// defaultVectorTileLayer = mLayerManager.getDefaultVectorLayer(true);
// getVtmMap().layers().add(defaultVectorTileLayer, LAYER_GROUPS.VECTOR_TILE.groupIndex);
// defaultVectorLabelLayer = new LabelLayer(getVtmMap(), (VectorTileLayer) defaultVectorTileLayer);
// getVtmMap().layers().add(defaultVectorLabelLayer, LAYER_GROUPS.VECTOR_TILE.groupIndex);
// if (theme != null) {
//// switchTileVectorLayerTheme(theme);
// }
// getVtmMap().updateMap();
// }
if (mapFileList != null && mapFileList.length > 0) { // public void setBaseRasterVisiable(boolean visiable) {
// if (baseRasterLayer != null) {
MultiMapFileTileSource multiMapFileTileSource = new MultiMapFileTileSource(); // baseRasterLayer.setEnabled(visiable);
// getVtmMap().updateMap();
for (File mapFile : mapFileList) { // }
// }
if (!mapFile.exists() || !mapFile.getName().endsWith(".map")) {
continue;
}
MapFileTileSource mTileSource = new MapFileTileSource();
mTileSource.setPreferredLanguage("zh");
if (mTileSource.setMapFile(mapFile.getAbsolutePath())) {
multiMapFileTileSource.add(mTileSource);
}
}
VectorTileLayer baseMapLayer = new OsmTileLayer(getVtmMap());
baseMapLayer.setTileSource(multiMapFileTileSource);
baseGroupLayer.layers.add(baseMapLayer);
if (getTheme(null) != null)
baseMapLayer.setTheme(getTheme(null));
baseGroupLayer.layers.add(new BuildingLayer(getVtmMap(), baseMapLayer));
baseGroupLayer.layers.add(new LabelLayer(getVtmMap(), baseMapLayer));
for (Layer layer : baseGroupLayer.layers) {
if (layer instanceof LabelLayer) {
getVtmMap().layers().add(layer, LAYER_GROUPS.VECTOR.groupIndex);
} else {
getVtmMap().layers().add(layer, LAYER_GROUPS.BASE_VECTOR.groupIndex);
}
}
}
}
//获取渲染资源
public IRenderTheme getTheme(final String styleId) {
AssetsRenderTheme theme = new AssetsRenderTheme(mContext.getAssets(), null, "default.xml");
if (styleId == null || "".equals(styleId.trim())) {
switch (2) {
case 0:
theme = new AssetsRenderTheme(mContext.getAssets(), null, "default.xml");
break;
case 1:
theme = new AssetsRenderTheme(mContext.getAssets(), null, "osmarender.xml");
break;
case 2:
theme = new AssetsRenderTheme(mContext.getAssets(), null, "tronrender.xml");
break;
}
}
return ThemeLoader.load(theme);
}
public void addDefaultVectorTileLayer(MAP_THEME theme) {
if (defaultVectorTileLayer != null) {
getVtmMap().layers().remove(defaultVectorTileLayer);
defaultVectorTileLayer = null;
getVtmMap().updateMap();
}
defaultVectorTileLayer = mLayerManager.getDefaultVectorLayer(true);
getVtmMap().layers().add(defaultVectorTileLayer, LAYER_GROUPS.VECTOR_TILE.groupIndex);
defaultVectorLabelLayer = new LabelLayer(getVtmMap(), (VectorTileLayer) defaultVectorTileLayer);
getVtmMap().layers().add(defaultVectorLabelLayer, LAYER_GROUPS.VECTOR_TILE.groupIndex);
if (theme != null) {
switchTileVectorLayerTheme(theme);
}
getVtmMap().updateMap();
}
public void setBaseRasterVisiable(boolean visiable) {
if (baseRasterLayer != null) {
baseRasterLayer.setEnabled(visiable);
getVtmMap().updateMap();
}
}
/** /**
* 基础 * 基础
@ -473,24 +566,26 @@ public final class NIMapView extends RelativeLayout {
} }
} }
/** // /**
* 网格图层是否显示 // * 网格图层是否显示
*/ // */
public void setGridLayerVisiable(boolean visiable) { // public void setGridLayerVisiable(boolean visiable) {
if (gridLayer != null) { // if (gridLayer != null) {
gridLayer.setEnabled(visiable); // gridLayer.setEnabled(visiable);
getVtmMap().updateMap(); // updateMap();
} // }
} // }
/** /**
* 图层组定义 * 图层组定义
*/ */
public enum LAYER_GROUPS { public enum LAYER_GROUPS {
BASE_RASTER(0)/*栅格底图*/, BASE_VECTOR(1)/*矢量底图*/, BASE(0)/*底图图层组*/,
RASTER_TILE(2)/*栅格网格*/, VECTOR_TILE(3)/*矢量网格*/, VECTOR_TILE(1)/*矢量瓦片组*/,
VECTOR(4)/*矢量图层组*/, OTHER(5)/*其他图层*/, VECTOR(2)/*高亮组*/,
ALLWAYS_SHOW_GROUP(6), OPERATE(7)/*操作图层组*/; OPERATE(3)/*操作图层组*/,
NAVIGATION(4)/*定位导航组*/;
int groupIndex; int groupIndex;
LAYER_GROUPS(int groupIndex) { LAYER_GROUPS(int groupIndex) {
@ -552,7 +647,7 @@ public final class NIMapView extends RelativeLayout {
* @param bundle * @param bundle
*/ */
public void onSaveInstanceState(Bundle bundle) { public void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState();
} }
@ -560,11 +655,11 @@ public final class NIMapView extends RelativeLayout {
* 当Activity销毁时调用地图的销毁 * 当Activity销毁时调用地图的销毁
*/ */
public void onDestroy() { public void onDestroy() {
try{ try {
if (mapView != null) { if (mapView != null) {
mapView.onDestroy(); mapView.onDestroy();
} }
}catch (Exception e){ } catch (Exception e) {
} }
} }
@ -627,9 +722,9 @@ public final class NIMapView extends RelativeLayout {
public void zoomIn(View view) { public void zoomIn(View view) {
if (view != null) { if (view != null) {
if (view.isEnabled()) { if (view.isEnabled()) {
MapPosition mapPosition = mapView.map().getMapPosition(); MapPosition mapPosition = getVtmMap().getMapPosition();
mapPosition.setZoom(mapPosition.getZoom() + 1); mapPosition.setZoom(mapPosition.getZoom() + 1);
mapView.map().animator().animateTo(mapPosition); getVtmMap().animator().animateTo(mapPosition);
// map.zoomIn(true); // map.zoomIn(true);
} }
view.setEnabled(false); view.setEnabled(false);
@ -648,9 +743,9 @@ public final class NIMapView extends RelativeLayout {
public void zoomOut(View view) { public void zoomOut(View view) {
if (view != null) { if (view != null) {
if (view.isEnabled()) { if (view.isEnabled()) {
MapPosition mapPosition = mapView.map().getMapPosition(); MapPosition mapPosition = getVtmMap().getMapPosition();
mapPosition.setZoom(mapPosition.getZoom() - 1); mapPosition.setZoom(mapPosition.getZoom() - 1);
mapView.map().animator().animateTo(mapPosition); getVtmMap().animator().animateTo(mapPosition);
// map.zoomOut(true); // map.zoomOut(true);
} }
@ -809,47 +904,9 @@ public final class NIMapView extends RelativeLayout {
} }
} }
public void switchTileVectorLayerTheme(MAP_THEME styleId) { // public NILayerManager getLayerManager() {
// 如果不包含vectorlayer则设置theme无效 // return mLayerManager;
boolean bHis = false; // }
for (Layer layer : getVtmMap().layers()) {
if (layer instanceof VectorTileLayer) {
bHis = true;
break;
}
}
if (!bHis) {
getVtmMap().updateMap(true);
return;
}
if (styleId == null) {
getVtmMap().setTheme(new AssetsRenderTheme(mContext.getAssets(), "", "navdefault.xml"), true);
} else {
switch (styleId) {
case NEWTRON:
getVtmMap().setTheme(VtmThemes.NEWTRON, true);
break;
case OSMAGRAY:
getVtmMap().setTheme(VtmThemes.OSMAGRAY, true);
break;
case OSMARENDER:
getVtmMap().setTheme(VtmThemes.OSMARENDER, true);
break;
case TRONRENDER:
getVtmMap().setTheme(VtmThemes.TRONRENDER, true);
break;
default:
getVtmMap().setTheme(new AssetsRenderTheme(mContext.getAssets(), "", "editormarker.xml"), true);
break;
}
}
getVtmMap().updateMap();
}
public NILayerManager getLayerManager() {
return mLayerManager;
}
// 地图点击事件对应的图层 // 地图点击事件对应的图层
private class MapEventsReceiver extends Layer implements GestureListener { private class MapEventsReceiver extends Layer implements GestureListener {
@ -874,7 +931,7 @@ public final class NIMapView extends RelativeLayout {
mapLongClickListener.onMapLongClick(geoPoint); mapLongClickListener.onMapLongClick(geoPoint);
} }
} }
setOnMapClickListener(new NIMap.OnMapClickListener() { setOnMapClickListener(new OnMapClickListener() {
@Override @Override
public void onMapClick(GeoPoint point) { public void onMapClick(GeoPoint point) {
@ -892,7 +949,7 @@ public final class NIMapView extends RelativeLayout {
/** /**
* 设置地图的点击事件 * 设置地图的点击事件
*/ */
public void setOnMapClickListener(@Nullable NIMap.OnMapClickListener listener) { public void setOnMapClickListener(@Nullable OnMapClickListener listener) {
this.mapClickListener = listener; this.mapClickListener = listener;
} }
@ -900,7 +957,7 @@ public final class NIMapView extends RelativeLayout {
* 设置地图的双击事件 * 设置地图的双击事件
* 默认情况下双击会自动放大地图 * 默认情况下双击会自动放大地图
*/ */
public void setOnMapDoubleClickListener(@Nullable NIMap.OnMapDoubleClickListener listener) { public void setOnMapDoubleClickListener(@Nullable OnMapDoubleClickListener listener) {
this.mapDoubleClickListener = listener; this.mapDoubleClickListener = listener;
} }
@ -909,7 +966,7 @@ public final class NIMapView extends RelativeLayout {
* *
* @param listener * @param listener
*/ */
public void setOnMapLongClickListener(@Nullable NIMap.OnMapLongClickListener listener) { public void setOnMapLongClickListener(@Nullable OnMapLongClickListener listener) {
this.mapLongClickListener = listener; this.mapLongClickListener = listener;
} }
@ -918,7 +975,21 @@ public final class NIMapView extends RelativeLayout {
* *
* @param listener * @param listener
*/ */
public void setOnMapTouchListener(@Nullable NIMap.OnMapTouchListener listener) { public void setOnMapTouchListener(@Nullable OnMapTouchListener listener) {
this.touchListener = listener; this.touchListener = listener;
} }
/**
* 刷新地图
*/
public void updateMap() {
mapView.map().updateMap();
}
/**
* 刷新地图
*/
public void updateMap(boolean redraw) {
mapView.map().updateMap(redraw);
}
} }

View File

@ -2,8 +2,21 @@ package com.navinfo.collect.library.map.handler
import android.content.Context import android.content.Context
import com.navinfo.collect.library.map.NIMapView import com.navinfo.collect.library.map.NIMapView
import org.oscim.layers.Layer
open class BaseHandler(context:Context, mapView: NIMapView) { abstract class BaseHandler(context: Context, mapView: NIMapView) {
protected val mContext:Context = context protected val mContext: Context = context
protected val mMapView: NIMapView = mapView protected val mMapView: NIMapView = mapView
fun addLayer(layer: Layer, groupType: NIMapView.LAYER_GROUPS) {
mMapView.vtmMap.layers().add(
layer,
groupType.groupIndex
)
}
fun removeLayer(layer: Layer) {
mMapView.vtmMap.layers().remove(layer)
}
} }

View File

@ -1,35 +1,105 @@
package com.navinfo.collect.library.map.handler package com.navinfo.collect.library.map.handler
import android.content.Context import android.content.Context
import android.os.Environment
import com.navinfo.collect.library.map.NIMapView import com.navinfo.collect.library.map.NIMapView
import com.navinfo.collect.library.map.NIMapView.LAYER_GROUPS import com.navinfo.collect.library.map.NIMapView.LAYER_GROUPS
import com.navinfo.collect.library.map.source.NavinfoMapRastorTileSource
import okhttp3.Cache
import okhttp3.OkHttpClient
import org.oscim.layers.Layer import org.oscim.layers.Layer
import org.oscim.layers.LocationLayer
import org.oscim.layers.tile.bitmap.BitmapTileLayer
import org.oscim.tiling.source.OkHttpEngine.OkHttpFactory
import java.io.File
/** /**
* Layer 操作 * Layer 操作
*/ */
open class LayerManagerHandler(context: Context, mapView: NIMapView) : class LayerManagerHandler(context: Context, mapView: NIMapView) :
BaseHandler(context, mapView) { BaseHandler(context, mapView) {
lateinit var mLocationLayer: LocationLayer
private var baseRasterLayer: Layer? = null
//增加RasterTileLayer init {
fun switchRasterTileLayer( initMap()
url: String?, }
filePath: String? = "",
cache: Boolean? = false, /**
): Boolean { * 初始化地图
mMapView.removeBaseMap() */
val layer: Layer = private fun initMap() {
mMapView.layerManager.getRasterTileLayer(mContext, url, filePath, cache!!) switchBaseMapType(BASE_MAP_TYPE.CYCLE_MAP)
if (layer != null) {
mMapView.vtmMap.layers().add(layer, LAYER_GROUPS.BASE_RASTER.groupIndex) // initVectorTileLayer()
mMapView.vtmMap.clearMap() // initMapLifeSource()
return true }
/**
* 切换基础底图样式
*/
fun switchBaseMapType(type: BASE_MAP_TYPE) {
if (baseRasterLayer != null) {
mMapView.vtmMap.layers().remove(baseRasterLayer)
baseRasterLayer = null
mMapView.vtmMap.updateMap()
} }
return false baseRasterLayer = getRasterTileLayer(type.url, type.tilePath, true)
addLayer(baseRasterLayer!!, LAYER_GROUPS.BASE)
mMapView.updateMap()
} }
//删除RasterTileLayer private fun getRasterTileLayer(
fun removeRasterTileLayer(url: String) { url: String?,
tilePath: String?,
useCache: Boolean
): Layer {
val builder = OkHttpClient.Builder()
val mTileSource =
NavinfoMapRastorTileSource.builder(url).tilePath(tilePath)
.httpFactory(OkHttpFactory(builder)).build()
// 如果使用缓存
if (useCache) {
val cacheDirectory: File =
File(Environment.getExternalStorageState() + "/" + "lalalal", "tiles-raster")
val cacheSize = 300 * 1024 * 1024 // 300 MB
val cache = Cache(cacheDirectory, cacheSize.toLong())
builder.cache(cache)
}
// mTileSource.setHttpEngine(new OkHttpEngine.OkHttpFactory(builder));
// mTileSource.setHttpRequestHeaders(Collections.singletonMap("User-Agent", "vtm-android-example"));
// mTileSource.setCache(new TileCache(mContext, defaultDir, url.substring(url.indexOf(":")+1)));
return BitmapTileLayer(mMapView.vtmMap, mTileSource)
} }
}
/**
* 基础
*/
enum class BASE_MAP_TYPE(// TransportMap底图
var title: String, var url: String, var tilePath: String
) {
OPEN_STREET_MAP(
"Open Street Map",
"http://a.tile.openstreetmap.org",
"/{Z}}/{X}/{Y}.png"
), // openStreetMap底图
CYCLE_MAP(
"Cycle Map",
"http://c.tile.opencyclemap.org/cycle",
"/{Z}}/{X}/{Y}.png"
), // cyclemap底图
S_MAP(
"SMap",
"http://smap.navinfo.com/gateway/smap-raster-map/raster/basemap/tile",
"z={Z}&x={X}&y={Y}"
), // cyclemap底图
TRANSPORT_MAP(
"Transport Map",
"http://b.tile2.opencyclemap.org/transport",
"/{Z}}/{X}/{Y}.png"
);
} }

View File

@ -84,22 +84,10 @@ open class LineHandler(context: Context, mapView: NIMapView) :
.build() .build()
mPathLayer = PathLayer(mMapView.vtmMap, lineStyle) mPathLayer = PathLayer(mMapView.vtmMap, lineStyle)
mMapView.layerManager.addLayer( // addLayer(mPathLayer, NIMapView.LAYER_GROUPS.OPERATE)
"defaultLineLayer",
mPathLayer,
NIMapView.LAYER_GROUPS.VECTOR.ordinal
)
mPathLayerTemp = if (mMapView.layerManager.containsLayer("guideLineLayer")) { mPathLayerTemp = PathLayer(mMapView.vtmMap, newTempStyle)
mMapView.layerManager.getLayer("guideLineLayer") as PathLayer // addLayer(mPathLayerTemp, NIMapView.LAYER_GROUPS.OPERATE)
} else {
PathLayer(mMapView.vtmMap, newTempStyle)
}
mMapView.layerManager.addLayer(
"guideLineLayer",
mPathLayerTemp,
NIMapView.LAYER_GROUPS.VECTOR.ordinal
)
mPathMarkerBitmap = AndroidBitmap( mPathMarkerBitmap = AndroidBitmap(
BitmapFactory.decodeResource( BitmapFactory.decodeResource(
@ -109,21 +97,10 @@ open class LineHandler(context: Context, mapView: NIMapView) :
) )
val markerSymbol = MarkerSymbol(mPathMarkerBitmap, MarkerSymbol.HotspotPlace.CENTER) val markerSymbol = MarkerSymbol(mPathMarkerBitmap, MarkerSymbol.HotspotPlace.CENTER)
//新增marker图层 //新增marker图层
mEndpointLayer = if (mMapView.layerManager.containsLayer("endpointLayer")) { mEndpointLayer = ItemizedLayer(
mMapView.layerManager.getLayer("endpointLayer") as ItemizedLayer mMapView.vtmMap, ArrayList<MarkerInterface>(), markerSymbol, null
} else
//新增marker图层
ItemizedLayer(
mMapView.vtmMap,
java.util.ArrayList<MarkerInterface>(),
markerSymbol,
null
)
mMapView.layerManager.addLayer(
"endpointLayer",
mEndpointLayer,
NIMapView.LAYER_GROUPS.VECTOR.ordinal
) )
// addLayer(mEndpointLayer, NIMapView.LAYER_GROUPS.OPERATE)
mEndpointLayer.setOnItemGestureListener(object : OnItemGestureListener<MarkerInterface> { mEndpointLayer.setOnItemGestureListener(object : OnItemGestureListener<MarkerInterface> {
override fun onItemSingleTapUp(index: Int, item: MarkerInterface): Boolean { override fun onItemSingleTapUp(index: Int, item: MarkerInterface): Boolean {
if (bDrawLine) { if (bDrawLine) {
@ -283,7 +260,7 @@ open class LineHandler(context: Context, mapView: NIMapView) :
} }
fun addDrawLine(list: List<GeoPoint>) { fun addDrawLine(list: List<GeoPoint>) {
for(item in list){ for (item in list) {
addDrawLinePoint(item) addDrawLinePoint(item)
} }
} }

View File

@ -1,23 +1,152 @@
package com.navinfo.collect.library.map.handler package com.navinfo.collect.library.map.handler
import android.content.Context import android.content.Context
import com.navinfo.collect.library.map.NILocation import android.util.Log
import android.widget.Toast
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.location.LocationClientOption.LocationMode
import com.navinfo.collect.library.map.NIMapView import com.navinfo.collect.library.map.NIMapView
import org.oscim.layers.LocationLayer
open class LocationLayerHandler(context: Context, mapView:NIMapView) :
class LocationLayerHandler(context: Context, mapView: NIMapView) :
BaseHandler(context, mapView) { BaseHandler(context, mapView) {
private var mCurrentLocation: NILocation? = null private var mCurrentLocation: BDLocation? = null
private var bFirst = true
private val mLocationLayer: LocationLayer = LocationLayer(mMapView.vtmMap)
private lateinit var locationClient: LocationClient
init {
///添加定位图层到地图,[NIMapView.LAYER_GROUPS.NAVIGATION] 是最上层layer组
addLayer(mLocationLayer, NIMapView.LAYER_GROUPS.NAVIGATION)
//初始化定位
initLocationOption()
}
/** /**
* 设置当前位置信息 * 初始化定位参数配置
*/ */
fun setCurrentLocation(location: NILocation) { private fun initLocationOption() {
this.mCurrentLocation = location try {
mMapView.layerManager.locationLayer.setPosition(
location.latitude, LocationClient.setAgreePrivacy(true)
location.longitude, locationClient = LocationClient(mContext.applicationContext)
location.radius //定位服务的客户端。宿主程序在客户端声明此类,并调用,目前只支持在主线程中启动
) //声明LocationClient类实例并配置定位参数
val locationOption = LocationClientOption()
val myLocationListener = MyLocationListener {
//此处的BDLocation为定位结果信息类通过它的各种get方法可获取定位相关的全部结果
//以下只列举部分获取经纬度相关(常用)的结果信息
//更多结果信息获取说明请参照类参考中BDLocation类中的说明
//获取纬度信息
val latitude = it.latitude
//获取经度信息
val longitude = it.longitude
//获取定位精度默认值为0.0f
val radius = it.radius
//获取经纬度坐标类型以LocationClientOption中设置过的坐标类型为准
val coorType = it.coorType
//获取定位类型、定位错误返回码具体信息可参照类参考中BDLocation类中的说明
val errorCode = it.locType
mCurrentLocation = it
mLocationLayer.setPosition(
it.latitude,
it.longitude,
it.radius
)
//第一次定位成功显示当前位置
if (this.bFirst) {
animateToCurrentPosition()
}
}
//注册监听函数
locationClient.registerLocationListener(myLocationListener)
//可选,默认高精度,设置定位模式,高精度,低功耗,仅设备
locationOption.locationMode = LocationMode.Hight_Accuracy
//可选默认gcj02设置返回的定位结果坐标系如果配合百度地图使用建议设置为bd09ll;
locationOption.setCoorType("gcj02")
//可选默认0即仅定位一次设置发起连续定位请求的间隔需要大于等于1000ms才是有效的
locationOption.setScanSpan(1000)
//可选,设置是否需要地址信息,默认不需要
locationOption.setIsNeedAddress(false)
//可选,设置是否需要地址描述
locationOption.setIsNeedLocationDescribe(false)
//可选,设置是否需要设备方向结果
locationOption.setNeedDeviceDirect(true)
//可选默认false设置是否当Gnss有效时按照1S1次频率输出Gnss结果
locationOption.isLocationNotify = true
//可选默认true定位SDK内部是一个SERVICE并放到了独立进程设置是否在stop的时候杀死这个进程默认不杀死
locationOption.setIgnoreKillProcess(true)
//可选默认false设置是否需要位置语义化结果可以在BDLocation.getLocationDescribe里得到结果类似于“在北京天安门附近”
locationOption.setIsNeedLocationDescribe(false)
//可选默认false设置是否需要POI结果可以在BDLocation.getPoiList里得到
locationOption.setIsNeedLocationPoiList(false)
//可选默认false设置是否收集CRASH信息默认收集
locationOption.SetIgnoreCacheException(false)
//可选默认false设置是否开启卫星定位
locationOption.isOpenGnss = true
//可选默认false设置定位时是否需要海拔信息默认不需要除基础定位版本都可用
locationOption.setIsNeedAltitude(true)
//设置打开自动回调位置模式该开关打开后期间只要定位SDK检测到位置变化就会主动回调给开发者该模式下开发者无需再关心定位间隔是多少定位SDK本身发现位置变化就会及时回调给开发者
// locationOption.setOpenAutoNotifyMode()
//设置打开自动回调位置模式该开关打开后期间只要定位SDK检测到位置变化就会主动回调给开发者
locationOption.setOpenAutoNotifyMode(
1000,
1,
LocationClientOption.LOC_SENSITIVITY_HIGHT
)
//需将配置好的LocationClientOption对象通过setLocOption方法传递给LocationClient对象使用
locationClient.locOption = locationOption
} catch (e: Throwable) {
Toast.makeText(mContext, "定位初始化失败 $e", Toast.LENGTH_SHORT)
}
}
/**
* 开启定位
*/
fun startLocation() {
//开始定位
if (!locationClient.isStarted) {
locationClient.start()
}
}
/**
* 停止定位
*/
fun stopLocation() {
if (locationClient.isStarted) {
locationClient.stop()
}
}
/**
* 回到当前位置
*/
fun animateToCurrentPosition()
{
mCurrentLocation?.run {
val mapPosition = mMapView.vtmMap.mapPosition;
mapPosition.setPosition(this.latitude, this.longitude);
mMapView.vtmMap.animator().animateTo(300, mapPosition);
}
}
}
/**
* 实现定位回调
*/
private class MyLocationListener(callback: (BDLocation) -> Unit) :
BDAbstractLocationListener() {
val call = callback;
override fun onReceiveLocation(location: BDLocation) {
call(location)
} }
} }

View File

@ -1,18 +0,0 @@
package com.navinfo.collect.library.map.handler
import android.content.Context
import com.navinfo.collect.library.map.NIMapView
open class MapBaseControlHandler(context: Context, mapView: NIMapView) :
BaseHandler(context, mapView) {
/**
* 刷新地图
*/
fun upDateMap(redraw: Boolean = true) {
if (redraw) {
mMapView.vtmMap.events.fire(org.oscim.map.Map.CLEAR_EVENT, mMapView.vtmMap.mapPosition)
}
mMapView.vtmMap.updateMap(redraw)
}
}

View File

@ -14,56 +14,56 @@ import org.oscim.layers.marker.MarkerItem
open class MarkHandler(context: Context, mapView:NIMapView) : open class MarkHandler(context: Context, mapView:NIMapView) :
BaseHandler(context, mapView), OnItemGestureListener<MarkerInterface> { BaseHandler(context, mapView), OnItemGestureListener<MarkerInterface> {
//增加marker // //增加marker
fun addMarker( // fun addMarker(
geoPoint: GeoPoint, // geoPoint: GeoPoint,
title: String?, // title: String?,
description: String? = "" // description: String? = ""
): MarkerItem { // ): MarkerItem {
var marker: MarkerItem? = null // var marker: MarkerItem? = null
for (e in mMapView.layerManager.defaultMarkerLayer.itemList) { // for (e in mMapView.layerManager.defaultMarkerLayer.itemList) {
if (e is MarkerItem && e.title == title) { // if (e is MarkerItem && e.title == title) {
marker = e; // marker = e;
break; // break;
} // }
} // }
if (marker == null) { // if (marker == null) {
var tempTitle = title; // var tempTitle = title;
if (tempTitle.isNullOrBlank()) { // if (tempTitle.isNullOrBlank()) {
tempTitle = StringUtil.createUUID(); // tempTitle = StringUtil.createUUID();
} // }
val marker = MarkerItem( // val marker = MarkerItem(
tempTitle, // tempTitle,
description, // description,
geoPoint // geoPoint
) // )
mMapView.layerManager.defaultMarkerLayer.addItem(marker); // mMapView.layerManager.defaultMarkerLayer.addItem(marker);
mMapView.vtmMap.updateMap(true) // mMapView.vtmMap.updateMap(true)
return marker // return marker
} else { // } else {
marker.description = description // marker.description = description
marker.geoPoint = geoPoint // marker.geoPoint = geoPoint
mMapView.layerManager.defaultMarkerLayer.removeItem(marker) // mMapView.layerManager.defaultMarkerLayer.removeItem(marker)
mMapView.layerManager.defaultMarkerLayer.addItem(marker) // mMapView.layerManager.defaultMarkerLayer.addItem(marker)
mMapView.vtmMap.updateMap(true) // mMapView.vtmMap.updateMap(true)
return marker // return marker
} // }
} // }
//
fun removeMarker(title: String) { // fun removeMarker(title: String) {
var marker: MarkerItem? = null // var marker: MarkerItem? = null
for (e in mMapView.layerManager.defaultMarkerLayer.itemList) { // for (e in mMapView.layerManager.defaultMarkerLayer.itemList) {
if (e is MarkerItem && e.title == title) { // if (e is MarkerItem && e.title == title) {
marker = e; // marker = e;
break; // break;
} // }
} // }
if (marker != null) { // if (marker != null) {
mMapView.layerManager.defaultMarkerLayer.removeItem(marker) // mMapView.layerManager.defaultMarkerLayer.removeItem(marker)
mMapView.vtmMap.updateMap(true) // mMapView.vtmMap.updateMap(true)
} // }
} // }
//
override fun onItemSingleTapUp(index: Int, item: MarkerInterface): Boolean { override fun onItemSingleTapUp(index: Int, item: MarkerInterface): Boolean {
return false return false
} }

View File

@ -7,7 +7,6 @@ import android.graphics.Color
import android.text.TextPaint import android.text.TextPaint
import android.widget.Toast import android.widget.Toast
import com.navinfo.collect.library.R import com.navinfo.collect.library.R
import com.navinfo.collect.library.map.NILayerManager
import com.navinfo.collect.library.map.NIMapView import com.navinfo.collect.library.map.NIMapView
import com.navinfo.collect.library.map.handler.BaseHandler import com.navinfo.collect.library.map.handler.BaseHandler
import com.navinfo.collect.library.map.layers.NIPolygonLayer import com.navinfo.collect.library.map.layers.NIPolygonLayer
@ -39,6 +38,7 @@ open class MeasureLayerHandler(context: Context, mapView: NIMapView) :
private val bDrawPoint = false private val bDrawPoint = false
private var mAreaLayer: ItemizedLayer private var mAreaLayer: ItemizedLayer
//绘制线 样式 //绘制线 样式
private val lineStyle: Style private val lineStyle: Style
@ -49,8 +49,10 @@ open class MeasureLayerHandler(context: Context, mapView: NIMapView) :
//新增线数据引线 //新增线数据引线
private var mPathLayerTemp: PathLayer private var mPathLayerTemp: PathLayer
//新增线数据 //新增线数据
private var mPathLayer: PathLayer private var mPathLayer: PathLayer
//线路端点图标 //线路端点图标
private var mPathMarkerBitmap: Bitmap private var mPathMarkerBitmap: Bitmap
@ -67,7 +69,7 @@ open class MeasureLayerHandler(context: Context, mapView: NIMapView) :
.fillColor(context.resources.getColor(R.color.draw_line_blue2_color, null)) .fillColor(context.resources.getColor(R.color.draw_line_blue2_color, null))
.fillAlpha(0.5f) .fillAlpha(0.5f)
.strokeColor(context.resources.getColor(R.color.draw_line_blue2_color, null)) .strokeColor(context.resources.getColor(R.color.draw_line_blue2_color, null))
.fillColor(context.resources.getColor(R.color.draw_line_red_color,null)) .fillColor(context.resources.getColor(R.color.draw_line_red_color, null))
.stippleWidth(4f) .stippleWidth(4f)
.fixed(true) .fixed(true)
.build() .build()
@ -96,22 +98,10 @@ open class MeasureLayerHandler(context: Context, mapView: NIMapView) :
mMapView.vtmMap, mMapView.vtmMap,
lineStyle lineStyle
) )
mMapView.layerManager.addLayer( // addLayer(mPolygonLayer, NIMapView.LAYER_GROUPS.OPERATE)
"meatureLayer",
mPolygonLayer,
NIMapView.LAYER_GROUPS.VECTOR.ordinal
)
mPathLayerTemp = if (mMapView.layerManager.containsLayer("meatureLineLayer")) { mPathLayerTemp = PathLayer(mMapView.vtmMap, newTempStyle)
mMapView.layerManager.getLayer("meatureLineLayer") as PathLayer // addLayer(mPathLayerTemp, NIMapView.LAYER_GROUPS.OPERATE)
} else {
PathLayer(mMapView.vtmMap, newTempStyle)
}
mMapView.layerManager.addLayer(
"meatureLineLayer",
mPathLayerTemp,
NIMapView.LAYER_GROUPS.VECTOR.ordinal
)
mPathMarkerBitmap = AndroidBitmap( mPathMarkerBitmap = AndroidBitmap(
BitmapFactory.decodeResource( BitmapFactory.decodeResource(
@ -126,175 +116,181 @@ open class MeasureLayerHandler(context: Context, mapView: NIMapView) :
mPathLayer = PathLayer(mMapView.vtmMap, lineStyle) mPathLayer = PathLayer(mMapView.vtmMap, lineStyle)
mMapView.vtmMap.layers().add(mPathLayer, NIMapView.LAYER_GROUPS.OTHER.ordinal) addLayer(mPathLayer, NIMapView.LAYER_GROUPS.OPERATE)
} }
open fun drawLineOrPolygon(type: Int) { open fun drawLineOrPolygon(type: Int) {
bDrawLine = true bDrawLine = true
//画面 // //画面
if (type == 3) { // if (type == 3) {
if (mPolygonLayer == null) { // if (mPolygonLayer == null) {
mPolygonLayer = NIPolygonLayer(mMapView.vtmMap, lineStyle) // mPolygonLayer = NIPolygonLayer(mMapView.vtmMap, lineStyle)
mMapView.vtmMap.layers().add(mPolygonLayer, NIMapView.LAYER_GROUPS.OTHER.ordinal) // addLayer(mPolygonLayer, NIMapView.LAYER_GROUPS.OPERATE)
} else if (!mPolygonLayer.isEnabled) { // } else if (!mPolygonLayer.isEnabled) {
mPolygonLayer.isEnabled = true // mPolygonLayer.isEnabled = true
} // }
} else { // } else {
if (mPathLayer == null) { // if (mPathLayer == null) {
mPathLayer = PathLayer(mMapView.vtmMap, lineStyle) // mPathLayer = PathLayer(mMapView.vtmMap, lineStyle)
mMapView.vtmMap.layers().add(mPathLayer, NIMapView.LAYER_GROUPS.OTHER.ordinal) // addLayer(mPathLayer, NIMapView.LAYER_GROUPS.OPERATE)
} else if (!mPathLayer.isEnabled()) { // } else if (!mPathLayer.isEnabled()) {
mPathLayer.setEnabled(true) // mPathLayer.setEnabled(true)
} // }
} // }
//上一个点的引线 // //上一个点的引线
if (mPathLayerTemp == null) { // if (mPathLayerTemp == null) {
mPathLayerTemp = PathLayer(mMapView.vtmMap, newTempStyle) // mPathLayerTemp = PathLayer(mMapView.vtmMap, newTempStyle)
mMapView.vtmMap.layers().add(mPathLayerTemp, NIMapView.LAYER_GROUPS.OTHER.ordinal) // addLayer(mPathLayerTemp, NIMapView.LAYER_GROUPS.OPERATE)
} else if (!mPathLayerTemp.isEnabled) { // } else if (!mPathLayerTemp.isEnabled) {
mPathLayerTemp.isEnabled = true // mPathLayerTemp.isEnabled = true
} // }
val geoPoint: GeoPoint = // val geoPoint: GeoPoint =
GeoPoint(mMapView.vtmMap.getMapPosition().getLatitude(), mMapView.vtmMap.getMapPosition().getLongitude()) // GeoPoint(
// mMapView.vtmMap.getMapPosition().getLatitude(),
//编辑点 // mMapView.vtmMap.getMapPosition().getLongitude()
if (editIndex > -1) { // )
if (mPathMakers.size > editIndex) { //
mMapView.layerManager.removeMarker(mPathMakers[editIndex], NILayerManager.MARQUEE_MARKER_LAYER) // //编辑点
mPathMakers.removeAt(editIndex) // if (editIndex > -1) {
if (mPathMarkerBitmap == null) { // if (mPathMakers.size > editIndex) {
mPathMarkerBitmap = AndroidBitmap( // mMapView.layerManager.removeMarker(
BitmapFactory.decodeResource( // mPathMakers[editIndex],
mContext.getResources(), // NILayerManager.MARQUEE_MARKER_LAYER
R.mipmap.icon_path_maker // )
) // mPathMakers.removeAt(editIndex)
) // if (mPathMarkerBitmap == null) {
} // mPathMarkerBitmap = AndroidBitmap(
val markerItem = MarkerItem(createUUID(), "", "", geoPoint) // BitmapFactory.decodeResource(
val markerSymbol = MarkerSymbol(mPathMarkerBitmap, MarkerSymbol.HotspotPlace.CENTER) // mContext.getResources(),
markerItem.marker = markerSymbol // R.mipmap.icon_path_maker
mMapView.layerManager.addMarker2MarkerLayer( // )
markerItem, // )
mPathMarkerBitmap, // }
NILayerManager.MARQUEE_MARKER_LAYER, // val markerItem = MarkerItem(createUUID(), "", "", geoPoint)
NIMapView.LAYER_GROUPS.OTHER.ordinal, // val markerSymbol = MarkerSymbol(mPathMarkerBitmap, MarkerSymbol.HotspotPlace.CENTER)
itemGestureListener // markerItem.marker = markerSymbol
) // mMapView.layerManager.addMarker2MarkerLayer(
mPathMakers.add(editIndex, markerItem) // markerItem,
if (mPathLayer != null && mPathLayer.getPoints().size > 0) { // mPathMarkerBitmap,
val list: MutableList<GeoPoint> = mPathLayer.getPoints() // NILayerManager.MARQUEE_MARKER_LAYER,
if (editIndex < list.size) { // NIMapView.LAYER_GROUPS.OTHER.ordinal,
list.removeAt(editIndex) // itemGestureListener
val list2: MutableList<GeoPoint> = java.util.ArrayList(list) // )
list2.add(editIndex, geoPoint) // mPathMakers.add(editIndex, markerItem)
mPathLayer.setPoints(list2) // if (mPathLayer != null && mPathLayer.getPoints().size > 0) {
} // val list: MutableList<GeoPoint> = mPathLayer.getPoints()
} else if (mPolygonLayer != null && mPolygonLayer.points.size > 0) { // if (editIndex < list.size) {
val list = mPolygonLayer.points // list.removeAt(editIndex)
if (editIndex < list.size) { // val list2: MutableList<GeoPoint> = java.util.ArrayList(list)
list.removeAt(editIndex) // list2.add(editIndex, geoPoint)
val list2: MutableList<GeoPoint> = java.util.ArrayList(list) // mPathLayer.setPoints(list2)
list2.add(editIndex, geoPoint) // }
mPolygonLayer.setPoints(list2) // } else if (mPolygonLayer != null && mPolygonLayer.points.size > 0) {
} // val list = mPolygonLayer.points
} // if (editIndex < list.size) {
if (mPathLayerTemp != null) { // list.removeAt(editIndex)
mPathLayerTemp.setStyle(newTempStyle) // val list2: MutableList<GeoPoint> = java.util.ArrayList(list)
val list: MutableList<GeoPoint> = java.util.ArrayList<GeoPoint>() // list2.add(editIndex, geoPoint)
if (type == 3 && mPathMakers.size > 1) { // mPolygonLayer.setPoints(list2)
list.add(mPathMakers[0].geoPoint) // }
list.add(geoPoint) // }
list.add(mPathMakers[mPathMakers.size - 1].geoPoint) // if (mPathLayerTemp != null) {
} else { // mPathLayerTemp.setStyle(newTempStyle)
list.add(mPathMakers[mPathMakers.size - 1].geoPoint) // val list: MutableList<GeoPoint> = java.util.ArrayList<GeoPoint>()
list.add(geoPoint) // if (type == 3 && mPathMakers.size > 1) {
} // list.add(mPathMakers[0].geoPoint)
mPathLayerTemp.setPoints(list) // list.add(geoPoint)
} // list.add(mPathMakers[mPathMakers.size - 1].geoPoint)
} // } else {
editIndex = -1 // list.add(mPathMakers[mPathMakers.size - 1].geoPoint)
} else { //新增点 // list.add(geoPoint)
if (type == 3) { // }
val points: MutableList<GeoPoint> = java.util.ArrayList(mPolygonLayer.points) // mPathLayerTemp.setPoints(list)
if (points.size > 2) { // }
val list: MutableList<GeoPoint> = java.util.ArrayList() // }
points.add(points[0]) // editIndex = -1
list.add(points[0]) // } else { //新增点
list.add(geoPoint) // if (type == 3) {
list.add(mPolygonLayer.points[mPolygonLayer.points.size - 1]) // val points: MutableList<GeoPoint> = java.util.ArrayList(mPolygonLayer.points)
val bCross = GeometryTools.isPolygonCrosses(points, list) // if (points.size > 2) {
if (bCross == true) { // val list: MutableList<GeoPoint> = java.util.ArrayList()
Toast.makeText(mContext, "不能交叉", Toast.LENGTH_SHORT).show() // points.add(points[0])
return // list.add(points[0])
} // list.add(geoPoint)
} // list.add(mPolygonLayer.points[mPolygonLayer.points.size - 1])
mPolygonLayer.addPoint(geoPoint) // val bCross = GeometryTools.isPolygonCrosses(points, list)
} else { // if (bCross == true) {
val points: List<GeoPoint> = mPathLayer.getPoints() // Toast.makeText(mContext, "不能交叉", Toast.LENGTH_SHORT).show()
if (points.size > 2) { // return
val list: MutableList<GeoPoint> = java.util.ArrayList() // }
list.add(geoPoint) // }
list.add(points[points.size - 1]) // mPolygonLayer.addPoint(geoPoint)
val bCross = GeometryTools.isLineStringCrosses(points, list) // } else {
if (bCross == true) { // val points: List<GeoPoint> = mPathLayer.getPoints()
Toast.makeText(mContext, "不能交叉", Toast.LENGTH_SHORT).show() // if (points.size > 2) {
return // val list: MutableList<GeoPoint> = java.util.ArrayList()
} // list.add(geoPoint)
} // list.add(points[points.size - 1])
mPathLayer.addPoint(geoPoint) // val bCross = GeometryTools.isLineStringCrosses(points, list)
} // if (bCross == true) {
if (mPathMarkerBitmap == null) { // Toast.makeText(mContext, "不能交叉", Toast.LENGTH_SHORT).show()
mPathMarkerBitmap = AndroidBitmap( // return
BitmapFactory.decodeResource( // }
mContext.getResources(), // }
R.mipmap.icon_path_maker // mPathLayer.addPoint(geoPoint)
) // }
) // if (mPathMarkerBitmap == null) {
} // mPathMarkerBitmap = AndroidBitmap(
val markerItem = MarkerItem(createUUID(), "", "", geoPoint) // BitmapFactory.decodeResource(
val markerSymbol = MarkerSymbol(mPathMarkerBitmap, MarkerSymbol.HotspotPlace.CENTER) // mContext.getResources(),
markerItem.marker = markerSymbol // R.mipmap.icon_path_maker
mMapView.layerManager.addMarker2MarkerLayer( // )
markerItem, // )
mPathMarkerBitmap, // }
NILayerManager.MARQUEE_MARKER_LAYER, // val markerItem = MarkerItem(createUUID(), "", "", geoPoint)
NIMapView.LAYER_GROUPS.OTHER.ordinal, // val markerSymbol = MarkerSymbol(mPathMarkerBitmap, MarkerSymbol.HotspotPlace.CENTER)
itemGestureListener // markerItem.marker = markerSymbol
) // mMapView.layerManager.addMarker2MarkerLayer(
mPathMakers.add(markerItem) // markerItem,
} // mPathMarkerBitmap,
// NILayerManager.MARQUEE_MARKER_LAYER,
// NIMapView.LAYER_GROUPS.OTHER.ordinal,
// itemGestureListener
// )
// mPathMakers.add(markerItem)
// }
showAreaLayer() showAreaLayer()
} }
open fun drawLineBackspace() { open fun drawLineBackspace() {
if (mPathLayer != null && mPathLayer.getPoints().size > 0) { // if (mPathLayer != null && mPathLayer.getPoints().size > 0) {
val list: MutableList<GeoPoint> = java.util.ArrayList<GeoPoint>(mPathLayer.getPoints()) // val list: MutableList<GeoPoint> = java.util.ArrayList<GeoPoint>(mPathLayer.getPoints())
val point = list[mPathLayer.getPoints().size - 1] // val point = list[mPathLayer.getPoints().size - 1]
list.remove(point) // list.remove(point)
mPathLayer.setPoints(list) // mPathLayer.setPoints(list)
mMapView.layerManager.jumpToPosition(point.longitude, point.latitude, 0) // mMapView.layerManager.jumpToPosition(point.longitude, point.latitude, 0)
} else if (mPolygonLayer != null && mPolygonLayer.points.size > 0) { // } else if (mPolygonLayer != null && mPolygonLayer.points.size > 0) {
val list: MutableList<GeoPoint> = java.util.ArrayList<GeoPoint>(mPolygonLayer.points) // val list: MutableList<GeoPoint> = java.util.ArrayList<GeoPoint>(mPolygonLayer.points)
val point = list[mPolygonLayer.points.size - 1] // val point = list[mPolygonLayer.points.size - 1]
list.remove(point) // list.remove(point)
mPolygonLayer.setPoints(list) // mPolygonLayer.setPoints(list)
mMapView.layerManager.jumpToPosition(point!!.longitude, point.latitude, 0) // mMapView.layerManager.jumpToPosition(point!!.longitude, point.latitude, 0)
} // }
if (mPathMakers.size > 0) { // if (mPathMakers.size > 0) {
var item: MarkerItem? = mPathMakers[mPathMakers.size - 1] // var item: MarkerItem? = mPathMakers[mPathMakers.size - 1]
mMapView.layerManager.removeMarker(item, NILayerManager.MARQUEE_MARKER_LAYER) // mMapView.layerManager.removeMarker(item, NILayerManager.MARQUEE_MARKER_LAYER)
mPathMakers.remove(item) // mPathMakers.remove(item)
item = null // item = null
} // }
if (mPathMakers.size == 0 && mPathLayerTemp != null) { // if (mPathMakers.size == 0 && mPathLayerTemp != null) {
mPathLayerTemp.clearPath() // mPathLayerTemp.clearPath()
} // }
editIndex = -1 // editIndex = -1
if (mPathLayerTemp != null) { // if (mPathLayerTemp != null) {
mPathLayerTemp.setStyle(newTempStyle) // mPathLayerTemp.setStyle(newTempStyle)
} // }
} }
@ -322,8 +318,8 @@ open class MeasureLayerHandler(context: Context, mapView: NIMapView) :
val area = DistanceUtil.planarPolygonAreaMeters2(list) val area = DistanceUtil.planarPolygonAreaMeters2(list)
var areaString: String var areaString: String
if (area < 1000000) { if (area < 1000000) {
areaString = area.toString()+"平方米" areaString = area.toString() + "平方米"
} else if (area < 10000000000.0){ } else if (area < 10000000000.0) {
val d = area / 1000000.0 val d = area / 1000000.0
val bg = BigDecimal(d) val bg = BigDecimal(d)
val f1 = bg.setScale(1, BigDecimal.ROUND_HALF_UP).toDouble() val f1 = bg.setScale(1, BigDecimal.ROUND_HALF_UP).toDouble()
@ -364,25 +360,25 @@ open class MeasureLayerHandler(context: Context, mapView: NIMapView) :
} }
open fun removeLine() { open fun removeLine() {
bDrawLine = false // bDrawLine = false
editIndex = -1 // editIndex = -1
for (item in mPathMakers) { // for (item in mPathMakers) {
mMapView.layerManager.removeMarker(item, NILayerManager.MARQUEE_MARKER_LAYER) // mMapView.layerManager.removeMarker(item, NILayerManager.MARQUEE_MARKER_LAYER)
} // }
mPathMakers.clear() // mPathMakers.clear()
if (mPathLayer != null) { // if (mPathLayer != null) {
mPathLayer.clearPath() // mPathLayer.clearPath()
mPathLayer.isEnabled = false // mPathLayer.isEnabled = false
} // }
if (mPolygonLayer != null) { // if (mPolygonLayer != null) {
mPolygonLayer.clearPath() // mPolygonLayer.clearPath()
mPolygonLayer.isEnabled = false // mPolygonLayer.isEnabled = false
} // }
if (mPathLayerTemp != null) { // if (mPathLayerTemp != null) {
mPathLayerTemp.clearPath() // mPathLayerTemp.clearPath()
mPathLayerTemp.isEnabled = false // mPathLayerTemp.isEnabled = false
mPathLayerTemp.setStyle(newTempStyle) // mPathLayerTemp.setStyle(newTempStyle)
} // }
hideAreaLayer() hideAreaLayer()
} }
@ -399,27 +395,31 @@ open class MeasureLayerHandler(context: Context, mapView: NIMapView) :
object : OnItemGestureListener<MarkerInterface> { object : OnItemGestureListener<MarkerInterface> {
override fun onItemSingleTapUp(index: Int, item: MarkerInterface): Boolean { override fun onItemSingleTapUp(index: Int, item: MarkerInterface): Boolean {
if (bDrawLine) { if (bDrawLine) {
for (i in mPathMakers.indices) { // for (i in mPathMakers.indices) {
val item1 = mPathMakers[i] // val item1 = mPathMakers[i]
if (item === item1) { // if (item === item1) {
mMapView.layerManager.jumpToPosition(item.getPoint().longitude, item.getPoint().latitude, 0) // mMapView.layerManager.jumpToPosition(
editIndex = i // item.getPoint().longitude,
if (mPathLayerTemp != null) { // item.getPoint().latitude,
mPathLayerTemp.setStyle(editTempStyle) // 0
val list: MutableList<GeoPoint> = java.util.ArrayList<GeoPoint>() // )
if (editIndex == 0 || editIndex == mPathMakers.size - 1) { // editIndex = i
list.add(item.geoPoint as Nothing) // if (mPathLayerTemp != null) {
list.add(item.geoPoint as Nothing) // mPathLayerTemp.setStyle(editTempStyle)
} else { // val list: MutableList<GeoPoint> = java.util.ArrayList<GeoPoint>()
list.add(mPathMakers[editIndex - 1].geoPoint as Nothing) // if (editIndex == 0 || editIndex == mPathMakers.size - 1) {
list.add(item.geoPoint as Nothing) // list.add(item.geoPoint as Nothing)
list.add(mPathMakers[editIndex + 1].geoPoint as Nothing) // list.add(item.geoPoint as Nothing)
} // } else {
mPathLayerTemp.setPoints(list) // list.add(mPathMakers[editIndex - 1].geoPoint as Nothing)
} // list.add(item.geoPoint as Nothing)
return true // list.add(mPathMakers[editIndex + 1].geoPoint as Nothing)
} // }
} // mPathLayerTemp.setPoints(list)
// }
// return true
// }
// }
} }
return false return false
} }

View File

@ -5,12 +5,10 @@ import android.graphics.BitmapFactory
import android.util.Log import android.util.Log
import android.widget.Toast import android.widget.Toast
import com.navinfo.collect.library.R import com.navinfo.collect.library.R
import com.navinfo.collect.library.map.NILayerManager
import com.navinfo.collect.library.map.NIMapView import com.navinfo.collect.library.map.NIMapView
import com.navinfo.collect.library.map.layers.NIPolygonLayer import com.navinfo.collect.library.map.layers.NIPolygonLayer
import com.navinfo.collect.library.utils.GeometryTools import com.navinfo.collect.library.utils.GeometryTools
import com.navinfo.collect.library.utils.StringUtil import com.navinfo.collect.library.utils.StringUtil
import com.navinfo.collect.library.utils.StringUtil.Companion.createUUID
import org.oscim.android.canvas.AndroidBitmap import org.oscim.android.canvas.AndroidBitmap
import org.oscim.backend.canvas.Bitmap import org.oscim.backend.canvas.Bitmap
import org.oscim.core.GeoPoint import org.oscim.core.GeoPoint
@ -41,13 +39,13 @@ open class PolygonHandler(context: Context, mapView: NIMapView) :
private val editTempStyle: Style private val editTempStyle: Style
//新增线数据引线 //新增线数据引线
private var mPathLayerTemp: PathLayer private lateinit var mPathLayerTemp: PathLayer
//线路端点图标 //线路端点图标
private var mPathMarkerBitmap: Bitmap private var mPathMarkerBitmap: Bitmap
//线路端点marker //线路端点marker
private val mEndpointLayer: ItemizedLayer private lateinit var mEndpointLayer: ItemizedLayer
private var bDrawPolygon = false private var bDrawPolygon = false
@ -92,22 +90,22 @@ open class PolygonHandler(context: Context, mapView: NIMapView) :
mMapView.vtmMap, mMapView.vtmMap,
lineStyle lineStyle
) )
mMapView.layerManager.addLayer( // mMapView.layerManager.addLayer(
"defaultPolygonLayer", // "defaultPolygonLayer",
mPolygonLayer, // mPolygonLayer,
NIMapView.LAYER_GROUPS.VECTOR.ordinal // NIMapView.LAYER_GROUPS.VECTOR.ordinal
) // )
//
mPathLayerTemp = if (mMapView.layerManager.containsLayer("guideLineLayer")) { // mPathLayerTemp = if (mMapView.layerManager.containsLayer("guideLineLayer")) {
mMapView.layerManager.getLayer("guideLineLayer") as PathLayer // mMapView.layerManager.getLayer("guideLineLayer") as PathLayer
} else { // } else {
PathLayer(mMapView.vtmMap, newTempStyle) // PathLayer(mMapView.vtmMap, newTempStyle)
} // }
mMapView.layerManager.addLayer( // mMapView.layerManager.addLayer(
"guideLineLayer", // "guideLineLayer",
mPathLayerTemp, // mPathLayerTemp,
NIMapView.LAYER_GROUPS.VECTOR.ordinal // NIMapView.LAYER_GROUPS.VECTOR.ordinal
) // )
mPathMarkerBitmap = AndroidBitmap( mPathMarkerBitmap = AndroidBitmap(
BitmapFactory.decodeResource( BitmapFactory.decodeResource(
@ -118,57 +116,57 @@ open class PolygonHandler(context: Context, mapView: NIMapView) :
val markerSymbol = MarkerSymbol(mPathMarkerBitmap, MarkerSymbol.HotspotPlace.CENTER) val markerSymbol = MarkerSymbol(mPathMarkerBitmap, MarkerSymbol.HotspotPlace.CENTER)
mEndpointLayer = if (mMapView.layerManager.containsLayer("endpointLayer")) { // mEndpointLayer = if (mMapView.layerManager.containsLayer("endpointLayer")) {
mMapView.layerManager.getLayer("endpointLayer") as ItemizedLayer // mMapView.layerManager.getLayer("endpointLayer") as ItemizedLayer
} else // } else
//新增marker图层 // //新增marker图层
ItemizedLayer( // ItemizedLayer(
mMapView.vtmMap, // mMapView.vtmMap,
java.util.ArrayList<MarkerInterface>(), // java.util.ArrayList<MarkerInterface>(),
markerSymbol, // markerSymbol,
null // null
) // )
mMapView.layerManager.addLayer( // mMapView.layerManager.addLayer(
"endpointLayer", // "endpointLayer",
mEndpointLayer, // mEndpointLayer,
NIMapView.LAYER_GROUPS.VECTOR.ordinal // NIMapView.LAYER_GROUPS.VECTOR.ordinal
) // )
mEndpointLayer.setOnItemGestureListener(object : OnItemGestureListener<MarkerInterface> { // mEndpointLayer.setOnItemGestureListener(object : OnItemGestureListener<MarkerInterface> {
override fun onItemSingleTapUp(index: Int, item: MarkerInterface): Boolean { // override fun onItemSingleTapUp(index: Int, item: MarkerInterface): Boolean {
if (bDrawPolygon) { // if (bDrawPolygon) {
for (i in mPathMakers.indices) { // for (i in mPathMakers.indices) {
val item1 = mPathMakers[i] // val item1 = mPathMakers[i]
if (item === item1) { // if (item === item1) {
mMapView.vtmMap.animator().animateTo( // mMapView.vtmMap.animator().animateTo(
GeoPoint( // GeoPoint(
item.getPoint().latitude, // item.getPoint().latitude,
item.getPoint().longitude // item.getPoint().longitude
) // )
) // )
editIndex = i // editIndex = i
mPathLayerTemp.setStyle(editTempStyle) // mPathLayerTemp.setStyle(editTempStyle)
val list: MutableList<GeoPoint> = mutableListOf() // val list: MutableList<GeoPoint> = mutableListOf()
if (editIndex == 0 || editIndex == mPathMakers.size - 1) { // if (editIndex == 0 || editIndex == mPathMakers.size - 1) {
list.add(item.getPoint()) // list.add(item.getPoint())
list.add(item.getPoint()) // list.add(item.getPoint())
} else { // } else {
list.add(mPathMakers[editIndex - 1].geoPoint) // list.add(mPathMakers[editIndex - 1].geoPoint)
list.add(item.getPoint()) // list.add(item.getPoint())
list.add(mPathMakers[editIndex + 1].geoPoint) // list.add(mPathMakers[editIndex + 1].geoPoint)
} // }
mPathLayerTemp.setPoints(list) // mPathLayerTemp.setPoints(list)
return false // return false
} // }
} // }
} // }
return false // return false
} // }
//
override fun onItemLongPress(index: Int, item: MarkerInterface): Boolean { // override fun onItemLongPress(index: Int, item: MarkerInterface): Boolean {
return false // return false
} // }
}) // })
} }
fun addDrawPolygonPoint(geoPoint: GeoPoint): List<GeoPoint> { fun addDrawPolygonPoint(geoPoint: GeoPoint): List<GeoPoint> {

View File

@ -61,7 +61,7 @@ public class NaviLocationLayer extends LocationTextureLayer {
this.locationRenderer.setColor(0xffa1dbf5); this.locationRenderer.setColor(0xffa1dbf5);
this.locationRenderer.setShowAccuracyZoom(4); this.locationRenderer.setShowAccuracyZoom(4);
this.setEnabled(true); // 默认开启当前位置显示 this.setEnabled(true); // 默认开启当前位置显示
mMap.layers().add(this, NIMapView.LAYER_GROUPS.ALLWAYS_SHOW_GROUP.getGroupIndex()); mMap.layers().add(this, NIMapView.LAYER_GROUPS.NAVIGATION.getGroupIndex());
return this; return this;
} }
} }

View File

@ -73,7 +73,7 @@ public class NaviMapScaleBar extends MapScaleBar {
BitmapRenderer renderer = mapScaleBarLayer.getRenderer(); BitmapRenderer renderer = mapScaleBarLayer.getRenderer();
renderer.setPosition(position); // 设置scaleBar在地图上的位置 renderer.setPosition(position); // 设置scaleBar在地图上的位置
renderer.setOffset(xOffset * CanvasAdapter.getScale(), yOffset* CanvasAdapter.getScale()); renderer.setOffset(xOffset * CanvasAdapter.getScale(), yOffset* CanvasAdapter.getScale());
this.map.layers().add(mapScaleBarLayer, NIMapView.LAYER_GROUPS.ALLWAYS_SHOW_GROUP.ordinal()); this.map.layers().add(mapScaleBarLayer, NIMapView.LAYER_GROUPS.NAVIGATION.ordinal());
return mapScaleBarLayer; return mapScaleBarLayer;
} }

View File

@ -1,5 +1,7 @@
package com.navinfo.collect.library.map.source; package com.navinfo.collect.library.map.source;
import android.util.Log;
import org.oscim.backend.CanvasAdapter; import org.oscim.backend.CanvasAdapter;
import org.oscim.backend.canvas.Bitmap; import org.oscim.backend.canvas.Bitmap;
import org.oscim.core.Tile; import org.oscim.core.Tile;
@ -32,6 +34,7 @@ public class NavinfoMapRastorTileSource extends UrlTileSource {
public static class Builder<T extends Builder<T>> extends UrlTileSource.Builder<T> { public static class Builder<T extends Builder<T>> extends UrlTileSource.Builder<T> {
private boolean isTMSProtocol = true; private boolean isTMSProtocol = true;
public Builder(String url) { public Builder(String url) {
super(url, DEFAULT_PATH); super(url, DEFAULT_PATH);
overZoom(2); overZoom(2);

View File

@ -1,64 +1,70 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"> android:layout_width="match_parent"
android:layout_height="match_parent">
<org.oscim.android.MapView <org.oscim.android.MapView
android:id="@+id/base_map_view" android:id="@+id/base_map_view"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent"></org.oscim.android.MapView> android:layout_height="match_parent" />
<ImageView <ImageView
android:id="@+id/navinfo_map_compass" android:id="@+id/navinfo_map_compass"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:padding="@dimen/nimap_defalut_padding"
android:layout_alignParentTop="true" android:layout_alignParentTop="true"
android:layout_alignParentRight="true" android:layout_alignParentRight="true"
android:layout_marginTop="50dp" android:layout_marginTop="50dp"
android:src="@mipmap/compass"></ImageView> android:padding="@dimen/nimap_defalut_padding"
android:src="@mipmap/compass" />
<ImageView <ImageView
android:id="@+id/navinfo_map_logo" android:id="@+id/navinfo_map_logo"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_alignParentBottom="true" android:layout_alignParentBottom="true"
android:src="@mipmap/logo" android:padding="@dimen/nimap_defalut_padding"
android:padding="@dimen/nimap_defalut_padding"></ImageView> android:src="@mipmap/logo" />
<LinearLayout <LinearLayout
android:id="@+id/navinfo_map_zoom_layer" android:id="@+id/navinfo_map_zoom_layer"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:padding="@dimen/nimap_defalut_padding"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true" android:layout_alignParentRight="true"
android:orientation="vertical"> android:layout_alignParentBottom="true"
android:orientation="vertical"
android:padding="@dimen/nimap_defalut_padding">
<ImageView <ImageView
android:id="@+id/navinfo_map_zoom_in" android:id="@+id/navinfo_map_zoom_in"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:src="@drawable/icon_map_zoom_in" android:background="@drawable/bg_nimap_default_button"
android:clickable="true" android:clickable="true"
android:focusable="true" android:focusable="true"
android:background="@drawable/bg_nimap_default_button"></ImageView> android:src="@drawable/icon_map_zoom_in" />
<Space <Space
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="@dimen/nimap_defalut_padding"></Space> android:layout_height="@dimen/nimap_defalut_padding" />
<ImageView <ImageView
android:id="@+id/navinfo_map_zoom_out" android:id="@+id/navinfo_map_zoom_out"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:src="@drawable/icon_map_zoom_out" android:background="@drawable/bg_nimap_default_button"
android:clickable="true" android:clickable="true"
android:focusable="true" android:focusable="true"
android:background="@drawable/bg_nimap_default_button"></ImageView> android:src="@drawable/icon_map_zoom_out" />
</LinearLayout> </LinearLayout>
<LinearLayout <LinearLayout
android:layout_centerInParent="true"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:visibility="gone" android:layout_centerInParent="true"
android:gravity="center" android:gravity="center"
android:orientation="vertical"> android:orientation="vertical"
android:visibility="gone">
<ImageView <ImageView
android:id="@+id/main_tracking_cross" android:id="@+id/main_tracking_cross"

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<network-security-config xmlns:tools="http://schemas.android.com/tools"
tools:ignore="MissingDefaultResource">
<base-config cleartextTrafficPermitted="true" />
</network-security-config>