android 地图自定义mark,以高德地图为例

配置key等基本操作就不赘述了,一个老弟问了,我就直接贴代码,简单梳理一下,有问题可以留言。

 var map: MapView? = null
    var mAMap: AMap? = null
    var myLocationStyle: MyLocationStyle? = null
    //用于定位
    var mlocationClient: AMapLocationClient? = null
    var mLocationOption: AMapLocationClientOption? = null
    var mLocationListener: AMapLocationListener? = null
    var listlocal: List<LocalBean> = listOf<LocalBean>()

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val rootView = inflater!!.inflate(R.layout.fragment_local_kot, null)
        map = rootView?.findViewById(R.id.map)
        map!!.onCreate(savedInstanceState)// 此方法必须重写
        mAMap = map!!.getMap()
        mAMap!!.moveCamera(CameraUpdateFactory.zoomTo(14f))
        myLocationStyle = MyLocationStyle()//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点,定位点依照设备方向旋转,并且会跟随设备移动。(1秒1次定位)如果不设置myLocationType,默认也会执行此种模式。
        myLocationStyle!!.interval(1000) //设置连续定位模式下的定位间隔,只在连续定位模式下生效,单次定位模式下不会生效。单位为毫秒。
        myLocationStyle!!.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE)
        mAMap!!.setMyLocationStyle(myLocationStyle)//设置定位蓝点的Style
        mAMap!!.getUiSettings()!!.isMyLocationButtonEnabled = true// 设置默认定位按钮是否显示
//  mAMap!!.uiSettings.isZoomControlsEnabled = false//缩放放大按钮是否显示
        mAMap?.uiSettings?.zoomPosition = AMapOptions.LOGO_POSITION_BOTTOM_LEFT
        mAMap?.uiSettings?.isZoomControlsEnabled = false

        mAMap!!.isMyLocationEnabled = true// 设置为true表示启动显示定位蓝点,false表示隐藏定位蓝点并不进行定位,默认是false。
        //用于定位的方法
        mlocationClient = AMapLocationClient(context)
        mLocationOption = AMapLocationClientOption()
        //  mLocationListener = AMapLocationListener { }
        mlocationClient?.setLocationListener(this)
        mLocationOption?.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy)
        mLocationOption?.setInterval(1000)
        mlocationClient?.setLocationOption(mLocationOption)
        mlocationClient?.startLocation();
        mPresent = LocalPresent(activity as Context)
        mPresent?.attachView(this)
        /*  val marker1 = LatLng(kotlin.Double.parseDouble(lat), kotlin.Double.parseDouble(lon))
          //设置中心点和缩放比例
          mAMap!!.moveCamera(CameraUpdateFactory.changeLatLng(marker1))
          mAMap!!.moveCamera(CameraUpdateFactory.zoomTo(12f))*/
        mAMap!!.setOnMarkerClickListener(this)
        mAMap?.setOnMyLocationChangeListener(this)
        return rootView
    }
  
//getAroundUser是通过自己服务器获得的接口返回数据,getAroundUser是自己起的方法名
    override fun getAroundUser(list: MutableList<LocalBean>) {

        mAMap!!.setOnMarkerClickListener(this)
        mAMap?.clear()
        for (index in 0..(list?.size - 1)) {
            var view: View = View.inflate(context, R.layout.view_map_mark, null)
            var iv_header = view.findViewById<ImageView>(R.id.iv_header)
            var rl_mark = view.findViewById<RelativeLayout>(R.id.rl_mark)
            if (list.get(index).type == 1) {
                rl_mark.setBackgroundResource(R.mipmap.position_bg_wc)
            } else if (list.get(index).id.equals(MyApplication.getInstance().user.id)) {
                rl_mark.setBackgroundResource(R.mipmap.position_bg_red)
            } else {
                rl_mark.setBackgroundResource(R.mipmap.position_bg_green)
            }
            val options = RequestOptions()
            options.centerCrop().placeholder(R.mipmap.default_avatar).error(R.mipmap.default_avatar)
            if (!list?.get(index)?.head_pic?.contains("http")) {
                Glide.with(this).asBitmap()
                        .load(UrlUtils.APIHTTP + "/" + list.get(index).head_pic)
                        .apply(options)
                        .into(object : SimpleTarget<Bitmap>() {
                            override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                                iv_header.imageBitmap = resource
                                var bitmap: Bitmap = convertViewToBitmap(view)
                                val latLng = LatLng(list.get(index).latitude, list.get(index).longitude)
                                drawMarkerOnMap(latLng, bitmap, list.get(index).id)
                            }

                            override fun onLoadFailed(errorDrawable: Drawable?) {
                                super.onLoadFailed(errorDrawable)
                                var bitmap: Bitmap = convertViewToBitmap(view)
                                val latLng = LatLng(list.get(index).latitude, list.get(index).longitude)
                                drawMarkerOnMap(latLng, bitmap, list.get(index).id)
                            }
                        })
            } else {
                Glide.with(this).asBitmap()
                        .load(list.get(index).head_pic)
                        .apply(options)
                        .into(object : SimpleTarget<Bitmap>() {
                            override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                                iv_header.imageBitmap = resource
                                var bitmap: Bitmap = convertViewToBitmap(view)
                                val latLng = LatLng(list.get(index).latitude, list.get(index).longitude)
                                drawMarkerOnMap(latLng, bitmap, list.get(index).id)
                            }

                            override fun onLoadFailed(errorDrawable: Drawable?) {
                                super.onLoadFailed(errorDrawable)
                                var bitmap: Bitmap = convertViewToBitmap(view)
                                val latLng = LatLng(list.get(index).latitude, list.get(index).longitude)
                                drawMarkerOnMap(latLng, bitmap, list.get(index).id)
                            }
                        })
            }

        }
        listlocal = list
    }
//view 转bitmap
    fun convertViewToBitmap(view: View): Bitmap {

        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))

        view.layout(0, 0, view.measuredWidth, view.measuredHeight)

        view.buildDrawingCache()

        return view.drawingCache
    }


    /**
     *
     * 在地图上画marker
     *
     *
     *
     * @param point      marker坐标点位置(example:LatLng point = new LatLng(39.963175,
     *
     * 116.400244); )
     *
     * @param markerIcon 图标
     *
     * @return Marker对象
     */

    private fun drawMarkerOnMap(point: LatLng?, markerIcon: Bitmap, id: String): Marker? {

        return if (mAMap != null && point != null) {
            mAMap?.addMarker(MarkerOptions().anchor(0.5f, 1f)

                    .position(point)

                    .title(id)

                    .icon(BitmapDescriptorFactory.fromBitmap(markerIcon)))
        } else null
    }

    var longitude = ""
    var latitude = ""
    override fun onLocationChanged(p0: AMapLocation?) {
        if (p0 != null) {
            if (p0.errorCode == 0) {
                //从location对象中获取经纬度信息,地址描述信息,建议拿到位置之后调用逆地理编码接口获取(获取地址描述数据章节有介绍)
 //记得有定位失败的情况,获得自己的经纬度,可以去请求附近人的数据,给后台传数据等
                longitude = p0?.longitude.toString()
                latitude = p0?.latitude.toString()       
                }
            } else {
                //显示错误信息ErrCode是错误码,errInfo是错误信息,详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + p0.getErrorCode() + ", errInfo:"
                        + p0.getErrorInfo());
            }
        }
    }
    
     var curShowWindowMarker: Marker? = null
    /*
    * 点击地图上的mark
    * */
    override fun onMarkerClick(p0: Marker?): Boolean {
        var local: LocalBean? = null
        for (index in 0..(listlocal.size - 1)) {
            if (listlocal.get(index).id.equals(p0?.title)) {
                local = listlocal.get(index)
            }
        }
        curShowWindowMarker = p0
        p0?.hideInfoWindow()
        val intent = Intent(activity, PersonHomeActivity::class.java)
        intent.putExtra("user_id", local?.id)
        startActivityForResult(intent, 66)
        return true
    }

 override fun onMyLocationChange(p0: Location?) {

    }
        override fun onCameraChange(p0: CameraPosition?) {
    }

    override fun onCameraChangeFinish(p0: CameraPosition?) {
    }
    
    
    //必须重写的几个方法
     
     override fun onResume() {
        super.onResume()
        map!!.onResume()
        }
     override fun onDestroy() {
        super.onDestroy()
        map!!.onDestroy()
    }
     override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        map?.onSaveInstanceState(outState)
    }
     override fun onPause() {
        super.onPause()
        map!!.onPause()
    }

注:
1、你的activity或者fragment用来管理地图的,需要继承AMap.OnCameraChangeListener, AMap.OnMarkerClickListener, AMap.OnMyLocationChangeListener, AMapLocationListener这几个接口。
2、R.layout.view_map_mark 就是你的自定义mark布局
3、R.layout.fragment_local_kot 就是你的地图布局

R.layout.view_map_mark

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:id="@+id/rl_mark"
    android:layout_width="50dp"
    android:layout_height="61dp"
    tools:background="@mipmap/position_bg_green">

    <com.makeramen.roundedimageview.RoundedImageView
        android:id="@+id/iv_header"
        android:layout_width="33dp"
        android:layout_height="33dp"
        android:layout_marginLeft="9dp"
        android:layout_marginTop="8dp"
        android:scaleType="centerCrop"
        android:src="@mipmap/default_avatar"
        app:riv_oval="true" />

</RelativeLayout>

R.layout.fragment_local_kot

<RelativeLayout 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="match_parent"
    android:background="@color/transparent"
    android:orientation="vertical">

    <com.amap.api.maps.MapView
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>
发布了42 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/u013750244/article/details/105158366