1.可以定位用户当前位置(6.0动态申请权限);
2.当前位置为起点,并根据获取到的终点信息,设置起点终点marker,进行路线规划,获得路线list的第一条数据使用,并在地图上overlay显示,修改默认的路径规划起点终点marker,弹出的bottomsheetdialog中文字显示(此处HTML.fromHtml());
3.将地图中心点调整为用户当前位置,并且根据起点终点距离调整到合适的缩放比例;
4.如果用户手机里安装了百度地图,点击导航,进入百度地图直接导航;如果用户未安装百度地图,则提示用户去安装百度地图(跳转到商店,进入百度地图安装页),或者打开浏览器导航。
5.定位(起点)和获取地理位置编码(终点)均是异步返回的,(因为要通过起点终点的经纬度计算距离)所以需要先得到一个,再去获取另一个,获取到第二个以后去设置起点终点就不会出现有一个可能为空;
6.管理地图的生命周期
7.调整缩放比例走过的坑
***********************************分割线***********************************
LatLngBounds.Builder builder = new LatLngBounds.Builder();
addWorkerMarker2Map(builder);//builder.include(point);添加维修工到地图显示范围
addCustomMarker2Map(builder);//builder.include(customPoint);添加客户到地图显示范围
//地图边界
final LatLngBounds bounds = builder.build();
//注意,调整地图缩放度应该在地图加载完成以后进行
mBaiduMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {
@Override
public void onMapLoaded() {
MapStatusUpdate update = MapStatusUpdateFactory.newLatLngBounds(bounds);
mBaiduMap.setMapStatus(update);
}
});
***********************************分割线***********************************
public class BaiduMapActivity extends BaseActivity implements View.OnClickListener {
@BindView(R.id.btnWalk)
ImageButton btnWalk;
@BindView(R.id.btnBike)
ImageButton btnBike;
@BindView(R.id.btnBus)
ImageButton btnBus;
@BindView(R.id.btnDrive)
ImageButton btnDrive;
@BindView(R.id.bmapView)
MapView mMapView;
//权限申请码
private static final int WRITE_COARSE_LOCATION_REQUEST_CODE = 100;
private static final int ACCESS_FINE_LOCATION = 200;
private static final int WRITE_EXTERNAL_STORAGE = 300;
private static final int READ_EXTERNAL_STORAGE = 400;
private static final int READ_PHONE_STATE = 500;
private LocationClient mLocationClient = null;//定位客户端
private BDLocationListener myListener = new MyLocationListener();//定位请求回调监听
private BaiduMap mBaiduMap;
private LatLng llStart;//开始位置(即工程师当前位置)
private LatLng llEnd;//终点(即报修用户位置)
//定位成功后返回,当前定位信息
private BDLocation mLocationStart;
//路径规划搜索接口
private RoutePlanSearch mSearch;
//地理编码查询接口
private GeoCoder mGeoSearch;
//出行节点信息(可用经纬度或地名+城市名确定)
private PlanNode stNode;
private PlanNode enNode;
private String endName;//终点名称
private String userCity;
private String userAddress;
private int[] distanceArr = new int[]{20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 25000, 50000, 100000, 200000, 500000, 1000000, 2000000, 5000000, 10000000};
private int[] levelArr = new int[]{21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3};
private String routeStr;//显示在BottomSheetDialog中的数据
private String distanceStr;
private boolean flag;//如果flag为true,即需要获得当前位置,并导航;若为false,则只需要展示终点
private String userName;
private String userDetail;
private BitmapDescriptor bitmapEnd;
private BitmapDescriptor bitmapStart;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_baidu_map);
ActivityManager.getAppInstance().addActivity(this);
ButterKnife.bind(this);
initToolBar(true, "查看位置");
//判断手机网络是否连接
checkNetWorkAvailable();
initButtonOnClickListener();
//获取终点信息,并初始化地图
initData();
//动态请求权限
checkPermission();
flag = getIntent().getBooleanExtra("flag", false);
if (!flag) {
btnWalk.setVisibility(View.GONE);
btnBike.setVisibility(View.GONE);
btnBus.setVisibility(View.GONE);
btnDrive.setVisibility(View.GONE);
//根据位置获得地理编码
mGeoSearch.geocode(new GeoCodeOption().city(userCity).address(userAddress));
} else {
//声明LocationClient类
mLocationClient = new LocationClient(getApplicationContext());
//注册监听函数
mLocationClient.registerLocationListener(myListener);
//初始化定位客户端
initLocation();
//开始定位
mLocationClient.start();
}
}
//判断手机网络是否连接
private void checkNetWorkAvailable() {
if (!isNetWorkAvailable(this)) {
showToast(this, getString(R.string.internet_error), TastyToast.ERROR);
return;
}
}
private void initData() {
Intent intent = getIntent();
endName = intent.getStringExtra("location");
if (!TextUtils.isEmpty(endName)) {
userCity = endName.substring(0, endName.indexOf("市"));
userAddress = endName.substring(endName.indexOf("市") + 1);
userName = getIntent().getStringExtra("name");
userDetail = getIntent().getStringExtra("detail");
}
mBaiduMap = mMapView.getMap();
//普通地图
mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
//设置定位地理编码查询监听
setLocationListener();
}
//设置定位地理编码查询监听
private void setLocationListener() {
mGeoSearch = GeoCoder.newInstance();
OnGetResult lis = new OnGetResult() {
@Override
public void setMap() {
setLevel();
}
};
MyOnGetGeoCoderResultListener listener = new MyOnGetGeoCoderResultListener(lis);
mGeoSearch.setOnGetGeoCodeResultListener(listener);
}
/**
* 当llEnd不为null是设置数据
*/
interface OnGetResult {
void setMap();
}
// 定位地理编码查询接口
private class MyOnGetGeoCoderResultListener implements OnGetGeoCoderResultListener {
private OnGetResult lis;
public MyOnGetGeoCoderResultListener(OnGetResult lis) {
this.lis = lis;
}
@Override
public void onGetGeoCodeResult(GeoCodeResult result) {
if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
//没有检索到结果
if ("PERMISSION_UNFINISHED".equalsIgnoreCase(result.error.toString())) {
mGeoSearch.geocode(new GeoCodeOption().city(userCity).address(userAddress));
return;
}
Toast.makeText(BaiduMapActivity.this, "没有检索到结果", Toast.LENGTH_SHORT).show();
}
//获取地理编码结果
if ("NO_ERROR".equalsIgnoreCase(result.error.toString())) {
mGeoSearch.destroy();
llEnd = new LatLng(result.getLocation().latitude, result.getLocation().longitude);
if (llEnd != null) {
//终点经纬度
setEnd();// 设置终点信息
if (flag) {
lis.setMap();
} else {
MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(llEnd);
if (update != null) {
// 将地图中心点移动到起点
mBaiduMap.animateMapStatus(update);
}
}
}
}
}
@Override
public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
//没有找到检索结果
Toast.makeText(BaiduMapActivity.this, "没有找到检索结果", Toast.LENGTH_SHORT).show();
}
//获取反向地理编码结果
mGeoSearch.destroy();
}
}
//初始化所需定位结果信息
private void initLocation() {
LocationClientOption option = new LocationClientOption();
option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
);//可选,默认高精度,设置定位模式,高精度,低功耗,仅设备
option.setCoorType("bd09ll");//可选,默认gcj02,设置返回的定位结果坐标系
int span = 0;
option.setScanSpan(span);//可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的
option.setIsNeedAddress(true);//可选,设置是否需要地址信息,默认不需要
option.setOpenGps(true);//可选,默认false,设置是否使用gps
option.setLocationNotify(true);//可选,默认false,设置是否当GPS有效时按照1S/1次频率输出GPS结果
option.setIsNeedLocationDescribe(true);//可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近”
option.setIsNeedLocationPoiList(true);//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到
option.setIgnoreKillProcess(false);//可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死
option.SetIgnoreCacheException(false);//可选,默认false,设置是否收集CRASH信息,默认收集
option.setEnableSimulateGps(false);//可选,默认false,设置是否需要过滤GPS仿真结果,默认需要
mLocationClient.setLocOption(option);
}
//view 转bitmap
public static Bitmap convertViewToBitmap(View view) {
view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
return bitmap;
}
//定位结果回调监听
private class MyLocationListener implements BDLocationListener {
//收到定位信息
@Override
public void onReceiveLocation(BDLocation location) {
mLocationClient.stop();
mLocationStart = location;
if (mLocationStart != null) {
llStart = new LatLng(mLocationStart.getLatitude(), mLocationStart.getLongitude());
if (llStart != null) {
MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(llStart);
if (update != null) {
//设置标注物
View viewStart = LayoutInflater.from(BaiduMapActivity.this).inflate(R.layout.baidu_map_start, null);
//必须使用百度的params
bitmapStart = BitmapDescriptorFactory
.fromBitmap(convertViewToBitmap(viewStart));
//构建MarkerOption,用于在地图上添加Marker
OverlayOptions option = new MarkerOptions()
.position(llStart)
.icon(bitmapStart);
//在地图上添加Marker,并显示
mBaiduMap.addOverlay(option);
mBaiduMap.animateMapStatus(update);
//根据位置获得地理编码
mGeoSearch.geocode(new GeoCodeOption().city(userCity).address(userAddress));
}
}
}
}
}
//设置终点信息
private void setEnd() {
// 设置标注物
View viewEnd = LayoutInflater.from(this).inflate(R.layout.baidu_map_end, null);
TextView txtName = (TextView) viewEnd.findViewById(R.id.txt_baidu_name);
txtName.setText(userName);
TextView txtDetail = (TextView) viewEnd.findViewById(R.id.txt_baidu_detail);
txtDetail.setText(userDetail);
bitmapEnd = BitmapDescriptorFactory
.fromBitmap(convertViewToBitmap(viewEnd));
//构建MarkerOption,用于在地图上添加Marker
OverlayOptions option = new MarkerOptions()
.position(llEnd)
.icon(bitmapEnd);
//在地图上添加Marker,并显示
mBaiduMap.addOverlay(option);
}
//设置地图缩放级别
private void setLevel() {
//起点: latitude纬度 longitude经度
if (llStart != null ) {
int distance = (int) DistanceUtil.getDistance(llStart, llEnd);
distanceStr = "距离约" + distance + "米";
int level = getLevel(distance);
//设置缩放级别
mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().zoom(levelArr[level]).build()));
}
}
//根据距离计算出差值数组,并排序(取正数)
private int getLevel(int distance) {
int level = -1;
int min = 10000000;
for (int i = 0; i < distanceArr.length; i++) {
if (distanceArr[i] - distance > 0 && distanceArr[i] - distance < min) {
min = distanceArr[i] - distance;
level = i;
}
}
return level;
}
//路径规划监听
private class MyGetRoutePlanResultListener implements OnGetRoutePlanResultListener {
@Override
public void onGetWalkingRouteResult(WalkingRouteResult result) {
if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
Toast.makeText(BaiduMapActivity.this, "抱歉,未找到结果", Toast.LENGTH_SHORT).show();
}
if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
//起终点或途经点地址有岐义,通过以下接口获取建议查询信息
//result.getSuggestAddrInfo()
return;
}
if (result.error == SearchResult.ERRORNO.NO_ERROR) {
mSearch.destroy();
WalkingRouteOverlay overlay = new WalkingRouteOverlay(mBaiduMap);
overlay.setStartDescriptor(bitmapStart);//自己添加的方法,设置开始位置的标志图片
overlay.setEndDescriptor(bitmapEnd);//设置终点位置的标志图片
mBaiduMap.setOnMarkerClickListener(overlay);
overlay.setData(result.getRouteLines().get(0));
overlay.addToMap();
overlay.zoomToSpan();
List step = result.getRouteLines().get(0).getAllStep();
routeStr = getWalkingRoute(step);
setBottomSheetDialog();
}
}
//获得规划的步行线路的详细信息
private String getWalkingRoute(List step) {
StringBuffer route = new StringBuffer();
for (int i = 0; i < step.size(); i++) {
Spanned stepStr = Html.fromHtml(step.get(i).getInstructions());
if (i == step.size() - 1) {
route.append(i + 1 + ". " + stepStr.toString());
return route.toString();
}
route.append(i + 1 + ". " + stepStr.toString() + "\r\n");
}
return route.toString();
}
@Override
public void onGetTransitRouteResult(TransitRouteResult result) {
if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
Toast.makeText(BaiduMapActivity.this, "抱歉,未找到结果", Toast.LENGTH_SHORT).show();
}
if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
//起终点或途经点地址有岐义,通过以下接口获取建议查询信息
//result.getSuggestAddrInfo()
return;
}
if (result.error == SearchResult.ERRORNO.NO_ERROR) {
mSearch.destroy();
TransitRouteOverlay overlay = new TransitRouteOverlay(mBaiduMap);
overlay.setStartDescriptor(bitmapStart);
overlay.setEndDescriptor(bitmapEnd);
mBaiduMap.setOnMarkerClickListener(overlay);
//返回的规划线路是一个集合,这里采用了第一条线路
overlay.setData(result.getRouteLines().get(0));
overlay.addToMap();
overlay.zoomToSpan();
List step = result.getRouteLines().get(0).getAllStep();
routeStr = getTransitRoute(step);
setBottomSheetDialog();
}
}
//获得规划的公交线路的详细信息
private String getTransitRoute(List step) {
StringBuffer route = new StringBuffer();
for (int i = 0; i < step.size(); i++) {
Spanned stepStr = Html.fromHtml(step.get(i).getInstructions());
if (i == step.size() - 1) {
route.append(i + 1 + ". " + stepStr.toString());
return route.toString();
}
route.append(i + 1 + ". " + stepStr.toString() + "\r\n");
}
return route.toString();
}
@Override
public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {
}
@Override
public void onGetDrivingRouteResult(DrivingRouteResult result) {
if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
Toast.makeText(BaiduMapActivity.this, "抱歉,未找到结果", Toast.LENGTH_SHORT).show();
}
if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
//起终点或途经点地址有岐义,通过以下接口获取建议查询信息
//result.getSuggestAddrInfo()
return;
}
if (result.error == SearchResult.ERRORNO.NO_ERROR) {
mSearch.destroy();
DrivingRouteOverlay overlay = new DrivingRouteOverlay(mBaiduMap);
overlay.setStartDescriptor(bitmapStart);
overlay.setEndDescriptor(bitmapEnd);
mBaiduMap.setOnMarkerClickListener(overlay);
overlay.setData(result.getRouteLines().get(0));
overlay.addToMap();
overlay.zoomToSpan();
List step = result.getRouteLines().get(0).getAllStep();
routeStr = getDrivingRoute(step);
setBottomSheetDialog();
}
}
//获得规划的驾车线路的详细信息
private String getDrivingRoute(List step) {
StringBuffer route = new StringBuffer();
for (int i = 0; i < step.size(); i++) {
Spanned stepStr = Html.fromHtml(step.get(i).getInstructions());
if (i == step.size() - 1) {
route.append(i + 1 + ". " + stepStr.toString());
return route.toString();
}
route.append(i + 1 + ". " + stepStr.toString() + "\r\n");
}
return route.toString();
}
@Override
public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {
}
@Override
public void onGetBikingRouteResult(BikingRouteResult result) {
if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
Toast.makeText(BaiduMapActivity.this, "抱歉,未找到结果", Toast.LENGTH_SHORT).show();
}
if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
//起终点或途经点地址有岐义,通过以下接口获取建议查询信息
//result.getSuggestAddrInfo()
return;
}
if (result.error == SearchResult.ERRORNO.NO_ERROR) {
mSearch.destroy();
BikingRouteOverlay overlay = new BikingRouteOverlay(mBaiduMap);
overlay.setStartDescriptor(bitmapStart);
overlay.setEndDescriptor(bitmapEnd);
mBaiduMap.setOnMarkerClickListener(overlay);
overlay.setData(result.getRouteLines().get(0));
overlay.addToMap();
overlay.zoomToSpan();
List step = result.getRouteLines().get(0).getAllStep();
routeStr = getBikingRoute(step);
setBottomSheetDialog();
}
}
//获得规划的骑行线路的详细信息
private String getBikingRoute(List step) {
StringBuffer route = new StringBuffer();
for (int i = 0; i < step.size(); i++) {
Spanned stepStr = Html.fromHtml(step.get(i).getInstructions());
if (i == step.size() - 1) {
route.append(i + 1 + ". " + stepStr.toString());
return route.toString();
}
route.append(i + 1 + ". " + stepStr.toString() + "\r\n");
}
return route.toString();
}
}
//初始化BottomSheetDialog,并设置数据
private void setBottomSheetDialog() {
BottomSheetDialog dialog = new BottomSheetDialog(this);
dialog.setCanceledOnTouchOutside(false);
View v = LayoutInflater.from(this).inflate(R.layout.route_bottomsheetdialog, null);
TextView txtEndName = (TextView) v.findViewById(R.id.txtEndName);
TextView txtDistance = (TextView) v.findViewById(R.id.txtDistance);
TextView txtRoute = (TextView) v.findViewById(R.id.txtRoute);
Button btnNavi = (Button) v.findViewById(R.id.btnNavi);
txtEndName.setText("终点:" + endName);
txtDistance.setText(distanceStr + "\r\n");
txtRoute.setText(routeStr);
btnNavi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkNetWorkAvailable();
if (llStart == null || llEnd == null) {
return;
}
//如果已安装,
if (isAvilible(BaiduMapActivity.this, "com.baidu.BaiduMap")) {//传入指定应用包名
try {
Intent i1 = new Intent();
// 公交路线规划
i1.setData(Uri.parse("baidumap://map/direction?region=" + llStart.latitude + "," + llStart.longitude + "&destination=name:" + endName + "|latlng:" + llEnd.latitude + "," + llEnd.longitude + "&mode=transit&sy=3&index=0&target=1"));
startActivity(i1);
} catch (Exception e) {
Log.e("intent", e.getMessage());
}
} else {
//未安装
//market为路径,id为包名
//显示手机上所有的market商店
AlertDialog.Builder builder = new AlertDialog.Builder(BaiduMapActivity.this);
builder.setTitle("提示");
builder.setMessage("是否安装百度地图");
builder.setIcon(R.drawable.ic_launcher);
builder.setPositiveButton("去安装", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Uri uri = Uri.parse("market://details?id=com.baidu.BaiduMap");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
builder.setNeutralButton("浏览器打开", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
openWebMap(llStart.latitude, llStart.longitude, mLocationStart.getAddrStr(), llEnd.latitude, llEnd.longitude, endName, mLocationStart.getCity());
}
});
builder.create().show();
}
}
});
dialog.setContentView(v, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 900));
dialog.show();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
dialog.dismiss();
}
});
}
//给按钮注册监听
private void initButtonOnClickListener() {
btnWalk.setOnClickListener(this);
btnBike.setOnClickListener(this);
btnBus.setOnClickListener(this);
btnDrive.setOnClickListener(this);
}
//路径规划前的准备工作
private RoutePlanSearch preparePlanning() {
mBaiduMap.clear();//清除原标注物
RoutePlanSearch mSearch = RoutePlanSearch.newInstance();
OnGetRoutePlanResultListener listener = new MyGetRoutePlanResultListener();
mSearch.setOnGetRoutePlanResultListener(listener);
stNode = PlanNode.withLocation(llStart);
enNode = PlanNode.withLocation(llEnd);
return mSearch;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnWalk:
//判断手机网络是否连接
checkNetWorkAvailable();
if (llStart == null || llEnd == null) {
//开始定位
if (mLocationClient != null) {
mLocationClient.start();
} else {
showToast(this, "网络错误", TastyToast.ERROR);
}
return;
}
mSearch = preparePlanning();
mSearch.walkingSearch((new WalkingRoutePlanOption())
.from(stNode)
.to(enNode));
break;
case R.id.btnBike:
//判断手机网络是否连接
checkNetWorkAvailable();
if (llStart == null || llEnd == null) {
//开始定位
if (mLocationClient != null) {
mLocationClient.start();
} else {
showToast(this, "网络错误", TastyToast.ERROR);
}
return;
}
mSearch = preparePlanning();
mSearch.bikingSearch((new BikingRoutePlanOption())
.from(stNode)
.to(enNode));
break;
case R.id.btnBus:
//判断手机网络是否连接
checkNetWorkAvailable();
if (llStart == null || llEnd == null) {
//开始定位
if (mLocationClient != null) {
mLocationClient.start();
} else {
showToast(this, "网络错误", TastyToast.ERROR);
}
return;
}
mSearch = preparePlanning();
mSearch.transitSearch((new TransitRoutePlanOption())
.from(stNode)
.city(mLocationStart.getCity())
.to(enNode));
break;
case R.id.btnDrive:
//判断手机网络是否连接
checkNetWorkAvailable();
if (llStart == null || llEnd == null) {
//开始定位
if (mLocationClient != null) {
mLocationClient.start();
} else {
showToast(this, "网络错误", TastyToast.ERROR);
}
return;
}
mSearch = preparePlanning();
mSearch.drivingSearch((new DrivingRoutePlanOption())
.from(stNode)
.to(enNode));
break;
default:
break;
}
}
@Override
protected void onResume() {
super.onResume();
//在activity执行onResume时执行mMapView. onResume (),实现地图生命周期管理
mMapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
//在activity执行onPause时执行mMapView. onPause (),实现地图生命周期管理
mMapView.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
//在activity执行onDestroy时执行mMapView.onDestroy(),实现地图生命周期管理
mMapView.onDestroy();
}
/**
* 打开浏览器进行百度地图导航
*/
private void openWebMap(double slat, double slon, String sname, double dlat, double dlon, String dname, String city) {
Uri mapUri = Uri.parse(getWebBaiduMapUri(String.valueOf(slat), String.valueOf(slon), sname,
String.valueOf(dlat), String.valueOf(dlon),
dname, city, "xxxxxx"));
Intent loction = new Intent(Intent.ACTION_VIEW, mapUri);
startActivity(loction);
}
/**
* 网页版百度地图 有经纬度
*
* @param originLat
* @param originLon
* @param originName ->注:必填
* @param desLat
* @param desLon
* @param destination
* @param region : 当给定region时,认为起点和终点都在同一城市,除非单独给定起点或终点的城市。-->注:必填,不填不会显示导航路线
* @param appName
* @return
*/
public static String getWebBaiduMapUri(String originLat, String originLon, String originName, String desLat, String desLon, String destination, String region, String appName) {
String uri = "http://api.map.baidu.com/direction?origin=latlng:%1$s,%2$s|name:%3$s" +
"&destination=latlng:%4$s,%5$s|name:%6$s&mode=transit®ion=%7$s&output=html" +
"&src=%8$s";
return String.format(uri, originLat, originLon, originName, desLat, desLon, destination, region, appName);
}
/**
* 检查手机上是否安装了指定的软件
*
* @param context
* @param packageName:应用包名
* @return
*/
private boolean isAvilible(Context context, String packageName) {
//获取packagemanager
final PackageManager packageManager = context.getPackageManager();
//获取所有已安装程序的包信息
List packageInfos = packageManager.getInstalledPackages(0);
//用于存储所有已安装程序的包名
List packageNames = new ArrayList();
//从pinfo中将包名字逐一取出,压入pName list中
if (packageInfos != null) {
for (int i = 0; i < packageInfos.size(); i++) {
String packName = packageInfos.get(i).packageName;
packageNames.add(packName);
}
}
//判断packageNames中是否有目标程序的包名,有TRUE,没有FALSE
return packageNames.contains(packageName);
}
//检查并请求权限
private void checkPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
//申请ACCESS_COARSE_LOCATION权限
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
WRITE_COARSE_LOCATION_REQUEST_CODE);//自定义的code
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
//申请ACCESS_FINE_LOCATION权限
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
ACCESS_FINE_LOCATION);//自定义的code
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
//申请WRITE_EXTERNAL_STORAGE权限
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
WRITE_EXTERNAL_STORAGE);//自定义的code
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
//申请READ_EXTERNAL_STORAGE权限
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
READ_EXTERNAL_STORAGE);//自定义的code
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
//申请READ_PHONE_STATE权限
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE},
READ_PHONE_STATE);//自定义的code
}
}
}
百度官方demo中的overlay
/**
* 该类提供一个能够显示和管理多个Overlay的基类
*
* 复写{@link #getOverlayOptions()} 设置欲显示和管理的Overlay列表
*
*
* 通过
* {@link BaiduMap#setOnMarkerClickListener(OnMarkerClickListener)}
* 将覆盖物点击事件传递给OverlayManager后,OverlayManager才能响应点击事件。
*
* 复写{@link #onMarkerClick(Marker)} 处理Marker点击事件
*
*/
public abstract class OverlayManager implements OnMarkerClickListener, OnPolylineClickListener {
BaiduMap mBaiduMap = null;
private List mOverlayOptionList = null;
List mOverlayList = null;
/**
* 通过一个BaiduMap 对象构造
*
* @param baiduMap
*/
public OverlayManager(BaiduMap baiduMap) {
mBaiduMap = baiduMap;
// mBaiduMap.setOnMarkerClickListener(this);
if (mOverlayOptionList == null) {
mOverlayOptionList = new ArrayList();
}
if (mOverlayList == null) {
mOverlayList = new ArrayList();
}
}
/**
* 覆写此方法设置要管理的Overlay列表
*
* @return 管理的Overlay列表
*/
public abstract List getOverlayOptions();
/**
* 将所有Overlay 添加到地图上
*/
public final void addToMap() {
if (mBaiduMap == null) {
return;
}
removeFromMap();
List 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都在合适的视野内
*
* 注: 该方法只对Marker类型的overlay有效
*
*
*/
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()));
}
}
}
/**
* 用于显示步行路线的overlay,自3.4.0版本起可实例化多个添加在地图中显示
*/
public class WalkingRouteOverlay extends OverlayManager {
private WalkingRouteLine mRouteLine = null;
public WalkingRouteOverlay(BaiduMap baiduMap) {
super(baiduMap);
}
/**
* 设置路线数据。
*
* @param line
* 路线数据
*/
public void setData(WalkingRouteLine line) {
mRouteLine = line;
}
@Override
public final List getOverlayOptions() {
if (mRouteLine == null) {
return null;
}
List overlayList = new ArrayList();
if (mRouteLine.getAllStep() != null
&& mRouteLine.getAllStep().size() > 0) {
for (WalkingRouteLine.WalkingStep step : mRouteLine.getAllStep()) {
Bundle b = new Bundle();
b.putInt("index", mRouteLine.getAllStep().indexOf(step));
if (step.getEntrance() != null) {
overlayList.add((new MarkerOptions())
.position(step.getEntrance().getLocation())
.rotate((360 - step.getDirection()))
.zIndex(10)
.anchor(0.5f, 0.5f)
.extraInfo(b)
.icon(BitmapDescriptorFactory
.fromAssetWithDpi("Icon_line_node.png")));
}
// 最后路段绘制出口点
if (mRouteLine.getAllStep().indexOf(step) == (mRouteLine
.getAllStep().size() - 1) && step.getExit() != null) {
overlayList.add((new MarkerOptions())
.position(step.getExit().getLocation())
.anchor(0.5f, 0.5f)
.zIndex(10)
.icon(BitmapDescriptorFactory
.fromAssetWithDpi("Icon_line_node.png")));
}
}
}
// starting
if (mRouteLine.getStarting() != null) {
overlayList.add((new MarkerOptions())
.position(mRouteLine.getStarting().getLocation())
.icon(getStartMarker() != null ? getStartMarker() :
BitmapDescriptorFactory
.fromAssetWithDpi("Icon_start.png")).zIndex(10));
}
// terminal
if (mRouteLine.getTerminal() != null) {
overlayList
.add((new MarkerOptions())
.position(mRouteLine.getTerminal().getLocation())
.icon(getTerminalMarker() != null ? getTerminalMarker() :
BitmapDescriptorFactory
.fromAssetWithDpi("Icon_end.png"))
.zIndex(10));
}
// poly line list
if (mRouteLine.getAllStep() != null
&& mRouteLine.getAllStep().size() > 0) {
LatLng lastStepLastPoint = null;
for (WalkingRouteLine.WalkingStep step : mRouteLine.getAllStep()) {
List watPoints = step.getWayPoints();
if (watPoints != null) {
List points = new ArrayList();
if (lastStepLastPoint != null) {
points.add(lastStepLastPoint);
}
points.addAll(watPoints);
overlayList.add(new PolylineOptions().points(points).width(10)
.color(getLineColor() != 0 ? getLineColor() : Color.argb(178, 0, 78, 255)).zIndex(0));
lastStepLastPoint = watPoints.get(watPoints.size() - 1);
}
}
}
return overlayList;
}
private BitmapDescriptor startDescriptor;
private BitmapDescriptor endDescriptor;
/**
* 覆写此方法以改变默认起点图标
*
* @return 起点图标
*/
public BitmapDescriptor getStartMarker() {
return this.startDescriptor;
}
public void setStartDescriptor(BitmapDescriptor startDescriptor) {
this.startDescriptor = startDescriptor;
}
public void setEndDescriptor(BitmapDescriptor endDescriptor) {
this.endDescriptor = endDescriptor;
}
public int getLineColor() {
return 0;
}
/**
* 覆写此方法以改变默认终点图标
*
* @return 终点图标
*/
public BitmapDescriptor getTerminalMarker() {
return this.endDescriptor;
}
/**
* 处理点击事件
*
* @param i
* 被点击的step在
* {@link WalkingRouteLine#getAllStep()}
* 中的索引
* @return 是否处理了该点击事件
*/
public boolean onRouteNodeClick(int i) {
if (mRouteLine.getAllStep() != null
&& mRouteLine.getAllStep().get(i) != null) {
Log.i("baidumapsdk", "WalkingRouteOverlay onRouteNodeClick");
}
return false;
}
@Override
public final boolean onMarkerClick(Marker marker) {
for (Overlay mMarker : mOverlayList) {
if (mMarker instanceof Marker && mMarker.equals(marker)) {
if (marker.getExtraInfo() != null) {
onRouteNodeClick(marker.getExtraInfo().getInt("index"));
}
}
}
return true;
}
@Override
public boolean onPolylineClick(Polyline polyline) {
// TODO Auto-generated method stub
return false;
}
}
/**
* 用于显示骑行路线的Overlay
*/
public class BikingRouteOverlay extends OverlayManager {
private BikingRouteLine mRouteLine = null;
public BikingRouteOverlay(BaiduMap baiduMap) {
super(baiduMap);
}
/**
* 设置路线数据。
*
* @param line
* 路线数据
*/
public void setData(BikingRouteLine line) {
mRouteLine = line;
}
@Override
public final List getOverlayOptions() {
if (mRouteLine == null) {
return null;
}
List overlayList = new ArrayList();
if (mRouteLine.getAllStep() != null
&& mRouteLine.getAllStep().size() > 0) {
for (BikingRouteLine.BikingStep step : mRouteLine.getAllStep()) {
Bundle b = new Bundle();
b.putInt("index", mRouteLine.getAllStep().indexOf(step));
if (step.getEntrance() != null) {
overlayList.add((new MarkerOptions())
.position(step.getEntrance().getLocation())
.rotate((360 - step.getDirection()))
.zIndex(10)
.anchor(0.5f, 0.5f)
.extraInfo(b)
.icon(BitmapDescriptorFactory
.fromAssetWithDpi("Icon_line_node.png")));
}
// 最后路段绘制出口点
if (mRouteLine.getAllStep().indexOf(step) == (mRouteLine
.getAllStep().size() - 1) && step.getExit() != null) {
overlayList.add((new MarkerOptions())
.position(step.getExit().getLocation())
.anchor(0.5f, 0.5f)
.zIndex(10)
.icon(BitmapDescriptorFactory
.fromAssetWithDpi("Icon_line_node.png")));
}
}
}
// starting
if (mRouteLine.getStarting() != null) {
overlayList.add((new MarkerOptions())
.position(mRouteLine.getStarting().getLocation())
.icon(getStartMarker() != null ? getStartMarker() :
BitmapDescriptorFactory
.fromAssetWithDpi("Icon_start.png")).zIndex(10));
}
// terminal
if (mRouteLine.getTerminal() != null) {
overlayList
.add((new MarkerOptions())
.position(mRouteLine.getTerminal().getLocation())
.icon(getTerminalMarker() != null ? getTerminalMarker() :
BitmapDescriptorFactory
.fromAssetWithDpi("Icon_end.png"))
.zIndex(10));
}
// poly line list
if (mRouteLine.getAllStep() != null
&& mRouteLine.getAllStep().size() > 0) {
LatLng lastStepLastPoint = null;
for (BikingRouteLine.BikingStep step : mRouteLine.getAllStep()) {
List watPoints = step.getWayPoints();
if (watPoints != null) {
List points = new ArrayList();
if (lastStepLastPoint != null) {
points.add(lastStepLastPoint);
}
points.addAll(watPoints);
overlayList.add(new PolylineOptions().points(points).width(10)
.color(getLineColor() != 0 ? getLineColor() : Color.argb(178, 0, 78, 255)).zIndex(0));
lastStepLastPoint = watPoints.get(watPoints.size() - 1);
}
}
}
return overlayList;
}
private BitmapDescriptor startDescriptor;
private BitmapDescriptor endDescriptor;
/**
* 覆写此方法以改变默认起点图标
*
* @return 起点图标
*/
public BitmapDescriptor getStartMarker() {
return this.startDescriptor;
}
public void setStartDescriptor(BitmapDescriptor startDescriptor) {
this.startDescriptor = startDescriptor;
}
public void setEndDescriptor(BitmapDescriptor endDescriptor) {
this.endDescriptor = endDescriptor;
}
public int getLineColor() {
return 0;
}
/**
* 覆写此方法以改变默认终点图标
*
* @return 终点图标
*/
public BitmapDescriptor getTerminalMarker() {
return this.endDescriptor;
}
/**
* 处理点击事件
*
* @param i
* 被点击的step在
* {@link BikingRouteLine#getAllStep()}
* 中的索引
* @return 是否处理了该点击事件
*/
public boolean onRouteNodeClick(int i) {
if (mRouteLine.getAllStep() != null
&& mRouteLine.getAllStep().get(i) != null) {
Log.i("baidumapsdk", "BikingRouteOverlay onRouteNodeClick");
}
return false;
}
@Override
public final boolean onMarkerClick(Marker marker) {
for (Overlay mMarker : mOverlayList) {
if (mMarker instanceof Marker && mMarker.equals(marker)) {
if (marker.getExtraInfo() != null) {
onRouteNodeClick(marker.getExtraInfo().getInt("index"));
}
}
}
return true;
}
@Override
public boolean onPolylineClick(Polyline polyline) {
// TODO Auto-generated method stub
return false;
}
}
/**
* 用于显示换乘路线的Overlay,自3.4.0版本起可实例化多个添加在地图中显示
*/
public class TransitRouteOverlay extends OverlayManager {
private TransitRouteLine mRouteLine = null;
/**
* 构造函数
*
* @param baiduMap
* 该TransitRouteOverlay引用的 BaiduMap 对象
*/
public TransitRouteOverlay(BaiduMap baiduMap) {
super(baiduMap);
}
@Override
public final List getOverlayOptions() {
if (mRouteLine == null) {
return null;
}
List overlayOptionses = new ArrayList();
// step node
if (mRouteLine.getAllStep() != null
&& mRouteLine.getAllStep().size() > 0) {
for (TransitRouteLine.TransitStep step : mRouteLine.getAllStep()) {
Bundle b = new Bundle();
b.putInt("index", mRouteLine.getAllStep().indexOf(step));
if (step.getEntrance() != null) {
overlayOptionses.add((new MarkerOptions())
.position(step.getEntrance().getLocation())
.anchor(0.5f, 0.5f).zIndex(10).extraInfo(b)
.icon(getIconForStep(step)));
}
// 最后路段绘制出口点
if (mRouteLine.getAllStep().indexOf(step) == (mRouteLine
.getAllStep().size() - 1) && step.getExit() != null) {
overlayOptionses.add((new MarkerOptions())
.position(step.getExit().getLocation())
.anchor(0.5f, 0.5f).zIndex(10)
.icon(getIconForStep(step)));
}
}
}
if (mRouteLine.getStarting() != null) {
overlayOptionses.add((new MarkerOptions())
.position(mRouteLine.getStarting().getLocation())
.icon(getStartMarker() != null ? getStartMarker() :
BitmapDescriptorFactory
.fromAssetWithDpi("Icon_start.png")).zIndex(10));
}
if (mRouteLine.getTerminal() != null) {
overlayOptionses
.add((new MarkerOptions())
.position(mRouteLine.getTerminal().getLocation())
.icon(getTerminalMarker() != null ? getTerminalMarker() :
BitmapDescriptorFactory
.fromAssetWithDpi("Icon_end.png"))
.zIndex(10));
}
// polyline
if (mRouteLine.getAllStep() != null
&& mRouteLine.getAllStep().size() > 0) {
for (TransitRouteLine.TransitStep step : mRouteLine.getAllStep()) {
if (step.getWayPoints() == null) {
continue;
}
int color = 0;
if (step.getStepType() != TransitRouteLine.TransitStep.TransitRouteStepType.WAKLING) {
// color = Color.argb(178, 0, 78, 255);
color = getLineColor() != 0 ? getLineColor() : Color.argb(178, 0, 78, 255);
} else {
// color = Color.argb(178, 88, 208, 0);
color = getLineColor() != 0 ? getLineColor() : Color.argb(178, 88, 208, 0);
}
overlayOptionses.add(new PolylineOptions()
.points(step.getWayPoints()).width(10).color(color)
.zIndex(0));
}
}
return overlayOptionses;
}
private BitmapDescriptor getIconForStep(TransitRouteLine.TransitStep step) {
switch (step.getStepType()) {
case BUSLINE:
return BitmapDescriptorFactory.fromAssetWithDpi("Icon_bus_station.png");
case SUBWAY:
return BitmapDescriptorFactory.fromAssetWithDpi("Icon_subway_station.png");
case WAKLING:
return BitmapDescriptorFactory.fromAssetWithDpi("Icon_walk_route.png");
default:
return null;
}
}
/**
* 设置路线数据
*
* @param routeOverlay
* 路线数据
*/
public void setData(TransitRouteLine routeOverlay) {
this.mRouteLine = routeOverlay;
}
private BitmapDescriptor startDescriptor;
private BitmapDescriptor endDescriptor;
/**
* 覆写此方法以改变默认起点图标
*
* @return 起点图标
*/
public BitmapDescriptor getStartMarker() {
return this.startDescriptor;
}
public void setStartDescriptor(BitmapDescriptor startDescriptor) {
this.startDescriptor = startDescriptor;
}
public void setEndDescriptor(BitmapDescriptor endDescriptor) {
this.endDescriptor = endDescriptor;
}
public int getLineColor() {
return 0;
}
/**
* 覆写此方法以改变默认终点图标
*
* @return 终点图标
*/
public BitmapDescriptor getTerminalMarker() {
return this.endDescriptor;
}
/**
* 覆写此方法以改变起默认点击行为
*
* @param i
* 被点击的step在
* {@link TransitRouteLine#getAllStep()}
* 中的索引
* @return 是否处理了该点击事件
*/
public boolean onRouteNodeClick(int i) {
if (mRouteLine.getAllStep() != null
&& mRouteLine.getAllStep().get(i) != null) {
Log.i("baidumapsdk", "TransitRouteOverlay onRouteNodeClick");
}
return false;
}
@Override
public final boolean onMarkerClick(Marker marker) {
for (Overlay mMarker : mOverlayList) {
if (mMarker instanceof Marker && mMarker.equals(marker)) {
if (marker.getExtraInfo() != null) {
onRouteNodeClick(marker.getExtraInfo().getInt("index"));
}
}
}
return true;
}
@Override
public boolean onPolylineClick(Polyline polyline) {
// TODO Auto-generated method stub
return false;
}
}
/**
* 用于显示一条驾车路线的overlay,自3.4.0版本起可实例化多个添加在地图中显示,当数据中包含路况数据时,则默认使用路况纹理分段绘制
*/
public class DrivingRouteOverlay extends OverlayManager {
private DrivingRouteLine mRouteLine = null;
boolean focus = false;
/**
* 构造函数
*
* @param baiduMap
* 该DrivingRouteOvelray引用的 BaiduMap
*/
public DrivingRouteOverlay(BaiduMap baiduMap) {
super(baiduMap);
}
@Override
public final List getOverlayOptions() {
if (mRouteLine == null) {
return null;
}
List overlayOptionses = new ArrayList();
// step node
if (mRouteLine.getAllStep() != null
&& mRouteLine.getAllStep().size() > 0) {
for (DrivingStep step : mRouteLine.getAllStep()) {
Bundle b = new Bundle();
b.putInt("index", mRouteLine.getAllStep().indexOf(step));
if (step.getEntrance() != null) {
overlayOptionses.add((new MarkerOptions())
.position(step.getEntrance().getLocation())
.anchor(0.5f, 0.5f)
.zIndex(10)
.rotate((360 - step.getDirection()))
.extraInfo(b)
.icon(BitmapDescriptorFactory
.fromAssetWithDpi("Icon_line_node.png")));
}
// 最后路段绘制出口点
if (mRouteLine.getAllStep().indexOf(step) == (mRouteLine
.getAllStep().size() - 1) && step.getExit() != null) {
overlayOptionses.add((new MarkerOptions())
.position(step.getExit().getLocation())
.anchor(0.5f, 0.5f)
.zIndex(10)
.icon(BitmapDescriptorFactory
.fromAssetWithDpi("Icon_line_node.png")));
}
}
}
if (mRouteLine.getStarting() != null) {
overlayOptionses.add((new MarkerOptions())
.position(mRouteLine.getStarting().getLocation())
.icon(getStartMarker() != null ? getStartMarker() :
BitmapDescriptorFactory
.fromAssetWithDpi("Icon_start.png")).zIndex(10));
}
if (mRouteLine.getTerminal() != null) {
overlayOptionses
.add((new MarkerOptions())
.position(mRouteLine.getTerminal().getLocation())
.icon(getTerminalMarker() != null ? getTerminalMarker() :
BitmapDescriptorFactory
.fromAssetWithDpi("Icon_end.png"))
.zIndex(10));
}
// poly line
if (mRouteLine.getAllStep() != null
&& mRouteLine.getAllStep().size() > 0) {
List steps = mRouteLine.getAllStep();
int stepNum = steps.size();
List points = new ArrayList();
ArrayList traffics = new ArrayList();
int totalTraffic = 0;
for (int i = 0; i < stepNum ; i++) {
if (i == stepNum - 1) {
points.addAll(steps.get(i).getWayPoints());
} else {
points.addAll(steps.get(i).getWayPoints().subList(0, steps.get(i).getWayPoints().size() - 1));
}
totalTraffic += steps.get(i).getWayPoints().size() - 1;
if (steps.get(i).getTrafficList() != null && steps.get(i).getTrafficList().length > 0) {
for (int j = 0;j < steps.get(i).getTrafficList().length;j++) {
traffics.add(steps.get(i).getTrafficList()[j]);
}
}
}
// Bundle indexList = new Bundle();
// if (traffics.size() > 0) {
// int raffic[] = new int[traffics.size()];
// int index = 0;
// for (Integer tempTraff : traffics) {
// raffic[index] = tempTraff.intValue();
// index++;
// }
// indexList.putIntArray("indexs", raffic);
// }
boolean isDotLine = false;
if (traffics != null && traffics.size() > 0) {
isDotLine = true;
}
PolylineOptions option = new PolylineOptions().points(points).textureIndex(traffics)
.width(7).dottedLine(isDotLine).focus(true)
.color(getLineColor() != 0 ? getLineColor() : Color.argb(178, 0, 78, 255)).zIndex(0);
if (isDotLine) {
option.customTextureList(getCustomTextureList());
}
overlayOptionses.add(option);
}
return overlayOptionses;
}
/**
* 设置路线数据
*
* @param routeLine
* 路线数据
*/
public void setData(DrivingRouteLine routeLine) {
this.mRouteLine = routeLine;
}
private BitmapDescriptor startDescriptor;
private BitmapDescriptor endDescriptor;
/**
* 覆写此方法以改变默认起点图标
*
* @return 起点图标
*/
public BitmapDescriptor getStartMarker() {
return this.startDescriptor;
}
public void setStartDescriptor(BitmapDescriptor startDescriptor) {
this.startDescriptor = startDescriptor;
}
public void setEndDescriptor(BitmapDescriptor endDescriptor) {
this.endDescriptor = endDescriptor;
}
/**
* 覆写此方法以改变默认绘制颜色
* @return 线颜色
*/
public int getLineColor() {
return 0;
}
public List getCustomTextureList() {
ArrayList list = new ArrayList();
list.add(BitmapDescriptorFactory.fromAsset("Icon_road_blue_arrow.png"));
list.add(BitmapDescriptorFactory.fromAsset("Icon_road_green_arrow.png"));
list.add(BitmapDescriptorFactory.fromAsset("Icon_road_yellow_arrow.png"));
list.add(BitmapDescriptorFactory.fromAsset("Icon_road_red_arrow.png"));
list.add(BitmapDescriptorFactory.fromAsset("Icon_road_nofocus.png"));
return list;
}
/**
* 覆写此方法以改变默认终点图标
*
* @return 终点图标
*/
public BitmapDescriptor getTerminalMarker() {
return this.endDescriptor;
}
/**
* 覆写此方法以改变默认点击处理
*
* @param i
* 线路节点的 index
* @return 是否处理了该点击事件
*/
public boolean onRouteNodeClick(int i) {
if (mRouteLine.getAllStep() != null
&& mRouteLine.getAllStep().get(i) != null) {
Log.i("baidumapsdk", "DrivingRouteOverlay onRouteNodeClick");
}
return false;
}
@Override
public final boolean onMarkerClick(Marker marker) {
for (Overlay mMarker : mOverlayList) {
if (mMarker instanceof Marker && mMarker.equals(marker)) {
if (marker.getExtraInfo() != null) {
onRouteNodeClick(marker.getExtraInfo().getInt("index"));
}
}
}
return true;
}
@Override
public boolean onPolylineClick(Polyline polyline) {
boolean flag = false;
for (Overlay mPolyline : mOverlayList) {
if (mPolyline instanceof Polyline && mPolyline.equals(polyline)) {
// 选中
flag = true;
break;
}
}
setFocus(flag);
return true;
}
public void setFocus(boolean flag) {
focus = flag;
for (Overlay mPolyline : mOverlayList) {
if (mPolyline instanceof Polyline) {
// 选中
((Polyline) mPolyline).setFocus(flag);
break;
}
}
}
}