当前位置: 首页 > news >正文

安卓 Google Maps 的使用和开发步骤

文章目录

  • 1. main
  • 2. Android 谷歌地图
  • 3. 源码
  • Reference

1. main

在国内选择的SDK可以是高德、百度、腾讯、xxxx等,但在国外,你首选是谷歌,因此要进行Google地图的开发你首先要解决下面三个问题

VPN
Google账号
信用卡American Express(美国运通卡)Discover(美国发现卡)JCB(Japan Credit Bureau,日本国际信用卡)MasterCard(万事达)VISA(维萨)

2. Android 谷歌地图

https://developers.google.cn/maps/documentation/android-sdk?hl=zh-cn

    一、设置Google Cloud 项目二、项目配置① 设置SDK② 配置API密钥③ 配置AndroidManifest.xml三、添加地图四、定位当前① 请求定位权限② 我的位置控件③ 获取当前位置五、配置地图① xml配置地图② 代码配置地图③ 地图点击事件④ 管理Marker六、地址位置编码① 坐标转地址② 地址转坐标七、源码

3. 源码

这里zhi贴上GoogleMapActivity的完整代码:

@SuppressLint("NewApi")
class GoogleMapActivity : AppCompatActivity(), OnMapReadyCallback, Geocoder.GeocodeListener {private lateinit var binding: ActivityGoogleMapBinding// 地图private lateinit var map: GoogleMap// Places API 的入口点。private lateinit var placesClient: PlacesClient// 融合位置信息提供程序的入口点。private lateinit var fusedLocationProviderClient: FusedLocationProviderClient// 最后已知位置private var lastKnownLocation: Location? = null// 标记private var marker: Marker? = null// 地理编码器private var geocoder: Geocoder? = null// 地址结果private var addressesLiveData: MutableLiveData<List<Address>> = MutableLiveData()companion object {private val TAG = GoogleMapActivity::class.java.simpleName// 默认缩放private const val DEFAULT_ZOOM = 15// 权限请求码private const val LOCATION_PERMISSION_REQUEST_CODE = 9527// 未授予位置权限时使用的默认位置(澳大利亚悉尼)和默认缩放。private val defaultLocation = LatLng(-33.8523341, 151.2106085)}override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)enableEdgeToEdge()binding = ActivityGoogleMapBinding.inflate(layoutInflater)setContentView(binding.root)ViewCompat.setOnApplyWindowInsetsListener(binding.main) { v, insets ->val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)insets}initView()}/*** 初始化视图*/private fun initView() {// 构造 PlacesClientPlaces.initialize(applicationContext, BuildConfig.MAPS_API_KEY)placesClient = Places.createClient(this)// 构造 FusedLocationProviderClient。fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragmentmapFragment.getMapAsync(this)}/*** 检查权限*/private fun checkPermission() {// 检查当前是否拥有精确位置或粗略位置权限if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {// 权限已授予,可以进行定位操作Log.d(TAG, "checkPermission: 权限已授予")configMap()} else {Log.d(TAG, "checkPermission: 请求权限")// 请求权限ActivityCompat.requestPermissions(this,arrayOf(Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION),LOCATION_PERMISSION_REQUEST_CODE)}}/*** 地图就绪*/override fun onMapReady(googleMap: GoogleMap) {map = googleMap// 检查权限checkPermission()}/*** 地图配置*/@SuppressLint("MissingPermission")private fun configMap() {Log.d(TAG, "configMap: 地图配置")// 初始化地理编码器geocoder = Geocoder(this)// 编码结果addressesLiveData.observe(this) { addresses ->// 获取地址信息if (!addresses.isNullOrEmpty()) {val address = addresses[0]Log.d(TAG, "Address: ${address.latitude} ${address.longitude} ${address.countryName} ${address.adminArea} ${address.locality} ${address.thoroughfare} ${address.subThoroughfare}")}}map.apply {isMyLocationEnabled = true // 地图上启用“我的位置”图层// 当前位置图标的点击事件setOnMyLocationButtonClickListener {Log.d(TAG, "configMap: 点击位置图标")// 移除标点marker?.remove()marker = nullreturn@setOnMyLocationButtonClickListener false}// 定位后的蓝点点击事件setOnMyLocationClickListener { location ->Log.d(TAG, "configMap: 点击我的位置 $location")Toast.makeText(this@GoogleMapActivity, "Current location:\n$location", Toast.LENGTH_LONG).show()}// 地图点击事件setOnMapClickListener { latLng ->changeMapCenter(latLng)}// 地图设置uiSettings.apply {isZoomControlsEnabled = true // 显示缩放按钮isMyLocationButtonEnabled = true // 显示定位按钮isCompassEnabled = true // 显示指南针isMapToolbarEnabled = true // 显示地图工具栏isRotateGesturesEnabled = true // 允许旋转手势isScrollGesturesEnabled = true // 允许滚动手势isTiltGesturesEnabled = true // 允许倾斜手势isZoomGesturesEnabled = true // 允许缩放手势isScrollGesturesEnabledDuringRotateOrZoom = true // 允许在旋转或缩放时滚动手势isIndoorLevelPickerEnabled = true // 显示室内层选择器}}// 获取当前位置getCurrentLocation()}/*** 获取当前位置*/@SuppressLint("MissingPermission")private fun getCurrentLocation() {Log.d(TAG, "getCurrentLocation: 获取当前位置")fusedLocationProviderClient.lastLocation.addOnCompleteListener { task ->// 获取当前位置未成功if (!task.isSuccessful) {Log.d(TAG, "Current location is null. Using defaults.")Log.e(TAG, "Exception: %s", task.exception)// 设置默认位置changeMapCenter(defaultLocation)return@addOnCompleteListener}lastKnownLocation = task.resultif (lastKnownLocation == null) return@addOnCompleteListener// 移动地图到当前位置changeMapCenter(LatLng(lastKnownLocation!!.latitude, lastKnownLocation!!.longitude))}}/*** 改变地图中心*/private fun changeMapCenter(latLng: LatLng) {// 移除标点marker?.remove()// 添加标点marker = map.addMarker(MarkerOptions().title("Marker") // 设置标题.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_google)) // 设置自定义图标.alpha(0.7f) // 设置透明度.position(latLng) // 设置位置)// 获取详细位置信息// getDetailAddress(latLng)// 获取默认经纬度的地址信息getDetailLatLng()// 地图中移动到经纬度处map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, DEFAULT_ZOOM.toFloat()))}/*** 获取默认经纬度的地址信息*/private fun getDetailLatLng(address: String = "悉尼歌剧院") {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {geocoder?.getFromLocationName(address, 1, this@GoogleMapActivity)} else {addressesLiveData.postValue(geocoder?.getFromLocationName(address, 1))}}/*** 获取详情位置信息,获取国内位置会出现异常*/private fun getDetailAddress(latLng: LatLng) {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {geocoder?.getFromLocation(latLng.latitude, latLng.longitude, 1, this@GoogleMapActivity)} else {addressesLiveData.postValue(geocoder?.getFromLocation(latLng.latitude, latLng.longitude, 1))}}/*** 权限请求结果*/override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {super.onRequestPermissionsResult(requestCode, permissions, grantResults)when (requestCode) {LOCATION_PERMISSION_REQUEST_CODE -> {// 如果请求被取消,则结果数组为空if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {// 权限被授予,可以进行定位操作Log.d(TAG, "onRequestPermissionsResult: 权限被授予")configMap()} else {// 权限被拒绝,无法进行定位操作Log.d(TAG, "onRequestPermissionsResult: 权限被拒绝")Toast.makeText(this, "拒绝将无法使用定位功能", Toast.LENGTH_SHORT).show()finish()}}}}/*** 地理编码结果,经纬度坐标转地址*/override fun onGeocode(addresses: MutableList<Address>) {addressesLiveData.postValue(addresses)}
}

Reference

https://blog.csdn.net/qq_38436214/article/details/140985527

https://developers.google.cn/maps/documentation/android-sdk?hl=zh-cn


文章转载自:

http://P2WdnKD6.xnrry.cn
http://mjoNih2q.xnrry.cn
http://JjqEegcm.xnrry.cn
http://GbJkr5cs.xnrry.cn
http://E0fkcVrG.xnrry.cn
http://ejbUOlqN.xnrry.cn
http://VXwtybAv.xnrry.cn
http://l0miC1ed.xnrry.cn
http://hypCOVzD.xnrry.cn
http://pGMKt64e.xnrry.cn
http://7tIWwPtP.xnrry.cn
http://OyzJr4Bl.xnrry.cn
http://KuNX2r2Z.xnrry.cn
http://6ZRIqVID.xnrry.cn
http://d6LgE9Rh.xnrry.cn
http://6i9XB7Wz.xnrry.cn
http://ebrAVrf6.xnrry.cn
http://2GphxFqf.xnrry.cn
http://GLPTJoAO.xnrry.cn
http://2wdIlvwZ.xnrry.cn
http://ciKXJ8sN.xnrry.cn
http://GtBhdJCU.xnrry.cn
http://aGyM51C4.xnrry.cn
http://b72CjEqS.xnrry.cn
http://7BUsmiiO.xnrry.cn
http://OPgQHa3V.xnrry.cn
http://P6OQr2r2.xnrry.cn
http://wlFJOt7h.xnrry.cn
http://lK8KmxpW.xnrry.cn
http://VBSRmWEg.xnrry.cn
http://www.dtcms.com/a/382709.html

相关文章:

  • 深入理解Java虚拟机:JVM高级特性与最佳实践(第3版)第十三章知识点问答(15题)
  • 深入理解 Spring @Async 注解:原理、实现与实践
  • 【Qt开发】显示类控件(三)-> QProgressBar
  • 《Linux——gflags》
  • leetcode35.搜索插入位置
  • Java调用UniHttp接口请求失败?一次开源的深入实践-百度SN签名认证场景下参数乱序问题的三种解决策略
  • MongoDB 监控
  • 【Linux】system V共享内存
  • --- 统一请求入口 Gateway ---
  • 豆包Seedream 4.0多图融合实力派:田园犬+三花猫多场景创作,AI绘画新时代来了!
  • 贪心算法应用:数据包调度问题详解
  • html基本知识
  • 视觉SLAM第10讲:后端2(滑动窗口与位子图优化)
  • Modbus协议原理与Go语言实现详解
  • 模型部署|将自己训练的yolov8模型在rk3568上部署
  • Vue中的slot标签——插槽
  • k8s集群—node节点的删除与添加
  • k8s的dashboard
  • k8s-容器探针和生命周期回调学习
  • 跟上大数据时代步伐:食物营养数据可视化分析系统技术前沿解析
  • 大数据毕业设计选题推荐-基于大数据的结核病数据可视化分析系统-Hadoop-Spark-数据可视化-BigData
  • 全网首发! Nvidia Jetson Thor 128GB DK 刷机与测评(三)常用功能测评 DeepAnything 系列
  • Python快速入门专业版(二十六):Python函数基础:定义、调用与返回值(Hello函数案例)
  • 【系列文章】Linux中的并发与竞争[03]-自旋锁
  • Web前端面试题(1)
  • 海盗王客户端BMP纹理图片解密
  • FreeRTOS 知识点
  • Mac电脑上如何打印出字体图标
  • 2.2顺序表
  • 如何打造高效AI智能体工具