百度地图选点定位界面

1.去申请app的Appkey,对百度sdk的引入和配置

2.xml

<?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="listener"
            type="android.view.View.OnClickListener" />
    </data>
    <LinearLayout
        tools:context=".activity.MapNavigation"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <RelativeLayout
            android:layout_width="match_parent"
            android:background="@drawable/home_top_gradient_bg"
            android:layout_height="48dp">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="@dimen/dp_48"
                android:gravity="center"
                android:text="选点定位"
                android:textColor="@color/white"
                android:textSize="18sp" />

            <TextView
                android:id="@+id/tv_sure"
                android:layout_width="wrap_content"
                android:layout_height="@dimen/dp_48"
                android:layout_alignParentRight="true"
                android:layout_marginRight="20dp"
                android:gravity="center"
                android:onClick="@{listener}"
                android:text="确定选点"
                android:textColor="@color/white"
                android:textSize="12sp" />
        </RelativeLayout>




        <com.baidu.mapapi.map.TextureMapView
            android:id="@+id/bmapView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1"/>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/line" />

        <LinearLayout
            android:id="@+id/ll_location"
            android:visibility="gone"
            android:layout_width="match_parent"
            android:layout_height="@dimen/dp_60"
            android:background="@color/white"
            android:layout_gravity="bottom"
            android:orientation="vertical">

            <com.hnwx.rhpk.view.MyValueTextView
                android:id="@+id/tv_address"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:maxLines="1"
                android:ellipsize="end"
                android:paddingLeft="@dimen/dp_10"
                android:gravity="left|center_vertical"
                android:text=""
                android:textColor="#000"
                android:textSize="12sp" />

            <com.hnwx.rhpk.view.MyValueTextView
                android:id="@+id/tv_latlng"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="left|center_vertical"
                android:maxLines="1"
                android:ellipsize="end"
                android:text="位置:"
                android:paddingLeft="@dimen/dp_10"
                android:textColor="#000"
                android:textSize="12sp" />

        </LinearLayout>

    </LinearLayout>
</layout>

3Java代码


/**
 * 地图选点定位
 */
open class MapNavigation : BaseActivity<ActivityMapNavigationBinding>(), BaiduMap.OnMapClickListener, OnGetGeoCoderResultListener {
    private lateinit var mBaiduMap: BaiduMap
    private var markList: ArrayList<MarkerOptions> = ArrayList()
    private var mClusterManager: ClusterManager<HomeFragmentMap.MyItem>? = null
    private var zoomTo = 13.0f
    private var mMapStatus: MapStatus? = null
    private lateinit var mSearch : GeoCoder
    private var lat = 28.234893
    private var lng = 112.94547
    private var viewId = 0
    private var position = -1

    companion object {
        @JvmStatic
        fun goMapNavigationActivity(context: Context, lon: Double, lat: Double,viewId: Int,position: Int) {
            val intent = Intent(context, MapNavigation().javaClass)
            intent.putExtra("lon", lon)
            intent.putExtra("lat", lat)
            intent.putExtra("viewId", viewId)
            intent.putExtra("position", position)
            ActivityUtils.startActivity(intent)
        }
        @JvmStatic
        fun goMapNavigationActivity(context: Context) {
            ActivityUtils.startActivity(Intent(context, MapNavigation().javaClass))
        }

    }

    override fun init() {
        mBaiduMap = getBinding().bmapView.map
        //设置不让手势旋转地图
        mBaiduMap.uiSettings.isRotateGesturesEnabled = false;
        mBaiduMap.uiSettings.isOverlookingGesturesEnabled = false;
//         设置地图监听,当地图状态发生改变时,进行点聚合运算
        mBaiduMap.setOnMapStatusChangeListener(mClusterManager)
//         设置maker点击时的响应
        mBaiduMap.setOnMarkerClickListener(mClusterManager)
        mSearch = GeoCoder.newInstance()
        mSearch.setOnGetGeoCodeResultListener(this)

        intent.getStringExtra("lat")
        lat = intent.getDoubleExtra("lat",28.234893)
        lng = intent.getDoubleExtra("lon",112.94547)
        viewId = intent.getIntExtra("viewId",0)
        position = intent.getIntExtra("position",-1)
        setMarks(lat,lng)

        getBinding().setListener {
            when (it.id) {
                R.id.tv_sure -> {
                    initLocation()

                    if(getBinding().tvLatlng.text.toString().isNotEmpty()){

                        EventBusUtil.post(MapSelectLocationEvent(
                            getBinding().tvLatlng.text.toString(),getBinding().tvAddress.text.toString(),
                            viewId,position))
                    }
                    finish()
                }
            }
        }
        mBaiduMap.setOnMapClickListener(this)
        mBaiduMap.isMyLocationEnabled = true
        // 初始化定位
        //地图加载完成回调,(只在初始化调一次)
        mBaiduMap.setOnMapLoadedCallback {
            mBaiduMap.setMaxAndMinZoomLevel(18.toFloat(), 11.toFloat())
            // 初始化默认定位点
            mMapStatus =
                MapStatus.Builder().target(LatLng(lat, lng)).zoom(zoomTo).build()
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(mMapStatus))
            getBinding().bmapView.setMapCustomStyleEnable(true)
        }
        // 隐藏百度logo
        val child: View = getBinding().bmapView.getChildAt(1)
        if (child != null && (child is ImageView || child is ZoomControls)) {
            child.visibility = View.GONE
        }
        initListener()
    }

    /**
     * 设置mark点
     */
    private fun setMarks(lat: Double, lon: Double) {
        mBaiduMap.clear()
        markList.clear()
        val markView =
            LayoutInflater.from(this).inflate(R.layout.layout_baidu_mark, null)
//        val markIndex = markView.findViewById<TextView>(R.id.iv_mark)
//                        val split = it.color.replace("rgb(", "").replace(")", "").split(",")

        val bundle = Bundle()
        val dataInfo = MapMarkBean.Data()
        dataInfo.site = "$lon,$lat"

        bundle.putSerializable("datainfo", dataInfo)
        val markerOptionsA = MarkerOptions()
            .extraInfo(bundle)
            // 经纬度
            .position(LatLng(lat, lon))
            // 设置 Marker 覆盖物的图标
            .icon(BitmapDescriptorFactory.fromView(markView))
//            .icon(BitmapDescriptorFactory.fromResource(R.drawable.dwd))
            // 设置 marker 在地图的层级
            .zIndex(9)
            // 设置Marker是否可点击
            .clickable(false)
            // 设置 marker 是否允许拖拽,默认不可拖拽
            .draggable(false)
            // 设置是否开启 marker 覆盖物近大远小效果,默认开启
            .perspective(false)
            // 设置 marker 覆盖物的锚点比例,默认(0.5f, 1.0f)水平居中,垂直下对齐
            .anchor(0.5f, 1.0f)
            // 设置多少帧刷新一次图片资源,Marker动画的间隔时间,值越小动画越快 默认为20,最小为1
            .period(10)
//        // 掉下动画
//        markerOptionsA.animateType(MarkerOptions.MarkerAnimateType.drop)
        // 生长动画
//        markerOptionsC.animateType(MarkerOptions.MarkerAnimateType.grow)
        markList.add(markerOptionsA)
        mBaiduMap.addOverlay(markerOptionsA)
    }

    /**
     * 给marker点添加点击事件
     */
    private fun initListener() {
        // 设置Marker 点击事件监听
        mBaiduMap.setOnMarkerClickListener { marker ->
            val dataInfo = marker.extraInfo.getSerializable("datainfo") as MapMarkBean.Data
            dataInfo.let {
                val list = ArrayList<MapMarkBean.Data>()
                list.add(dataInfo)
//                showMarkInfo(list)
            }
            true
        }

        // 设置地图监听,当地图状态发生改变时,进行点聚合运算
        mBaiduMap.setOnMapStatusChangeListener(object : BaiduMap.OnMapStatusChangeListener {
            /**
             * status - 地图状态改变开始时的地图状态
             */
            override fun onMapStatusChangeStart(p0: MapStatus?) {
                // 手势操作地图,设置地图状态等操作导致地图状态开始改变。
            }

            /**
             * status - 地图状态改变开始时的地图状态
             * reason - 地图状态改变的原因
             */
            override fun onMapStatusChangeStart(p0: MapStatus?, p1: Int) {
                // 手势操作地图,设置地图状态等操作导致地图状态开始改变。
            }

            /**
             * status - 当前地图状态
             */
            override fun onMapStatusChange(p0: MapStatus?) {
                // 地图状态变化中
            }

            /**
             * status - 地图状态改变结束后的地图状态
             */
            override fun onMapStatusChangeFinish(p0: MapStatus?) {
                // 地图状态改变结束
                //   p0.zoom 地图缩放级别 4~21,室内图支持到22
                LogUtil.d("zoom->", p0?.zoom.toString())

            }

        })
    }

    override fun onResume() {
        super.onResume()
        // MapView的生命周期与Activity同步,当activity onResume 时必须调用MapView.onResume()
        getBinding().bmapView.onResume()

    }

    override fun onPause() {
        super.onPause()
        // MapView的生命周期与Activity同步,当activity销毁时必须调用MapView.onPause()
        getBinding().bmapView.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        //不允许图层定位
        mBaiduMap.isMyLocationEnabled = false
        // 清除所有图层
        mBaiduMap.clear()
        mSearch.destroy()
        getBinding().bmapView.setMapCustomStyleEnable(false)
        // MapView的生命周期与Activity同步,当activity销毁时必须调用MapView.destroy()
        getBinding().bmapView.onDestroy()
    }

    override fun isUserEventBus(): Boolean {
        return false
    }

    override fun onMapClick(p0: LatLng?) {
        if (p0 != null) {
            LogUtils.d("onMapClick"+p0.latitude+"lon"+p0.longitude)
            setMarks(p0.latitude, p0.longitude)
            mSearch.reverseGeoCode(
                ReverseGeoCodeOption()
                    .location(p0)
            )
        }
    }

    override fun onMapPoiClick(p0: MapPoi?) {
        if (p0 != null) {
            LogUtils.d("onMapClick"+p0.position.latitude+"lon"+p0.position.longitude)
            setMarks(p0.position.latitude, p0.position.longitude)
            mSearch.reverseGeoCode(
                ReverseGeoCodeOption()
                    .location(p0.position)
            )
        }
    }

    //正向编码,通过地址获得经纬度
    override fun onGetGeoCodeResult(result: GeoCodeResult?) {
    }

    //反向编码,通过经纬度获得地址
    override fun onGetReverseGeoCodeResult(result: ReverseGeoCodeResult?) {

        if (result == null || result.error !== SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(this, "抱歉,未能找到结果", Toast.LENGTH_LONG)
                .show()

            getBinding().tvLatlng.text = "位置:"
            getBinding().tvAddress.text = "未获取到位置"
            return
        }
        if(getBinding().llLocation.visibility == View.GONE){
            getBinding().llLocation.visibility = View.VISIBLE
        }
//        getBinding().tvLatlng.text = "位置:"+result.location.longitude+","+result.location.latitude
//        getBinding().tvLatlng.text = ""+result.location.longitude+","+result.location.latitude
        getBinding().tvLatlng.text = ""+
                String.format("%.6f", result.location.longitude)+","+String.format("%.6f", result.location.latitude)
        getBinding().tvAddress.text = ""+result.address

    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值