Android:高德SDK的基本使用

时间:2025-01-29 12:01:45

文章目录

  • 前言
  • 一、显示地图
    • 布局
    • 2.代码部分(kotlin)
  • 二、获取定位
      • 1.先做声明
      • 2.初始化定位模式
      • 3.设置定位监听器
      • 4.初始化定位客户端
      • 5.整体代码
  • 总结


前言

这段时间做了一个需要定位的项目,于是就想到了用到高德地图的SDK,在这里我就不讲下载和配置了,直接说开始使用的部分


提示:以下是本篇文章正文内容,下面案例可供参考

一、显示地图

显示地图比较简单,在这里直接就上代码了## 1.布局文件:

布局

<?xml version="1.0" encoding="utf-8"?>
< xmlns:android="/apk/res/android"
    xmlns:app="/apk/res-auto"
    xmlns:tools="/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".">

    <
        android:id="@+id/map_map_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</>

2.代码部分(kotlin)

class MapActivity : BaseActivity() {
    private lateinit var binding: ActivityMapBinding
    private lateinit var aMap: AMap
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMapBinding.inflate(layoutInflater)
        setContentView(binding.root)
        mapInit(savedInstanceState)
    }

    //初始化地图
    private fun mapInit(savedInstanceState: Bundle?){
        binding.mapMapView.onCreate(savedInstanceState)
        aMap = binding.mapMapView.map//初始化地图客户端
        aMap.apply {
            uiSettings.apply {
                isTiltGesturesEnabled = false //禁止倾斜手势
                isRotateGesturesEnabled = false //禁止旋转手势
                zoomPosition = AMapOptions.ZOOM_POSITION_RIGHT_CENTER //放大和缩小手势摆放位置(右中)
            }

            moveCamera(CameraUpdateFactory.zoomTo(15f)) //初始地图缩放大小
            mapTextZIndex = 2 //设置地图底图文字标注的层级指数

            var isFirst = true
            addOnMyLocationChangeListener { //位置监听器
                if(isFirst) {
                    animateCamera(CameraUpdateFactory.newLatLng(LatLng(it.latitude,it.longitude)))//移动视图
                    isFirst = false
                }
            }
        }
        val mLocationStyle = MyLocationStyle().apply {//定位样式
            interval(2000) //定位间隔
            showMyLocation(true) //是否显示定位蓝点
            strokeColor(Color.TRANSPARENT)//设置蓝点经度圆圈的边框颜色
            radiusFillColor(Color.TRANSPARENT) //设置蓝点经度圆圈的填充颜色
            myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER) //定位模式(在这里是连续定位,但视图不跟随蓝点移动)
        }

        aMap.myLocationStyle = mLocationStyle
        aMap.isMyLocationEnabled = true

    }


	/**
	*管理地图的生命周期
	*/
    override fun onDestroy() {
        super.onDestroy()
        //在activity执行onDestroy时执行(),销毁地图
        binding.mapMapView.onDestroy()
    }

    override fun onResume() {
        super.onResume()
        //在activity执行onResume时执行 (),重新绘制加载地图
        binding.mapMapView.onResume()
    }

    override fun onPause() {
        super.onPause()
        //在activity执行onPause时执行 (),暂停地图的绘制
        binding.mapMapView.onPause()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        binding.mapMapView.onSaveInstanceState(outState)
    }
}

二、获取定位

1.先做声明

这两句代码少了会报错的,定位之前记得先声明

 AMapLocationClient.updatePrivacyShow(context, true, true)
 AMapLocationClient.updatePrivacyAgree(context, true)

2.初始化定位模式

val aMapOption = AMapLocationClientOption().apply {
       locationPurpose = AMapLocationClientOption.AMapLocationPurpose.Transport //定位场景:出行
       locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy //高精度模式
       isOnceLocationLatest = true //采取三秒内经度最高的一点
       isOnceLocation = true //是否开启单词定位模式,为true的话只会定位一次
       isLocationCacheEnable = false //是否清楚定位缓存
}

3.设置定位监听器

获取的位置都会在监听器里面,可以在这里面设置活动

 val locationListener = AMapLocationListener{
     if(0 == it.errorCode){//如果errorCode == 0 则定位成功                
          Log.i(TAG, "locatInfo: $it,${it.adress}")
     }else{//否则定位失败,具体报错内容可以从errorInfo中获取
          Log.e(TAG, "locatInit: code: ${it.errorCode}  ,info:${it.errorInfo}")
     }
}

4.初始化定位客户端

val aMapClient = AMapLocationClient(context).apply {//定位客户端
      setLocationOption(aMapOption) //设置定位模式,上面设置好的options
      stopLocation() //重启定位,防止option设置不生效
      startLocation()
      setLocationListener(locationListener)
} 

5.整体代码

这是我项目的全部代码,也不想整理了,直接全部贴上了

class HomeFragment : Fragment(){
    private val TAG = "HomeFragment"
    private lateinit var binding: FragmentHomeBinding
    private val radioBtns = arrayListOf<RadioButton>()
    private lateinit var registerResult: ActivityResultLauncher<Intent>
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentHomeBinding.inflate(inflater,container,false)
        init()
        Log.d(TAG, "onCreateView: ")
        return binding.root
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        registerResult =  registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
            val data = it.data //获取跳转的数据
            //
        }
    }


    private fun init(){
        viewPageInit()
        binding.fragmentHomeLocation.setOnClickListener{
            registerResult.launch(Intent(context,MapActivity::class.java))
        }
        locatInit()
        binding.fragmentHomeLocation.text = Entitys.locationInfos?.poiName ?: "定位中..."
    }

    private fun viewPageInit(){
        binding.fragmentHomeViewpage.adapter = HomeViewPageAdapter()
        setRadioBtn()
        binding.fragmentHomeGroup.setOnCheckedChangeListener{group,checkId ->
            binding.fragmentHomeViewpage.currentItem = checkId
        }
        binding.fragmentHomeViewpage.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback(){
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                radioBtns[position].isChecked = true
            }
        })
    }

    /**
     * 初始化定位
     */
    private fun locatInit(){
        AMapLocationClient.updatePrivacyShow(context, true, true)
        AMapLocationClient.updatePrivacyAgree(context, true)
        val locationListener = AMapLocationListener{
            if(0 == it.errorCode){
                Entitys.locationInfos = it
                binding.fragmentHomeLocation.text = it.aoiName
                Log.i(TAG, "locatInfo: $it,${it.address}")
            }else{
                binding.fragmentHomeLocation.text = "定位失败"
                Log.e(TAG, "locatInit: code: ${it.errorCode}  ,info:${it.errorInfo}")
            }
        }

        val aMapOption = AMapLocationClientOption().apply {
            locationPurpose = AMapLocationClientOption.AMapLocationPurpose.Transport //定位场景:出行
            locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy //高精度模式
            isOnceLocationLatest = true //采取三秒内经度最高的一点
            isOnceLocation = true
            isLocationCacheEnable = false

        }
        val aMapClient = AMapLocationClient(context).apply {//定位客户端
            setLocationOption(aMapOption)
            stopLocation() //重启定位,防止option设置不生效
            startLocation()
            setLocationListener(locationListener)
        }
    }


    /**
     * 设置活动页面的单选按钮
     */
    private fun setRadioBtn(){
        for(a in 0 until Entitys.activityEntitys.size){
            val radioBtn = RadioButton(context)
            val img =  resources.getDrawable(R.drawable.selector_fragment_home_circle,null)
            img.setBounds(0,0,25,25)
            radioBtn.buttonDrawable = null
            radioBtn.setPadding(3,3,3,3)
            radioBtn.setCompoundDrawables(null,img,null,null)
            radioBtn.id = a
            radioBtns.add(radioBtn)
            binding.fragmentHomeGroup.addView(radioBtn)
        }
    }

    override fun onDestroy() {
        super.onDestroy()

    }
}

总结

高德地图的SDK内容很多,还需要很长时间来学习,最近我要做一个类美团的应用来练手,正好也用到了高德的SDK,也希望能有大佬来带带我