Android中高德地图SDK的一些操作

952 阅读3分钟

自定义地图背景

1.地图背景使用自定义图片

1.1 使用整张图

      val aMap = mBinding.mapView.getaMap()
      aMap.showBuildings(false)
      val latLngBounds = LatLngBounds(
          LatLng(data.latitudeBottomLeft.toDouble(), data.longitudeBottomLeft.toDouble()),
          LatLng(data.latitudeTopRight.toDouble(), data.longitudeTopRight.toDouble())
      )
      aMap.setMapStatusLimits(latLngBounds);
      aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(data.latitude.toDouble(), data.longitude.toDouble()), 18f))
      //设置显示在屏幕中的地图地理范围,地图中点显示为两个点的中点
      val bounds = LatLngBounds.Builder()
          .include(LatLng(data.latitudeBottomLeft.toDouble(), data.longitudeBottomLeft.toDouble()))
          .include(LatLng(data.latitudeTopRight.toDouble(), data.longitudeTopRight.toDouble()))
          .build()
      aMap.addGroundOverlay(
          GroundOverlayOptions()
              //设置ground覆盖物的锚点比例,默认为0.5f,水平和垂直方向都居中对齐
//                .anchor(10.0f, 10.0f)
              //设置覆盖物的透明度,范围:0.0~1.0
              .transparency(0.0f)
              //设置覆盖物的层次,zIndex值越大越在上层;
              .zIndex(-9999f)
              //覆盖物图片
              .image(BitmapDescriptorFactory.fromPath(filePath))
              .positionFromBounds(bounds)
      )
     
     

1.2 使用瓦片图

    val oriTileUrl = data.tilesMap

       if (oriTileUrl.isBlank()) return

       //后台的瓦片图路径
       val tileOverlayOptions = TileOverlayOptions().tileProvider(object : UrlTileProvider(256, 256) {
           override fun getTileUrl(x: Int, y: Int, zoom: Int): URL {
               try {
                   // x横坐标 ,y纵坐标,zoom缩放比
                   val url = oriTileUrl + zoom + "/" + x + "_" + y + ".png";
                   logI(url)
                   return URL(url)
               } catch (e: Exception) {
                   e.printStackTrace()
               }
               return URL("")
           }
       })

       tileOverlayOptions.diskCacheEnabled(true)
           //添加缓存路径
           .diskCacheDir(cacheDir.absolutePath + "/amap/tile")
           //瓦片图数量
           .diskCacheSize(100000)
           .memoryCacheEnabled(true)
           .memCacheSize(100000)
           //显示的优先级
           .zIndex(-9999f)

       //添加到地图
       val mtileOverlay = mBinding.mapView.getaMap().addTileOverlay(tileOverlayOptions)
       

2 路径动态预览

    //marker animation
    private lateinit var movingPointOverlay: MovingPointOverlay
    private lateinit var bounds: LatLngBounds
    private var passedPointIndex = 0
    private val passedPoints = mutableListOf<LatLng>()
    private var passPolyline: Polyline? = null
    private var isAnimationRun = false
    /**
     * 每个景点 动画时长 秒
     */
    private var eachSpotAnimationTime = 3

    private fun initMapAnimationLayerEachSpot(latLngList: List<LatLng>) {
        //marker animation


        mBinding.mapView.getaMap().setCustomRenderer(object : CustomRenderer {
            override fun OnMapReferencechanged() {
            }

            override fun onDrawFrame(gl: GL10?) {

                if (isAnimationRun) {

                    passedPoints.add(movingPointOverlay.position)
                    passPolyline?.remove()
                    passPolyline = mBinding.mapView.getaMap().addPolyline(
                        PolylineOptions()
                            .addAll(passedPoints)
                            .color(Color.RED)
                            .zIndex(3f)
                            .width(10F)
                    )

                }
            }

            override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) {
            }

            override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) {
            }
        })


        movingPointOverlay.setPoints(latLngList)
        movingPointOverlay.setTotalDuration(eachSpotAnimationTime * latLngList.size)


        //end marker animation
    }

    private fun doAnimationEachSpot() {


        passedPoints.clear()

        if (mCurrentPosition < 1) mCurrentPosition = 1

        initMapAnimationLayerEachSpot(mPointList.subList(mCurrentPosition - 1, mCurrentPosition + 1))

        mBinding.mapView.getaMap().moveCamera(CameraUpdateFactory.changeLatLng(mPointList[mCurrentPosition - 1]))

        isAnimationRun = true

        movingPointOverlay.startSmoothMove()

        mBinding.mapView.getaMap().animateCamera(CameraUpdateFactory.changeLatLng(mPointList[mCurrentPosition]), (eachSpotAnimationTime * 1000).toLong(), null)

    }


    private fun initMapAnimationLayer() {
        //marker animation

        movingPointOverlay = MovingPointOverlay(
            mBinding.mapView.getaMap(),
            mBinding.mapView.getaMap().addMarker(
                MarkerOptions()
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.guide_map_location))
                    .zIndex(10f)
            )
        )


        val leastBound = LatLng(
            mPointList.minBy { it.latitude }?.latitude ?: 0.0,
            mPointList.minBy { it.longitude }?.longitude ?: 0.0
        )

        val maxBound = LatLng(
            mPointList.maxBy { it.latitude }?.latitude ?: 0.0,
            mPointList.maxBy { it.longitude }?.longitude ?: 0.0
        )



        mBinding.mapView.getaMap().setCustomRenderer(object : CustomRenderer {
            override fun OnMapReferencechanged() {
            }

            override fun onDrawFrame(gl: GL10?) {

                if (isAnimationRun) {

                    if (movingPointOverlay.index > passedPointIndex) {
                        passedPointIndex = movingPointOverlay.index
                        passedPoints.add(mPointList[passedPointIndex])
                    }

                    passedPoints.add(movingPointOverlay.position)
                    passPolyline?.remove()
                    passPolyline = mBinding.mapView.getaMap().addPolyline(
                        PolylineOptions()
                            .addAll(passedPoints)
                            .color(Color.RED)
                            .zIndex(3f)
                            .width(10F)
                    )

                    if (passedPoints.contains(mPointList[mCurrentPosition])) {
                        isAnimationRun = false
                        movingPointOverlay.stopMove()
                    }


                    if (movingPointOverlay.position == mPointList.last()) {
                        isAnimationRun = false
                        passedPoints.clear()
                    }


                }
            }

            override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) {
            }

            override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) {
            }
        })


        movingPointOverlay.setMoveListener {
            logI("movingPointOverlay.setMoveListener  $it ")
            if (it == 0.0) {
                isAnimationRun = false
                movingPointOverlay.stopMove()
                passedPoints.clear()

                mBinding.mapView.getaMap().animateCamera(CameraUpdateFactory.changeLatLng(mPointList.last()), (eachSpotAnimationTime * 1000).toLong(), null)
            }

            //获取当前的移动marker点,设置地图中心坐标点
            val position = movingPointOverlay.position
            mBinding.mapView.getaMap().moveCamera(CameraUpdateFactory.changeLatLng(position))

        }


        bounds = LatLngBounds(leastBound, maxBound)
        movingPointOverlay.setPoints(mPointList)
        movingPointOverlay.setTotalDuration(eachSpotAnimationTime * mPointList.size)
        mBinding.mapView.getaMap().animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50))

        //end marker animation
    }

    private fun doAnimation() {

        if (mCurrentPosition < 1) mCurrentPosition = 1

        mBinding.mapView.getaMap().moveCamera(CameraUpdateFactory.changeLatLng(mPointList[mCurrentPosition - 1]))

        isAnimationRun = true

        movingPointOverlay.startSmoothMove()

        mBinding.mapView.getaMap().animateCamera(CameraUpdateFactory.changeLatLng(mPointList[mCurrentPosition]), (eachSpotAnimationTime * 1000).toLong(), null)
    }

    //  end  marker animation
    

3.自定义infowindo Adapter

  private fun setMarkerInfoWindowAdapter() {

        mBinding.mapView.getaMap().setInfoWindowAdapter(object : AMap.InfoWindowAdapter {
            override fun getInfoContents(marker: Marker?): View? {
                return null
            }

            override fun getInfoWindow(marker: Marker?): View {
                val v = View.inflate(this@GuideTourMapActivity, R.layout.guide_layout_map_marker_info_window, null)
                val tv = v.findViewById<TextView>(R.id.tv_marker)

                marker?.let { markerView ->
                    val bean = markerView.`object`

                    if (bean is GuideScenicListBean) {
                        tv.text = bean.name
                    }
                }
                return v
            }
        })

    }
    
    
    
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
    
    </data>

    <TextView
        android:id="@+id/tv_marker"
        android:layout_width="@dimen/dp_70"
        android:layout_marginBottom="@dimen/dp_3"
        android:layout_height="@dimen/dp_15"
        android:background="@drawable/guide_map_marker_info_window"
        android:ellipsize="middle"
        android:gravity="center"
        android:singleLine="true"
        android:textColor="@color/guide_916112"
        android:textSize="@dimen/sp_10"
        tools:text="峡谷大景区峡谷大景区峡谷大景区峡谷大景区峡谷大景区峡谷大景区" />


</layout>

4.其它

  //设置层级   zIndex()
  
      tileOverlayOptions.diskCacheEnabled(true)
            //添加缓存路径
            .diskCacheDir(cacheDir.absolutePath + "/amap/tile")
            //瓦片图数量
            .diskCacheSize(100000)
            .memoryCacheEnabled(true)
            .memCacheSize(100000)
            //显示的优先级
            .zIndex(-9999f)
            
  
   mPolyLine = mBinding.mapView.getaMap()
                    ?.addPolyline(
                        PolylineOptions().addAll(points).color(resources.getColor(R.color.guide_green_6ac302)).zIndex(2f)
                            .width(10f)
                    )
                    
  val markerOptions = MarkerOptions()
            .title(el.name)
            .icon(BitmapDescriptorFactory.fromView(markerView))
            .position(LatLng(el.latitude.toDouble(), el.longitude.toDouble()))
            .setInfoWindowOffset(0, 0)
            .draggable(false)
            .zIndex(2f)
            

未完待续