• Android开发之百度地图定位打卡



    前面发了一篇地图定位的,今天继续深入学习,实现定位打卡功能。

    一、效果图

    在这里插入图片描述

    二、下载百度地图SDK

    前面已经详细讲解过,这里就不再说了,新来的小伙伴可以去看上一篇文章哦
    上一篇:Android开发之百度地图定位
    申请好AK、下载好SDK并导入完成后,进入下一步

    三、代码实现

    1.布局文件(activity_main)

    在这里插入图片描述

    
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:orientation="vertical">
    
        
        <androidx.appcompat.widget.Toolbar
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:id="@+id/toolbar"
            android:background="?attr/colorPrimary"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
            <TextView
                android:id="@+id/tv_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"
                android:textColor="#ffffff"
                android:layout_gravity="center"/>
        androidx.appcompat.widget.Toolbar>
    
        
        <FrameLayout
            android:id="@+id/viewContent"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        FrameLayout>
    
    LinearLayout>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    2.布局文件(activity_map)

    在这里插入图片描述

    
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    
        <com.baidu.mapapi.map.MapView
            android:id="@+id/mapview"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"/>
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:background="#fff"
            android:padding="10dp">
    
            <TextView
                android:id="@+id/distance_tv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="距离目的地:"
                android:textColor="#000000"
                android:layout_margin="10dp"/>
    
            <RelativeLayout
                android:id="@+id/arriver_bt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:background="@drawable/restaurant_btbg_gray">
    
                <TextView
                    android:id="@+id/arriver_timetv"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textStyle="bold"
                    android:textSize="20sp"
                    android:textColor="@color/colorPrimaryDark"
                    android:text="18:00:00"
                    android:layout_centerInParent="true"
                    />
    
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/arriver_timetv"
                    android:layout_centerHorizontal="true"
                    android:text="打卡签到"
                    android:textColor="@color/colorAccent"
                    android:textStyle="bold" />
    
            RelativeLayout>
    
    
        LinearLayout>
    
    LinearLayout>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60

    3.在res文件夹下新建menu文件夹,在其下新建布局文件(toolbar)

    在这里插入图片描述

    
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    
    
        <item
            android:id="@+id/menu_item_one"
            android:icon="@drawable/ic_launcher"
            android:orderInCategory="1"
            android:title="Settings_one"
            app:showAsAction="always"
            />
    
        <item
            android:id="@+id/menu_item_two"
            android:icon="@drawable/ic_launcher"
            android:orderInCategory="2"
            android:title="Settings_two"
            app:showAsAction="always"
    
            />
    menu>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    4.colors.xml

    
    <resources>
        <color name="purple_200">#FFBB86FCcolor>
        <color name="purple_500">#FF6200EEcolor>
        <color name="purple_700">#FF3700B3color>
        <color name="teal_200">#FF03DAC5color>
        <color name="teal_700">#FF018786color>
        <color name="black">#FF000000color>
        <color name="white">#FFFFFFFFcolor>
        <color name="colorPrimary">#3F51B5color>
        <color name="colorPrimaryDark">#303F9Fcolor>
        <color name="colorAccent">#FF4081color>
    resources>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    5.themes.xml的style中加入代码

    在这里插入图片描述

      <item name="windowActionBar">falseitem>
      <item name="windowNoTitle">trueitem>
    
    • 1
    • 2

    6.java文件(BaseActivity)

    package com.example;
    
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.os.Bundle;
    import androidx.appcompat.app.AlertDialog;
    import androidx.appcompat.app.AppCompatActivity;
    import 	androidx.appcompat.widget.Toolbar;
    import android.text.TextUtils;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.FrameLayout;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import com.baidu.mapapi.SDKInitializer;
    
    /**
     * Created by aiyang on 2018/5/18.
     */
    
    public abstract class BaseActivity extends AppCompatActivity {
    
        private String menuStr;
        private int menuResId;
        private String menuStr2;
        private int menuResId2;
        private TextView tvTitle;
        private FrameLayout viewContent;
        private Toolbar toolbar;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            //1、设置支出,并不显示项目的title文字
            toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayShowTitleEnabled(false);
    
            //2、将子类的布局解析到 FrameLayout 里面
            viewContent = (FrameLayout) findViewById(R.id.viewContent);
            LayoutInflater.from(this).inflate(getConentView(), viewContent);
    
            //3、初始化操作(此方法必须放在最后执行位置)
            try {
                init(savedInstanceState);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        /**
         * 设置布局资源
         *
         * @return
         */
        protected abstract int getConentView();
    
        /**
         * 初始化操作
         *
         * @param savedInstanceState
         */
        protected abstract void init(Bundle savedInstanceState) throws Exception;
    
        /**
         * 设置页面标题
         *
         * @param title 标题文字
         */
        protected void setTitle(String title) {
            if (!TextUtils.isEmpty(title)) {
                tvTitle = (TextView) findViewById(R.id.tv_title);
                tvTitle.setText(title);
            }
        }
        /**
         * 设置显示返回按钮
         */
        protected void setTitleBack(boolean visible) {
            if (visible) {
                toolbar.setNavigationIcon(R.drawable.back_whait);//设置返回按钮
            }
        }
    
        /**
         * 设置标题栏右键按钮事件
         *
         * @param menuStr 文字
         * @param menuResId 图片icon
         * @param onClickListener 事件响应
         */
        protected void setToolBarMenuOne(String menuStr, int menuResId, OnClickRightListener onClickListener) {
            this.onClickRightListener = onClickListener;
            this.menuStr = menuStr;
            this.menuResId = menuResId;
        }
        protected void setToolBarMenuTwo(String menuStr, int menuResId, OnClickRightListener onClickListener) {
            this.onClickRightListener2 = onClickListener;
            this.menuStr2 = menuStr;
            this.menuResId2 = menuResId;
        }
        /**
         * 设置拦截事件处理业务逻辑
         *
         * @param item 自定义菜单项
         * @return
         */
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case android.R.id.home:
                    finish();
                    break;
                case R.id.menu_item_one:
                    this.onClickRightListener.onClick();
    
                    break;
                case R.id.menu_item_two:
                    this.onClickRightListener2.onClick();
    
                    break;
            }
            return true;//拦截系统处理事件
        }
    
        /**
         * 加载Toolbar标题右菜单图标和文字
         * @param menu
         * @return
         */
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            if (menuResId != 0 || !TextUtils.isEmpty(menuStr)) {//显示自定义右菜单
                getMenuInflater().inflate(R.menu.toobar, menu);
            }else if (menuResId2 != 0 || !TextUtils.isEmpty(menuStr2)){
                getMenuInflater().inflate(R.menu.toobar, menu);
            }else {
                //如果把下面这行代码表示右侧菜单显示默认值。
                //显示的默认Menu、Item里的值必须在menu文件中配置好文字和icon。
                getMenuInflater().inflate(R.menu.toobar, menu);
            }
            return true;
        }
    
        /**
         * 选择性显示图标或文字
         * @param menu
         * @return
         */
        @Override
        public boolean onPrepareOptionsMenu(Menu menu) {
            if (menuResId != 0) {
                menu.findItem(R.id.menu_item_one).setIcon(menuResId);
            } else if (!TextUtils.isEmpty(menuStr)) {
                menu.findItem(R.id.menu_item_one).setTitle(menuStr);
            }else{
                menu.findItem(R.id.menu_item_one).setVisible(false);
            }
    
            if (menuResId2 != 0){
                menu.findItem(R.id.menu_item_two).setIcon(menuResId2);
            } else if (!TextUtils.isEmpty(menuStr)) {
                menu.findItem(R.id.menu_item_two).setTitle(menuStr2);
            }else {
                menu.findItem(R.id.menu_item_two).setVisible(false);
            }
    
            return super.onPrepareOptionsMenu(menu);
        }
    
        private OnClickRightListener onClickRightListener;
        private OnClickRightListener onClickRightListener2;
    
        public interface OnClickRightListener {
            void onClick();
        }
    
    
        /**
         * 构造广播监听类,监听 SDK key 验证以及网络异常广播
         */
        private SDKReceiver mReceiver;
        public class SDKReceiver extends BroadcastReceiver {
    
            public void onReceive(Context context, Intent intent) {
                String s = intent.getAction();
                String tx = "";
    
                if (s.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR)) {
    
                    tx = "key 验证出错! 错误码 :" + intent.getIntExtra
                            (SDKInitializer.SDK_BROADTCAST_INTENT_EXTRA_INFO_KEY_ERROR_CODE, 0)
                            +  " ; 请在 AndroidManifest.xml 文件中检查 key 设置";
                } else if (s.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK)) {
                    tx ="key 验证成功! 功能可以正常使用";
                } else if (s.equals(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR)) {
                    tx = "网络出错";
                }
                if (tx.contains("错")){
                    AlertDialog.Builder normalDialog =
                            new AlertDialog.Builder(context);
                    normalDialog.setTitle("提示");
                    normalDialog.setMessage(tx);
                    normalDialog.setPositiveButton("确定", null);
                    normalDialog.setNegativeButton("关闭", null);
                    // 显示
                    normalDialog.show();
                }else {
                    Toast.makeText(context,tx,Toast.LENGTH_SHORT).show();
                }
    
            }
        }
        protected void RegisterBroadcast(){
            IntentFilter iFilter = new IntentFilter();
            iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK);
            iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR);
            iFilter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR);
            mReceiver = new SDKReceiver();
            registerReceiver(mReceiver, iFilter);
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            // 取消监听 SDK 广播
            unregisterReceiver(mReceiver);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237

    7.java文件(MainActivity)

    package com.example;
    
    import android.annotation.SuppressLint;
    import android.graphics.Color;
    import android.graphics.Typeface;
    import android.hardware.Sensor;
    import android.hardware.SensorEvent;
    import android.hardware.SensorEventListener;
    import android.hardware.SensorManager;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Looper;
    import android.os.Message;
    import android.util.Log;
    import android.view.Gravity;
    import android.view.View;
    import android.widget.RelativeLayout;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import com.baidu.location.BDAbstractLocationListener;
    import com.baidu.location.BDLocation;
    import com.baidu.location.BDLocationListener;
    import com.baidu.location.LocationClient;
    import com.baidu.location.LocationClientOption;
    import com.baidu.mapapi.CoordType;
    import com.baidu.mapapi.SDKInitializer;
    import com.baidu.mapapi.map.BaiduMap;
    import com.baidu.mapapi.map.BitmapDescriptor;
    import com.baidu.mapapi.map.BitmapDescriptorFactory;
    import com.baidu.mapapi.map.CircleOptions;
    import com.baidu.mapapi.map.InfoWindow;
    import com.baidu.mapapi.map.MapStatusUpdateFactory;
    import com.baidu.mapapi.map.MapView;
    import com.baidu.mapapi.map.MarkerOptions;
    import com.baidu.mapapi.map.MyLocationConfiguration;
    import com.baidu.mapapi.map.MyLocationData;
    import com.baidu.mapapi.map.OverlayOptions;
    import com.baidu.mapapi.map.Stroke;
    import com.baidu.mapapi.model.CoordUtil;
    import com.baidu.mapapi.model.LatLng;
    //import com.baidu.mapapi.model.inner.Point;
    import com.baidu.mapapi.utils.DistanceUtil;
    import com.baidu.platform.comapi.basestruct.Point;
    
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    
    public class MainActivity extends BaseActivity implements SensorEventListener, View.OnClickListener {
        /**
         * 规定到达距离范围距离
         */
        private int DISTANCE = 200;
    
        private MapView mMapView;
        private TextView mDistance_tv;
        private RelativeLayout commit_bt;
        public TextView mTime_tv;
        private BaiduMap mBaiduMap;
        private SensorManager mSensorManager;//方向传感器
        private LatLng mDestinationPoint;//目的地坐标点
        private LocationClient client;//定位监听
        private LocationClientOption mOption;//定位属性
        private MyLocationData locData;//定位坐标
        private InfoWindow mInfoWindow;//地图文字位置提醒
        private double mCurrentLat = 0.0;
        private double mCurrentLon = 0.0;
        private int mCurrentDirection = 0;
        private double mDistance = 0;
        private LatLng mCenterPos;
        private float mZoomScale = 0; //比例
        private Double lastX = 0.0;
    
        @Override
        protected int getConentView() {
            SDKInitializer.setAgreePrivacy(getApplicationContext(),true);
            SDKInitializer.initialize(getApplicationContext());
            SDKInitializer.setCoordType(CoordType.BD09LL);
            LocationClient.setAgreePrivacy(true);
            // 注册 SDK 广播监听者
            RegisterBroadcast();
            return R.layout.activity_map;
        }
    
        @Override
        protected void init(Bundle savedInstanceState) throws Exception {
    
            setTitle("打卡签到");
    
            setTitleBack(true);
    
            initBaiduMap();     //1、初始化地图
    
            getLocationClientOption();//2、定位开启
    
            mHandler.post(run);//设置系统时间
    
            mDistance_tv = (TextView) findViewById(R.id.distance_tv);
            mTime_tv = (TextView) findViewById(R.id.arriver_timetv);
            commit_bt = (RelativeLayout) findViewById(R.id.arriver_bt);
            commit_bt.setOnClickListener(this);
        }
    
        /**
         * 初始化地图
         */
        private void initBaiduMap() {
            mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);//获取传感器管理服务
            mMapView = (MapView) findViewById(R.id.mapview);
            mBaiduMap = mMapView.getMap();
            mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
            mBaiduMap.setMyLocationEnabled(true);
        }
    
        //设置打卡目标范围圈
        private void setCircleOptions() {
            if (mDestinationPoint == null) return;
            OverlayOptions ooCircle = new CircleOptions().fillColor(0x4057FFF8)
                    .center(mDestinationPoint).stroke(new Stroke(1, 0xB6FFFFFF)).radius(DISTANCE);
            mBaiduMap.addOverlay(ooCircle);
        }
    
        /***
         * 定位选项设置
         * @return
         */
        public void getLocationClientOption() throws Exception {
            mOption = new LocationClientOption();
            mOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选,默认高精度,设置定位模式,高精度,低功耗,仅设备
            mOption.setCoorType("bd09ll");//可选,默认gcj02,设置返回的定位结果坐标系,如果配合百度地图使用,建议设置为bd09ll;
            mOption.setScanSpan(2000);//可选,默认0,即仅定位一次,设置发起连续定位请求的间隔需要大于等于1000ms才是有效的
            mOption.setIsNeedAddress(true);//可选,设置是否需要地址信息,默认不需要
            mOption.setIsNeedLocationDescribe(true);//可选,设置是否需要地址描述
            mOption.setNeedDeviceDirect(true);//可选,设置是否需要设备方向结果
            mOption.setLocationNotify(true);//可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果
            mOption.setIgnoreKillProcess(true);//可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死
            mOption.setIsNeedLocationDescribe(false);//可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近”
            mOption.setIsNeedLocationPoiList(false);//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到
            mOption.SetIgnoreCacheException(false);//可选,默认false,设置是否收集CRASH信息,默认收集
            mOption.setOpenGps(true);//可选,默认false,设置是否开启Gps定位
            mOption.setIsNeedAltitude(false);//可选,默认false,设置定位时是否需要海拔信息,默认不需要,除基础定位版本都可用
            client = new LocationClient(this);
            client.setLocOption(mOption);
            client.registerLocationListener(BDAblistener);
            client.start();
        }
    
        /***
         * 接收定位结果消息,并显示在地图上
         */
        private BDAbstractLocationListener BDAblistener = new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {
                //定位方向
                mCurrentLat = location.getLatitude();
                mCurrentLon = location.getLongitude();
                //骑手定位
                locData = new MyLocationData.Builder()
                        .direction(mCurrentDirection).latitude(location.getLatitude())
                        .longitude(location.getLongitude()).build();
                mBaiduMap.setMyLocationData(locData);
                mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                        MyLocationConfiguration.LocationMode.NORMAL, true, null));
                //更改UI
                Message message = new Message();
                message.obj = location;
                mHandler.sendMessage(message);
            }
        };
    
        /**
         * 处理连续定位的地图UI变化
         */
        private Handler mHandler = new Handler(Looper.getMainLooper()) {
            @SuppressLint("HandlerLeak")
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                BDLocation location = (BDLocation) msg.obj;
                LatLng LocationPoint = new LatLng(location.getLatitude(), location.getLongitude());
                //打卡范围
                mDestinationPoint = new LatLng(location.getLatitude() * 1.0001, location.getLongitude() * 1.0001);//假设公司坐标
                setCircleOptions();
                //计算两点距离,单位:米
                mDistance = DistanceUtil.getDistance(mDestinationPoint, LocationPoint);
                if (mDistance <= DISTANCE) {
                    //显示文字
                    setTextOption(mDestinationPoint, "您已在打卡范围内", "#7ED321");
                    //目的地图标
                    setMarkerOptions(mDestinationPoint, R.drawable.arrive_icon);
                    //按钮颜色
                    commit_bt.setBackgroundDrawable(getResources().getDrawable(R.drawable.restaurant_btbg_yellow));
                    mBaiduMap.setMyLocationEnabled(false);
                } else {
                    setTextOption(LocationPoint, "您不在打卡范围之内", "#FF6C6C");
                    setMarkerOptions(mDestinationPoint, R.drawable.restaurant_icon);
                    commit_bt.setBackgroundDrawable(getResources().getDrawable(R.drawable.restaurant_btbg_gray));
                    mBaiduMap.setMyLocationEnabled(true);
                }
                mDistance_tv.setText("距离目的地:" + mDistance + "米");
                //缩放地图
                setMapZoomScale(LocationPoint);
            }
        };
    
        /**
         * 添加地图文字
         *
         * @param point
         * @param str
         * @param color 字体颜色
         */
        private void setTextOption(LatLng point, String str, String color) {
            //使用MakerInfoWindow
            if (point == null) return;
            TextView view = new TextView(getApplicationContext());
            view.setBackgroundResource(R.drawable.map_textbg);
            view.setPadding(0, 23, 0, 0);
            view.setTypeface(Typeface.DEFAULT_BOLD);
            view.setTextSize(14);
            view.setGravity(Gravity.CENTER);
            view.setText(str);
            view.setTextColor(Color.parseColor(color));
            mInfoWindow = new InfoWindow(view, point, 170);
            mBaiduMap.showInfoWindow(mInfoWindow);
        }
    
        /**
         * 设置marker覆盖物
         *
         * @param ll   坐标
         * @param icon 图标
         */
        private void setMarkerOptions(LatLng ll, int icon) {
            if (ll == null) return;
            BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(icon);
            MarkerOptions ooD = new MarkerOptions().position(ll).icon(bitmap);
            mBaiduMap.addOverlay(ooD);
        }
    
        //改变地图缩放
        private void setMapZoomScale(LatLng ll) {
            if (mDestinationPoint == null) {
                mZoomScale = getZoomScale(ll);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngZoom(ll, mZoomScale));//缩放
            } else {
                mZoomScale = getZoomScale(ll);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngZoom(mCenterPos, mZoomScale));//缩放
            }
        }
    
        /**
         * 获取地图的中心点和缩放比例
         *
         * @return float
         */
        private float getZoomScale(LatLng LocationPoint) {
            double maxLong;    //最大经度
            double minLong;    //最小经度
            double maxLat;     //最大纬度
            double minLat;     //最小纬度
            List<Double> longItems = new ArrayList<Double>();    //经度集合
            List<Double> latItems = new ArrayList<Double>();     //纬度集合
    
            if (null != LocationPoint) {
                longItems.add(LocationPoint.longitude);
                latItems.add(LocationPoint.latitude);
            }
            if (null != mDestinationPoint) {
                longItems.add(mDestinationPoint.longitude);
                latItems.add(mDestinationPoint.latitude);
            }
    
            maxLong = longItems.get(0);    //最大经度
            minLong = longItems.get(0);    //最小经度
            maxLat = latItems.get(0);     //最大纬度
            minLat = latItems.get(0);     //最小纬度
    
            for (int i = 0; i < longItems.size(); i++) {
                maxLong = Math.max(maxLong, longItems.get(i));   //获取集合中的最大经度
                minLong = Math.min(minLong, longItems.get(i));   //获取集合中的最小经度
            }
    
            for (int i = 0; i < latItems.size(); i++) {
                maxLat = Math.max(maxLat, latItems.get(i));   //获取集合中的最大纬度
                minLat = Math.min(minLat, latItems.get(i));   //获取集合中的最小纬度
            }
            double latCenter = (maxLat + minLat) / 2;
            double longCenter = (maxLong + minLong) / 2;
            int jl = (int) getDistance(new LatLng(maxLat, maxLong), new LatLng(minLat, minLong));//缩放比例参数
            mCenterPos = new LatLng(latCenter, longCenter);   //获取中心点经纬度
            int zoomLevel[] = {2500000, 2000000, 1000000, 500000, 200000, 100000,
                    50000, 25000, 20000, 10000, 5000, 2000, 1000, 500, 100, 50, 20, 0};
            int i;
            for (i = 0; i < 18; i++) {
                if (zoomLevel[i] < jl) {
                    break;
                }
            }
            float zoom = i + 4;
            return zoom;
        }
    
        /**
         * 缩放比例参数
         *
         * @param var0
         * @param var1
         * @return
         */
        public double getDistance(LatLng var0, LatLng var1) {
            if (var0 != null && var1 != null) {
                Point var2 = CoordUtil.ll2point(var0);
                Point var3 = CoordUtil.ll2point(var1);
                return var2 != null && var3 != null ? CoordUtil.getDistance(var2, var3) : -1.0D;
            } else {
                return -1.0D;
            }
        }
    
        @Override
        public void onSensorChanged(SensorEvent sensorEvent) {
            double x = sensorEvent.values[SensorManager.DATA_X];
            if (Math.abs(x - lastX) > 1.0) {
                mCurrentDirection = (int) x;
                locData = new MyLocationData.Builder()
                        // 此处设置开发者获取到的方向信息,顺时针0-360
                        .direction(mCurrentDirection).latitude(mCurrentLat)
                        .longitude(mCurrentLon).build();
                mBaiduMap.setMyLocationData(locData);
            }
            lastX = x;
        }
    
        @Override
        public void onAccuracyChanged(Sensor sensor, int i) {
    
        }
    
        /**
         * 设置系统时间
         */
        private Runnable run = new Runnable() {
            @Override
            public void run() {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");// HH:mm:ss
                Date date = new Date(System.currentTimeMillis());//获取当前时间
                mTime_tv.setText(simpleDateFormat.format(date)); //更新时间
                mHandler.postDelayed(run, 1000);
            }
        };
    
        @Override
        public void onClick(View view) {
            if (view.getId() == R.id.arriver_bt) {
                if (mDistance <= DISTANCE) {
                    Toast.makeText(this, "打卡成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "打卡失败", Toast.LENGTH_SHORT).show();
                }
    
            }
        }
    
        @Override
        protected void onDestroy() {
            if (BDAblistener != null) {
                client.unRegisterLocationListener(BDAblistener);
    
            }
            if (client != null && client.isStarted()) {
                client.stop();
            }
            mMapView.onDestroy();
            mMapView = null;
            mHandler.removeCallbacks(run);
            super.onDestroy();
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            mMapView.onResume();
            //为系统的方向传感器注册监听器
            mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                    SensorManager.SENSOR_DELAY_UI);
        }
    
        @Override
        protected void onPause() {
            super.onPause();
            mMapView.onPause();
        }
    
        @Override
        protected void onStop() {
            super.onStop();
            //取消注册传感器监听
            mSensorManager.unregisterListener(this);
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
    • 329
    • 330
    • 331
    • 332
    • 333
    • 334
    • 335
    • 336
    • 337
    • 338
    • 339
    • 340
    • 341
    • 342
    • 343
    • 344
    • 345
    • 346
    • 347
    • 348
    • 349
    • 350
    • 351
    • 352
    • 353
    • 354
    • 355
    • 356
    • 357
    • 358
    • 359
    • 360
    • 361
    • 362
    • 363
    • 364
    • 365
    • 366
    • 367
    • 368
    • 369
    • 370
    • 371
    • 372
    • 373
    • 374
    • 375
    • 376
    • 377
    • 378
    • 379
    • 380
    • 381
    • 382
    • 383
    • 384
    • 385
    • 386
    • 387
    • 388
    • 389
    • 390
    • 391
    • 392
    • 393
    • 394
    • 395
    • 396
    • 397
    • 398
    • 399
    • 400
    • 401
    • 402
    • 403
    • 404
    • 405

    8.相关图片

    arrive_icon:
    在这里插入图片描述
    back_whait:
    在这里插入图片描述
    ic_launcher:
    在这里插入图片描述
    ic_launcher_round:
    在这里插入图片描述
    map_textbg:
    在这里插入图片描述
    message_icon:
    在这里插入图片描述
    restaurant_btbg_gray:
    在这里插入图片描述
    restaurant_btbg_yellow:
    在这里插入图片描述
    restaurant_icon:
    在这里插入图片描述

    9.修改AndroidManifest.xml文件

    (1)添加权限

      <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
      <uses-permission android:name="android.permission.INTERNET" />
      <uses-permission android:name="android.permission.READ_PHONE_STATE" />
      <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
      <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
      <uses-permission android:name="android.permission.WRITE_SETTINGS"
            tools:ignore="ProtectedPermissions" />
      <uses-permission android:name="android.permission.REAL_GET_TASKS"
            tools:ignore="ProtectedPermissions" />
      <uses-permission android:name="android.permission.CAMERA" />
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    (2)在application 标签中写入代码密钥配置,value中的值为AK,修改为自己在百度地图申请的

    在这里插入图片描述

     <meta-data
                android:name="com.baidu.lbsapi.API_KEY"
                android:value="ionrVhbqggVl3xu3Cf4C88teGrfGshFQ" />
    
    • 1
    • 2
    • 3

    四、资源下载

    下载地址:Android开发之百度地图定位打卡

  • 相关阅读:
    Spring Framework :WebClient 取代 RestTemplate
    WorkManager的学习二
    Android Studio 创建项目不自动生成BuildConfig文件
    【测试工具】Fiddler
    linux系统配置之单一网卡配置多个不同网段IP(centos)
    关于网站安全的一些讨论
    数据结构---顺序表,链表
    Servlet的基本使用
    java计算机毕业设计基于安卓Android微信小程序的共享单车租赁系统uniApp
    网站有反爬机制就爬不了数据?那是你不会【反】反爬!道高一尺魔高一丈啊!
  • 原文地址:https://blog.csdn.net/qq_61963074/article/details/126761914