“This is my 28th day of participating in the First Challenge 2022. For details: First Challenge 2022

Enter the baidu map open platform Baidu map open platform | | baidu map API SDK development to create applications that write simple no technical content of the tutorial, skip, mainly summarizes the details of the use

To integrate the SDK

Configure repositories in the Project build.gradle file and add the repository address of mavenCentral

allprojects {
    repositories {
        mavenCentral()
    }
}
Copy the code

Import dependence

Then import the dependencies from build.gradle in app

implementation 'com. Baidu. Lbsyun: BaiduMapSDK_Search: 7.4.0'// Retrieve the component
implementation 'com. Baidu. Lbsyun: BaiduMapSDK_Util: 7.4.0'// Tool components
implementation 'com. Baidu. Lbsyun: BaiduMapSDK_Location: 9.1.8'// Base positioning components
implementation 'com. Baidu. Lbsyun: BaiduMapSDK_Map - AllNavi: 7.4.0'/ / navigation
implementation 'com. Baidu. Lbsyun: NaviTts: 2.5.5'/ / the TTS language
Copy the code

Remember to obtain SHA1 configuration Key oh, the official website has a tutorial, here will not talk about

BaiduMap

Gets a map control reference

mMapView = binding.bmapView;
mBaiduMap = mMapView.getMap();
mBaiduMap.setMyLocationEnabled(true);
Copy the code

Gets a map control reference

positioning

Location initialization

// Initialize new LocationClient(getContext()) // Set the LocationClient parameter LocationClientOption option = new via LocationClientOption // Enable GPS option.setopengps (true) // Set coordinate type option.setcoorType (“bd09ll”)

private void initMap(a) {
    // Get the map control reference
    mMapView = binding.bmapView;
    mBaiduMap = mMapView.getMap();
    mBaiduMap.setMyLocationEnabled(true);
    // Location initialization
    mLocationClient = new LocationClient(getContext());
    // Set parameters related to the LocationClient using LocationClientOption
    LocationClientOption option = new LocationClientOption();
    / / open the GPS
    option.setOpenGps(true);
    // Set the coordinate type
    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);

    / / set locationClientOption
    mLocationClient.setLocOption(option);

    // Register the LocationListener listener
    MyLocationListeners myLocationListener = new MyLocationListeners();
    mLocationClient.registerLocationListener(myLocationListener);
    // Turn on the map positioning layer
    mLocationClient.start();
}
Copy the code

Next, implement the abstract location listener

public class MyLocationListeners extends BDAbstractLocationListener { @Override public void onReceiveLocation(BDLocation Location) {/ / mapView destroyed the placement of the new receiver is absent after the if (location = = null | | mMapView = = null) {return; } // LatLng ll = new LatLng(location.getlatitude (), location.getlongitude ()); if (isFirstLocate) { isFirstLocate = false; / / to map Settings mBaiduMap. AnimateMapStatus (MapStatusUpdateFactory. NewLatLng (ll)); } MyLocationData locData = new mylocationData.builder ().accuracy(location.getradius ()) Clockwise 0-360.direction (location.getdirection ()).latitude(location.getlatitude ()).longitude(location.getlongitude ()) .build(); mBaiduMap.setMyLocationData(locData); curr_city = location.getCity(); }}Copy the code
Get the details via the callback located by BDLocation
location.getCity() city
location.getAddrStr() place
location.getLatitude() longitude
location.getLongitude() latitude

You need to set setIsNeedAddress again to LocationClientOption to get the latitude and longitude, otherwise return null

LocationClientOption option = new LocationClientOption();
option.setIsNeedAddress(true);
Copy the code

Implement map lifecycle management

Preventing memory leaks

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

    mMapView.onResume();
}

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

@Override
public void onDestroyView(a) {
    mLocationClient.stop();
    mBaiduMap.setMyLocationEnabled(false);
    mMapView.onDestroy();
    mMapView = null;
    super.onDestroyView();
    binding = null;
}
Copy the code

Handles SUG retrieval

Edit edit box

<EditText
    android:id="@+id/et_search"
    .
    android:hint="Input destination"

   />
Copy the code

Input to monitor

etSearch.addTextChangedListener(
        new TextWatcher() {
        ...
           @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String search = etSearch.getText().toString();
                mSuggestionSearch.requestSuggestion(newSuggestionSearchOption().city(BDLocation location callbacks get to the current city}.keyword(search));// Hide the list if empty
                if (search.equals("")) { card.setVisibility(View.GONE); }}}); .Copy the code

Add RecyclerView into card this simple will not paste oh

OnGetSuggestionResultListener listener = suggestionResult -> {
    // Process suG search results
    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);

        }
      / / refresh RecyclerView
        mSearcPlacehAdapter.notifyDataSetChanged();
        card.setVisibility(View.VISIBLE);
    } else {
        Log.d(TAG, "Handle SUG search result null"); }}; mSuggestionSearch.setOnGetSuggestionResultListener(listener);Copy the code

Heat map

Using FavoriteManager to implement the addition of hot zone, add data is saved locally

implements OnMapLongClickListener
Copy the code

Get latitude and longitude

@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);
}
Copy the code

save

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."Added successfully", Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(ManageRiskPlace.this."Add failed", Toast.LENGTH_LONG).show();
        return; }}catch (Exception e) {
    Toast.makeText(ManageRiskPlace.this."Coordinate resolution error", Toast.LENGTH_LONG).show();
    return;
}
Copy the code

Update the current newly added point on the map

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);
Copy the code

Display heat map

Initialize the

private HeatMap mHeatmap;
List<LatLng> latLngHeatmapList = new ArrayList<>();
Copy the code

Get all added heat zones and display heat zones

public void getAllClick(View v) {
    mBaiduMap.clear();
    List<FavoritePoiInfo> list = FavoriteManager.getInstance().getAllFavPois();
    if (list == null || list.size() == 0) {
        Toast.makeText(ManageRiskPlace.this."No collection points.", Toast.LENGTH_LONG).show();
        return;
    }
    latLngHeatmapList.clear();
    // Draw on the map
    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());
    }
// Add hot zones
    addHeatMap();
}
Copy the code

Latlngheatmaplist.add (list.get(I).getpt ()));


// Add hot zones
private void addHeatMap(a) {
    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(a) {
            super.run();
            mHeatmap = new HeatMap.Builder().data(latLngHeatmapList).radius(36).build();
            handler.sendEmptyMessage(0);
        }
    }.start();
}
Copy the code

Radius (hot zone radius)