一、添加权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- 用于进行网络定位 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- 用于访问GPS定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- 这个权限用于进行网络定位 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- 这个权限用于访问GPS定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- 获取访问手机振动器权限,用于导航过程中的震动提示 -->
<uses-permission android:name="android.permission.VIBRATE" /> <!-- 获取摄像头权限,用于AR步行导航 -->
<uses-permission android:name="android.permission.CAMERA" /> <!-- 访问网络,进行地图相关业务数据请求,包括地图数据,路线规划,POI检索等 -->
<uses-permission android:name="android.permission.INTERNET" /> <!-- 获取网络状态,根据网络状态切换进行数据请求网络转换 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- 读取外置存储。如果开发者使用了so动态加载功能并且把so文件放在了外置存储区域,则需要申请该权限,否则不需要 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <!-- 写外置存储。如果开发者使用了离线地图,并且数据写在外置存储区域,则需要申请该权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- 用于进行网络定位 -->
<uses-permission
android:name="android.permission.LOCATION_HARDWARE"
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<meta-data
android:name="com.baidu.lbsapi.API_KEY"
android:value="IsRs1HWLvUvbj7QL33RqGeih6z2G2dYB" /> //写自己的应用AK
<service
android:name="com.baidu.location.f"
android:enabled="true"
android:process=":remote" />
二、在gradle里添加
sourceSets {
main {
jniLibs.srcDir 'libs'
}
}
依赖implementation 'com.android.support:multidex:1.0.3'
三、添加资源
在app下添加libs 在src的main里添加assets资源
四、代码
1.MapApplication(记得注册)
package com.example.baidumap;
import android.app.Application;
import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
public class MapApplication extends Application {
private static volatile MapApplication app;
public static MapApplication getApp() {
return app;
}
@Override
public void onCreate() {
super.onCreate();
app = this;
//在使用SDK各组件之前初始化context信息,传入ApplicationContext
SDKInitializer.initialize(this);
//自4.3.0起,百度地图SDK所有接口均支持百度坐标和国测局坐标,用此方法设置您使用的坐标类型.
//包括BD09LL和GCJ02两种坐标,默认是BD09LL坐标。
SDKInitializer.setCoordType(CoordType.BD09LL);
}
}
2.SDKReceiver
package com.example.baidumap;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.baidu.mapapi.SDKInitializer;
public class SDKReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR)) {
//key验证失败,做相应处理
} else if (action.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK)) {
//key验证成功,做相应处理
}
}
}
4.PoiOverlay
package com.example.baidumap;
import android.os.Bundle;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.search.poi.PoiResult;
import java.util.ArrayList;
import java.util.List;
public class PoiOverlay extends OverlayManager {
private static final int MAX_POI_SIZE = 10;
private PoiResult mPoiResult = null;
/**
* 构造函数
*
* @param baiduMap 该 PoiOverlay 引用的 BaiduMap 对象
*/
public PoiOverlay(BaiduMap baiduMap) {
super(baiduMap);
}
/**
* 设置POI数据
*
* @param poiResult 设置POI数据
*/
public void setData(PoiResult poiResult) {
this.mPoiResult = poiResult;
}
@Override
public final List<OverlayOptions> getOverlayOptions() {
if (mPoiResult == null || mPoiResult.getAllPoi() == null) {
return null;
}
List<OverlayOptions> markerList = new ArrayList<>();
int markerSize = 0;
for (int i = 0; i < mPoiResult.getAllPoi().size() && markerSize < MAX_POI_SIZE; i++) {
if (mPoiResult.getAllPoi().get(i).location == null) {
continue;
}
markerSize++;
Bundle bundle = new Bundle();
bundle.putInt("index", i);
markerList.add(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromAssetWithDpi("Icon_mark" + markerSize + ".png"))
.extraInfo(bundle)
.position(mPoiResult.getAllPoi().get(i).location));
}
return markerList;
}
/**
* 获取该PoiOverlay的poi数据
*
* @return POI数据
*/
public PoiResult getPoiResult() {
return mPoiResult;
}
/**
* 覆写此方法以改变默认点击行为
*
* @param i 被点击的poi在
* {@link PoiResult#getAllPoi()} 中的索引
* @return true--事件已经处理,false--事件未处理
*/
public boolean onPoiClick(int i) {
// if (mPoiResult.getAllPoi() != null
// && mPoiResult.getAllPoi().get(i) != null) {
// Toast.makeText(BMapManager.getInstance().getContext(),
// mPoiResult.getAllPoi().get(i).name, Toast.LENGTH_LONG)
// .show();
// }
return false;
}
@Override
public final boolean onMarkerClick(Marker marker) {
if (!mOverlayList.contains(marker)) {
return false;
}
if (marker.getExtraInfo() != null) {
return onPoiClick(marker.getExtraInfo().getInt("index"));
}
return false;
}
@Override
public boolean onPolylineClick(Polyline polyline) {
return false;
}
}
5.OverlayManager
package com.example.baidumap;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLngBounds;
import java.util.ArrayList;
import java.util.List;
public abstract class OverlayManager implements BaiduMap.OnMarkerClickListener, BaiduMap.OnPolylineClickListener {
BaiduMap mBaiduMap = null;
private List<OverlayOptions> mOverlayOptionList = null;
List<Overlay> mOverlayList = null;
/**
* 通过一个BaiduMap 对象构造
*
* @param baiduMap
*/
public OverlayManager(BaiduMap baiduMap) {
mBaiduMap = baiduMap;
// mBaiduMap.setOnMarkerClickListener(this);
if (mOverlayOptionList == null) {
mOverlayOptionList = new ArrayList<OverlayOptions>();
}
if (mOverlayList == null) {
mOverlayList = new ArrayList<Overlay>();
}
}
/**
* 覆写此方法设置要管理的Overlay列表
*
* @return 管理的Overlay列表
*/
public abstract List<OverlayOptions> getOverlayOptions();
/**
* 将所有Overlay 添加到地图上
*/
public final void addToMap() {
if (mBaiduMap == null) {
return;
}
removeFromMap();
List<OverlayOptions> overlayOptions = getOverlayOptions();
if (overlayOptions != null) {
mOverlayOptionList.addAll(getOverlayOptions());
}
for (OverlayOptions option : mOverlayOptionList) {
mOverlayList.add(mBaiduMap.addOverlay(option));
}
}
/**
* 将所有Overlay 从 地图上消除
*/
public final void removeFromMap() {
if (mBaiduMap == null) {
return;
}
for (Overlay marker : mOverlayList) {
marker.remove();
}
mOverlayOptionList.clear();
mOverlayList.clear();
}
/**
* 缩放地图,使所有Overlay都在合适的视野内
* <p>
* 注: 该方法只对Marker类型的overlay有效
* </p>
*
*/
public void zoomToSpan() {
if (mBaiduMap == null) {
return;
}
if (mOverlayList.size() > 0) {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Overlay overlay : mOverlayList) {
// polyline 中的点可能太多,只按marker 缩放
if (overlay instanceof Marker) {
builder.include(((Marker) overlay).getPosition());
}
}
mBaiduMap.setMapStatus(MapStatusUpdateFactory
.newLatLngBounds(builder.build()));
}
}
}
6.WNaviGuideActivity
package com.example.baidumap;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import androidx.annotation.Nullable;
import com.baidu.mapapi.walknavi.WalkNavigateHelper;
import com.baidu.mapapi.walknavi.adapter.IWRouteGuidanceListener;
import com.baidu.mapapi.walknavi.model.RouteGuideKind;
public class WNaviGuideActivity extends Activity {
private WalkNavigateHelper instance;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//获取WalkNavigateHelper实例
instance = WalkNavigateHelper.getInstance();
//获取诱导页面地图展示View
View view = instance.onCreate(WNaviGuideActivity.this);
if (view != null) {
setContentView(view);
}
instance.startWalkNavi(WNaviGuideActivity.this);
instance.setRouteGuidanceListener(this, new IWRouteGuidanceListener() {
@Override
public void onRouteGuideIconUpdate(Drawable drawable) {
}
@Override
public void onRouteGuideKind(RouteGuideKind routeGuideKind) {
}
@Override
public void onRoadGuideTextUpdate(CharSequence charSequence, CharSequence charSequence1) {
}
@Override
public void onRemainDistanceUpdate(CharSequence charSequence) {
}
@Override
public void onRemainTimeUpdate(CharSequence charSequence) {
}
@Override
public void onGpsStatusChange(CharSequence charSequence, Drawable drawable) {
}
@Override
public void onRouteFarAway(CharSequence charSequence, Drawable drawable) {
}
@Override
public void onRoutePlanYawing(CharSequence charSequence, Drawable drawable) {
}
@Override
public void onReRouteComplete() {
}
@Override
public void onArriveDest() {
}
@Override
public void onIndoorEnd(Message message) {
}
@Override
public void onFinalEnd(Message message) {
}
@Override
public void onVibrate() {
}
});
}
@Override
protected void onResume() {
super.onResume();
instance.resume();
}
@Override
protected void onPause() {
super.onPause();
instance.pause();
}
@Override
protected void onDestroy() {
super.onDestroy();
instance.quit();
}
}
7.布局
<com.baidu.mapapi.map.MapView
android:id="@+id/bmapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true" />
8.MainActivity
package com.example.baidumap;
import android.Manifest;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.PermissionUtils;
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.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.walknavi.WalkNavigateHelper;
import com.baidu.mapapi.walknavi.adapter.IWEngineInitListener;
import com.baidu.mapapi.walknavi.adapter.IWRoutePlanListener;
import com.baidu.mapapi.walknavi.model.WalkRoutePlanError;
import com.baidu.mapapi.walknavi.params.WalkNaviLaunchParam;
import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private MapView mMapView;
private BaiduMap mBaiduMap;
private Button btn_location;
private LocationClient mLocationClient;
private LatLng mUserLatLng;
private UiSettings mUiSettings;
private SDKReceiver mReceiver;
private WalkNaviLaunchParam mParam;
private PoiSearch mPoiSearch;
private MapView bmapView;
private Button btn_poi;
private EditText et_poi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initPer();
showLocation();
setting();
initPoi();
}
private void initPoi() {
mPoiSearch = PoiSearch.newInstance();
OnGetPoiSearchResultListener listener = new OnGetPoiSearchResultListener() {
@Override
public void onGetPoiResult(PoiResult poiResult) {
//检索结果覆盖物
if (poiResult.error == SearchResult.ERRORNO.NO_ERROR) {
mBaiduMap.clear();
//创建PoiOverlay对象
PoiOverlay poiOverlay = new PoiOverlay(mBaiduMap);
//设置Poi检索数据
poiOverlay.setData(poiResult);
//将poiOverlay添加至地图并缩放至合适级别
poiOverlay.addToMap();
poiOverlay.zoomToSpan();
} else {
Toast.makeText(MainActivity.this, "未搜索到内容", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onGetPoiDetailResult(PoiDetailSearchResult poiDetailSearchResult) {
Toast.makeText(MainActivity.this, "onGetPoiDetailResult", Toast.LENGTH_SHORT).show();
}
@Override
public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {
Toast.makeText(MainActivity.this, "onGetPoiIndoorResult", Toast.LENGTH_SHORT).show();
}
//废弃
@Override
public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
}
};
mPoiSearch.setOnGetPoiSearchResultListener(listener);
}
private void setting() {
mMapView = (MapView) findViewById(R.id.bmapView);
mBaiduMap = mMapView.getMap();
btn_location = (Button) findViewById(R.id.btn_location);
btn_location.setOnClickListener(this);
bmapView = (MapView) findViewById(R.id.bmapView);
bmapView.setOnClickListener(this);
btn_poi = (Button) findViewById(R.id.btn_poi);
btn_poi.setOnClickListener(this);
mBaiduMap = mMapView.getMap();
mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
mBaiduMap.setMyLocationEnabled(true);
//实例化UiSettings类对象
mUiSettings = mBaiduMap.getUiSettings();
//通过设置enable为true或false 选择是否显示指南针
mUiSettings.setCompassEnabled(true);
mUiSettings.setEnlargeCenterWithDoubleClickEnable(true);
initListener();
}
private void initListener() {
BaiduMap.OnMapClickListener listener = new BaiduMap.OnMapClickListener() {
/**
* 地图单击事件回调函数
*
* @param point 点击的地理坐标
*/
@Override
public void onMapClick(LatLng point) {
Toast.makeText(MainActivity.this, "点击了地图某个位置", Toast.LENGTH_SHORT).show();
//构建Marker图标
BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.icon_marka);
//构建MarkerOption,用于在地图上添加Marker
OverlayOptions option = new MarkerOptions()
.position(point)
.icon(bitmap);
//在地图上添加Marker,并显示
mBaiduMap.addOverlay(option);
}
/**
* 地图内 Poi 单击事件回调函数
*
* @param mapPoi 点击的 poi 信息
*/
@Override
public void onMapPoiClick(MapPoi mapPoi) {
Toast.makeText(MainActivity.this, "点击地图图标", Toast.LENGTH_SHORT).show();
engine( mapPoi.getPosition());
}
};
//设置地图单击事件监听
mBaiduMap.setOnMapClickListener(listener);
}
private void engine(final LatLng position) {
WalkNavigateHelper.getInstance().initNaviEngine(this, new IWEngineInitListener() {
@Override
public void engineInitSuccess() {
//引擎初始化成功的回调
Toast.makeText(MainActivity.this, "点击了Mark", Toast.LENGTH_SHORT).show();
routeWalkPlanWithParam(position);
}
@Override
public void engineInitFail() {
//引擎初始化失败的回调
}
});
}
private void routeWalkPlanWithParam(LatLng position) {
mParam = new WalkNaviLaunchParam().stPt(mUserLatLng).endPt(position);
WalkNavigateHelper.getInstance().routePlanWithParams(mParam, new IWRoutePlanListener() {
@Override
public void onRoutePlanStart() {
//开始算路的回调
}
@Override
public void onRoutePlanSuccess() {
//算路成功
//跳转至诱导页面
Toast.makeText(MainActivity.this, "点击了Mark111111", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, WNaviGuideActivity.class);
// Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
}
@Override
public void onRoutePlanFail(WalkRoutePlanError walkRoutePlanError) {
//算路失败的回调
Toast.makeText(MainActivity.this, "shibai", Toast.LENGTH_SHORT).show();
}
});
}
private void initPer() {
PermissionsUtil.requestPermission(this, new PermissionListener() {
@Override
public void permissionGranted(@NonNull String[] permission) {
}
@Override
public void permissionDenied(@NonNull String[] permission) {
}
}, new String[]{Manifest.permission.WRITE_CALENDAR, Manifest.permission.READ_CALENDAR, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION});
}
@Override
protected void onResume() {
super.onResume();
//在activity执行onResume时执行mMapView. onResume (),实现地图生命周期管理
mMapView.onResume();
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR);
iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK);
mReceiver = new SDKReceiver();
registerReceiver(mReceiver, iFilter);
}
@Override
protected void onPause() {
super.onPause();
//在activity执行onPause时执行mMapView. onPause (),实现地图生命周期管理
mMapView.onPause();
}
@Override
protected void onDestroy() {
mLocationClient.stop();
mBaiduMap.setMyLocationEnabled(false);
mMapView.onDestroy();
mMapView = null;
unregisterReceiver(mReceiver);
mPoiSearch.destroy();
super.onDestroy();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_location:
go2LatLng(mUserLatLng);
break;
case R.id.btn_poi:
String poi = et_poi.getText().toString().trim();
search(poi);
break;
}
}
private void search(String poi) {
mPoiSearch.searchNearby(new PoiNearbySearchOption()
.location(mUserLatLng)
.radius(10000)
.keyword(poi)
.pageNum(10));
}
private void go2LatLng(LatLng mUserLatLng) {
if (mUserLatLng != null) {
MapStatusUpdate status2 = MapStatusUpdateFactory.newLatLng(mUserLatLng);
mBaiduMap.setMapStatus(status2);
}
}
private void showLocation() {
//定位初始化
mLocationClient = new LocationClient(this);
//通过LocationClientOption设置LocationClient相关参数
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true); // 打开gps
option.setCoorType("bd09ll"); // 设置坐标类型
option.setScanSpan(1000);
//设置locationClientOption
mLocationClient.setLocOption(option);
//注册LocationListener监听器
MyLocationListener myLocationListener = new MyLocationListener();
mLocationClient.registerLocationListener(myLocationListener);
//开启地图定位图层
mLocationClient.start();
}
private void initView() {
btn_poi = (Button) findViewById(R.id.btn_poi);
btn_poi.setOnClickListener(this);
et_poi = (EditText) findViewById(R.id.et_poi);
et_poi.setOnClickListener(this);
}
public class MyLocationListener extends BDAbstractLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
//mapView 销毁后不在处理新接收的位置
if (location == null || mMapView == null) {
return;
}
MyLocationData locData = new MyLocationData.Builder()
.accuracy(location.getRadius())
// 此处设置开发者获取到的方向信息,顺时针0-360
.direction(location.getDirection()).latitude(location.getLatitude())
.longitude(location.getLongitude()).build();
mUserLatLng = new LatLng(location.getLatitude(), location.getLongitude());
mBaiduMap.setMyLocationData(locData);
}
}
}
网友评论