安卓利用百度地图实现定位

1、下载百度地图的SDK
下载地址:http://lbsyun.baidu.com/index.php?title=android-locsdk/geosdk-android-download
2、申请key值
注册百度账号——>登录百度地图官网——>控制台—–>创建应用
获取key(也就是AK)的具体方法的官网地址 :http://lbsyun.baidu.com/apiconsole/key
3、通过解压得到.jar文件并放到libs文件中(copy也可以),手动添加到依赖库中(右键Add—-)
4.在AndroidManifest的Application中添加服务:


        <meta-data
            android:name="com.baidu.lbsapi.API_KEY"
            android:value="AK" />//在百度官网自行申请

        <service
            android:name="com.baidu.location.f"
            android:enabled="true"
            android:process=":remote" />

5.添加权限

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <!-- provider的权限 -->
    <uses-permission android:name="android.permission.ACCESS_GPS" /> <!-- 获取精确gps位置 -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- 获取粗略位置 -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- 允许程序访问额外的定位提供者指令获取模拟定位信息 -->
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" /> <!-- 网络链接 -->
    <uses-permission android:name="android.permission.INTERNET" />

6.具体实现:
布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:background="@drawable/round_button_click"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp">
        <Button
            android:id="@+id/btn_geilocation"
            android:onClick="btn_getLocation"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/round_button"
            android:layout_marginLeft="10dp"
            android:layout_gravity="center"
            android:text="点击刷新当前位置"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignRight="@+id/btn_geilocation"
            android:gravity="center"
            android:layout_gravity="center"
            android:text="--------------------------------------------------------" />
    </LinearLayout>

    <TextView
        android:id="@+id/text_location"
        android:layout_width="wrap_content"
        android:layout_height="35dp"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:text="您目前在:" />
    <EditText
        android:id="@+id/editext_location"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginTop="30dp"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:background="@drawable/round_button"
        android:hint="请输入您要去的地方"/>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="30dp">
        <Button
            android:layout_width="wrap_content"
            android:layout_marginLeft="50dp"
            android:layout_height="40dp"
            android:layout_centerInParent="true"
            android:background="@drawable/round_button"
            android:onClick="btn_confirm"
            android:text="确定"/>
    </RelativeLayout>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginBottom="10dp"
        android:background="@drawable/map"/>

</LinearLayout>




在这里插入图片描述
实现代码:

public class Location extends AppCompatActivity {

    //定义数据
    //定位都要通过LocationManager这个类实现
    private LocationManager locationManager;
    private String provider; //是否为网络位置控制器或GPS定位
    //当前可用的位置控制器
    static BDLocation lastLocation = null;
    private LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();//自定义方法
    List<String> list;
    TextView textView;//当前地址
    EditText editText_Location;//编辑目的地
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location);
        ActionBar actionBar=getSupportActionBar();
        if (actionBar!=null){
            actionBar.hide();
        }
        editText_Location=findViewById(R.id.editext_location);
        textView=findViewById(R.id.text_location);
        showMapWithLocationClient();
        Log.d("进入系统", "ceshi");

    }
    /**
     * 初始化定位参数配置
     */

    private void showMapWithLocationClient() {
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener((BDLocationListener) myListener);

        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// open gps
        option.setCoorType("bd09ll");
        //可选,默认0,即仅定位一次,设置定时发起定位请求的间隔需要大于等于1000ms才是有效的
        /*
         * 定位sdk提供2种定位模式,定时定位和app主动请求定位。
         * setScanSpan < 1000 则为 app主动请求定位;
         * setScanSpan >=1000,则为定时定位模式(setScanSpan的值就是定时定位的时间间隔))
         * 定时定位模式中,定位sdk会按照app设定的时间定位进行位置更新,定时回调定位结果。此种定位模式适用于希望获得连续定位结果的情况。
         * 对于单次定位类应用,或者偶尔需要一下位置信息的app,可采用app主动请求定位这种模式。*/
        //option.setScanSpan(2000);
        //可选,设置是否需要地址信息,默认不需要
        option.setIsNeedAddress(true);
        //可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近”
        option.setIsNeedLocationDescribe(true);
        //设置是否需要返回位置POI信息,可以在BDLocation.getPoiList()中得到数据
        option.setIsNeedLocationPoiList(true);
        //在网络定位时,是否需要设备方向 true:需要 ; false:不需要
        option.setNeedDeviceDirect(true);
        //可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死
        option.setIgnoreKillProcess(false);
        //可选,默认false,设置是否收集CRASH信息,默认收集
        option.SetIgnoreCacheException(false);
        //可选,默认false,设置是否需要过滤gps仿真结果,默认需要
        option.setEnableSimulateGps(false);
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        mLocClient.setLocOption(option);
        mLocClient.start();
    }
    /**
     * 实现定位回调
     */
    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null) {
                return;
            }
            if (lastLocation != null) {
                if (lastLocation.getLatitude() == location.getLatitude() && lastLocation.getLongitude() == location.getLongitude()) {
                    Log.d("map", "same location, skip refresh");
                    // mMapView.refresh(); //need this refresh?
                    return;
                }
            }
            String addrlg; //定位结果
            lastLocation = location;
            if (!TextUtils.isEmpty(lastLocation.getLocationDescribe())){
                addrlg = lastLocation.getLocationDescribe();
            }else if (lastLocation.hasAddr()) {
                addrlg = lastLocation.getAddrStr();
            }else {
                addrlg = "定位失败...";
                return;
            }
            String city = lastLocation.getCity();
            double lat = lastLocation.getLatitude();
            double lot = lastLocation.getLongitude();
//            ShareUtil.sharedPstring("nowla",String.valueOf(lat));
//            ShareUtil.sharedPstring("nowlo",String.valueOf(lot));
//            ShareUtil.sharedPstring("nowad",addrlg);
            Log.i("lgq","............"+addrlg+"........"+lat+"......."+lot);
            String addr = location.getAddrStr();    //获取详细地址信息
            String country = location.getCountry();    //获取国家
            String province = location.getProvince();    //获取省份
            //String city = location.getCity();    //获取城市
            String district = location.getDistrict();    //获取区县
            String street = location.getStreet();    //获取街道信息
            String adcode = location.getAdCode();    //获取adcode
            String town = location.getTown();    //获取乡镇信息
            textView.setText("");
            textView.append(country+province+district+street+town+addrlg);
            Log.d("刷新了一次", "onReceiveLocation: ");
//            Toast.makeText(MainActivity.this, addrlg+"........"+lat, Toast.LENGTH_SHORT).show();
//            tv_bottom_bar_me.setText(addrlg);
//           mBaiduMap.animateMapStatus(u);
        }
    }
    public void btn_getLocation(View view){//点击获取当前位置
        showMapWithLocationClient();
    }
    public void btn_confirm(View view) {
        final String destination =editText_Location.getText().toString();

        if (destination.length()==0){
            Toast.makeText(this,"请注意目标地址为空",Toast.LENGTH_LONG).show();
            return;
        }
        new AlertDialog.Builder(Location.this).setTitle("注意")//.setIcon(R.drawable.)
                .setMessage("请选择地图软件")
                .setPositiveButton("高德",new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog,int whichButton){
                        if (MapNaviUtils.isGdMapInstalled()) {
                            MapNaviUtils.openGaoDeNavi(Location.this,0,0,null,31.239666,121.499809,destination);
//                            MapUtils.openMap(mContext,"com.autonavi.minimap",new LatLng(31.33260711060764,121.54777721524306,"CCB"));
                        }else {
                            Toast.makeText(Location.this, "您还未安装高德地图", Toast.LENGTH_LONG).show();
                            new AlertDialog.Builder(Location.this)
                                    .setMessage("下载高德地图?")
                                    .setNegativeButton("取消", null)
                                    .setPositiveButton("下载",new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(MapNaviUtils.DOWNLOAD_GAODE_MAP)));
                                        }
                                    }).show();
                        }
                    }
                })
                .setNegativeButton("百度",new DialogInterface.OnClickListener(){

                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (MapNaviUtils.isBaiduMapInstalled()) {
                            MapNaviUtils.openBaiDuNavi(Location.this, 0, 0, null, 31.239666, 121.499809, "上海外滩");
//                            MapUtils.openMap(mContext,"com.baidu.BaiduMap",new LatLng(31.33260715160764,121.54777723124306,"CCB"));
                        } else {
                            Toast.makeText(Location.this, "您还未安装百度地图", Toast.LENGTH_LONG).show();

                            new AlertDialog.Builder(Location.this)
                                    .setMessage("下载百度地图?")
                                    .setNegativeButton("取消", null)
                                    .setPositiveButton("下载",new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(MapNaviUtils.DOWNLOAD_BAIDU_MAP)));
                                        }
                                    }).show();
                        }
                    }
                }).create().show();
        }
}

输入目标地址后,可以选择用高德地图或者百度地图打开导航,方便实用
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

发布了47 篇原创文章 · 获赞 13 · 访问量 1639

猜你喜欢

转载自blog.csdn.net/weixin_43605701/article/details/105498899