安卓百度地图sdk定位的使用

「这是我参与2022首次更文挑战的第28天,活动详情查看:2022首次更文挑战

进入百度地图开放平台 百度地图开放平台 | 百度地图API SDK | 地图开发 创建应用这写简单没有技术含量的教程就跳过,主要总结使用中的细节

集成sdk

在Project的build.gradle文件中配置repositories,添加mavenCentral仓库地址

1645886063(1).png

allprojects {
    repositories {
        mavenCentral()
    }
}
复制代码

导入依赖

接着再app下的build.gradle导入依赖

implementation 'com.baidu.lbsyun:BaiduMapSDK_Search:7.4.0'//检索组件
implementation 'com.baidu.lbsyun:BaiduMapSDK_Util:7.4.0'//工具组件
implementation 'com.baidu.lbsyun:BaiduMapSDK_Location:9.1.8'//基础定位组件
implementation 'com.baidu.lbsyun:BaiduMapSDK_Map-AllNavi:7.4.0'//导航
implementation 'com.baidu.lbsyun:NaviTts:2.5.5'//TTS语言
复制代码

记得获取SHA1配置 Key哦,官网有教程,这里就不讲了

BaiduMap

获取地图控件引用

mMapView = binding.bmapView;
mBaiduMap = mMapView.getMap();
mBaiduMap.setMyLocationEnabled(true);
复制代码

获取地图控件引用

定位

定位初始化

//定位初始化 new LocationClient(getContext()) //通过LocationClientOption设置LocationClient相关参数 LocationClientOption option = new LocationClientOption() // 打开gps option.setOpenGps(true) // 设置坐标类型 option.setCoorType("bd09ll")

private void initMap() {
    //获取地图控件引用
    mMapView = binding.bmapView;
    mBaiduMap = mMapView.getMap();
    mBaiduMap.setMyLocationEnabled(true);
    //定位初始化
    mLocationClient = new LocationClient(getContext());
    //通过LocationClientOption设置LocationClient相关参数
    LocationClientOption option = new LocationClientOption();
    // 打开gps
    option.setOpenGps(true);
    // 设置坐标类型
    option.setCoorType("bd09ll");
    option.setScanSpan(1000);
    option.setIsNeedAddress(true);
     option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
    // option.setLocationMode(LocationClientOption.LocationMode.Battery_Saving);
    //option.setLocationMode(LocationClientOption.LocationMode.Device_Sensors);

    //设置locationClientOption
    mLocationClient.setLocOption(option);

    //注册LocationListener监听器
    MyLocationListeners myLocationListener = new MyLocationListeners();
    mLocationClient.registerLocationListener(myLocationListener);
    //开启地图定位图层
    mLocationClient.start();
}
复制代码

接着实现抽象位置监听器

public class MyLocationListeners extends BDAbstractLocationListener {
    @Override
    public void onReceiveLocation(BDLocation location) {
        //mapView 销毁后不在处理新接收的位置
        if (location == null || mMapView == null) {
            return;
        }
        // 如果是第一次定位
        LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
        if (isFirstLocate) {
            isFirstLocate = false;
            //给地图设置状态
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(ll));
        }

        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(location.getRadius())
                // 此处设置开发者获取到的方向信息,顺时针0-360
                .direction(location.getDirection())
                .latitude(location.getLatitude())
                .longitude(location.getLongitude())
                .build();
        mBaiduMap.setMyLocationData(locData);
        curr_city = location.getCity();

    }
}
复制代码
通过BDLocation定位的回调获取详细信息
location.getCity() 城市
location.getAddrStr() 地点
location.getLatitude() 经度
location.getLongitude() 纬度

需要再LocationClientOption设置setIsNeedAddress才能获取到经纬度,否则返回空

LocationClientOption option = new LocationClientOption();
option.setIsNeedAddress(true);
复制代码

实现地图生命周期管理

防止内存泄漏

@Override
public void onResume() {
    super.onResume();

    mMapView.onResume();
}

@Override
public void onPause() {
    super.onPause();
    mMapView.onPause();
}

@Override
public void onDestroyView() {
    mLocationClient.stop();
    mBaiduMap.setMyLocationEnabled(false);
    mMapView.onDestroy();
    mMapView = null;
    super.onDestroyView();
    binding = null;
}
复制代码

处理sug检索

edit编辑框

<EditText
    android:id="@+id/et_search"
    ...
    android:hint="输入目的地"

   />
复制代码

image.png

输入监听

etSearch.addTextChangedListener(
        new TextWatcher() {
        ...
           @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String search = etSearch.getText().toString();
                mSuggestionSearch.requestSuggestion(new SuggestionSearchOption()
                        .city(BDLocation定位的回调获取到当前的城市}
                        .keyword(search));
                //如果空就隐藏列表
                if (search.equals("")) {
                    card.setVisibility(View.GONE);
                }
            }
        });
     ...
复制代码

card里面放入RecyclerView这个简单就不贴了哦

OnGetSuggestionResultListener listener = suggestionResult -> {
    //处理sug检索结果
    if (suggestionResult != null && suggestionResult.getAllSuggestions() != null) {
        placeList.clear();

        for (SuggestionResult.SuggestionInfo info : suggestionResult.getAllSuggestions()) {
            PlacehBean bean = new PlacehBean();
            bean.setCity(info.city);
            bean.setAddress(info.address);
            bean.setLatitude(info.getPt().latitude);
            bean.setLongitude(info.getPt().longitude);
            placeList.add(bean);

        }
      //刷新RecyclerView
        mSearcPlacehAdapter.notifyDataSetChanged();
        card.setVisibility(View.VISIBLE);
    } else {
        Log.d(TAG, "处理sug检索结果 null");
    }
};
mSuggestionSearch.setOnGetSuggestionResultListener(listener);
复制代码

ezgif.com-gif-maker (18).gif

热力图

利用FavoriteManager来实现热区的添加,添加的数据是保存再本地的

implements OnMapLongClickListener
复制代码

拿到经纬度

@Override
public void onMapLongClick(LatLng point) {
    mEditLocation.setText(String.valueOf(point.latitude) + "," + String.valueOf(point.longitude));
    MarkerOptions ooA = new MarkerOptions().position(point).icon(bitmapA);
    mBaiduMap.clear();
    mBaiduMap.addOverlay(ooA);
}
复制代码

保存

FavoritePoiInfo info = new FavoritePoiInfo();
info.poiName(mEditName.getText().toString());

LatLng latLng;
try {
    String strLatLng = mEditLocation.getText().toString();
    String lat = strLatLng.substring(0, strLatLng.indexOf(","));
    String lng = strLatLng.substring(strLatLng.indexOf(",") + 1);
    latLng = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));
    info.pt(latLng);
    if (FavoriteManager.getInstance().add(info) == 1) {
        Toast.makeText(ManageRiskPlace.this, "添加成功", Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(ManageRiskPlace.this, "添加失败", Toast.LENGTH_LONG).show();
        return;
    }

} catch (Exception e) {
    Toast.makeText(ManageRiskPlace.this, "坐标解析错误", Toast.LENGTH_LONG).show();
    return;
}
复制代码

在地图上更新当前最新添加的点

mBaiduMap.clear();
List<FavoritePoiInfo> list = FavoriteManager.getInstance().getAllFavPois();
if(null == list || list.size() == 0){
    return;
}
MarkerOptions option = new MarkerOptions().icon(bitmapA).position(list.get(0).getPt());
Bundle bundle = new Bundle();
bundle.putString("id", list.get(0).getID());
option.extraInfo(bundle);
Marker currentMarker = (Marker) mBaiduMap.addOverlay(option);
markers.add(currentMarker);
复制代码

显示热力图

初始化

private HeatMap mHeatmap;
List<LatLng> latLngHeatmapList = new ArrayList<>();
复制代码

获取全部添加的热力区并显示热区

public void getAllClick(View v) {
    mBaiduMap.clear();
    List<FavoritePoiInfo> list = FavoriteManager.getInstance().getAllFavPois();
    if (list == null || list.size() == 0) {
        Toast.makeText(ManageRiskPlace.this, "没有收藏点", Toast.LENGTH_LONG).show();
        return;
    }
    latLngHeatmapList.clear();
    // 绘制在地图
    markers.clear();
    for (int i = 0; i < list.size(); i++) {
        MarkerOptions option = new MarkerOptions().icon(bitmapA).position(list.get(i).getPt());
        Bundle b = new Bundle();
        b.putString("id", list.get(i).getID());
        option.extraInfo(b);
        markers.add((Marker) mBaiduMap.addOverlay(option));

        latLngHeatmapList.add(list.get(i).getPt());
    }
//添加热区
    addHeatMap();
}
复制代码

加载热区的数据 latLngHeatmapList.add(list.get(i).getPt());


//添加热区
private void addHeatMap() {
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (!isDestroy) {
                mBaiduMap.addHeatMap(mHeatmap);
            }
        }
    };
    new Thread() {
        @Override
        public void run() {
            super.run();
            mHeatmap = new HeatMap.Builder().data(latLngHeatmapList).radius(36).build();
            handler.sendEmptyMessage(0);
        }
    }.start();
}
复制代码

radius(热区半径) 1961f651c9e4304b0725d2f431a0b20.jpg

猜你喜欢

转载自juejin.im/post/7069040204773851173