如何自动调整地图7.2视野调整宏

第三方支持(4)
1.可以定位用户当前位置(6.0动态申请权限);
2.当前位置为起点,并根据获取到的终点信息,设置起点终点marker,进行路线规划,获得路线list的第一条数据使用,并在地图上overlay显示,修改默认的路径规划起点终点marker,弹出的bottomsheetdialog中文字显示(此处HTML.fromHtml());
3.将地图中心点调整为用户当前位置,并且根据起点终点距离调整到合适的缩放比例;
4.如果用户手机里安装了百度地图,点击导航,进入百度地图直接导航;如果用户未安装百度地图,则提示用户去安装百度地图(跳转到商店,进入百度地图安装页),或者打开浏览器导航。
5.定位(起点)和获取地理位置编码(终点)均是异步返回的,(因为要通过起点终点的经纬度计算距离)所以需要先得到一个,再去获取另一个,获取到第二个以后去设置起点终点就不会出现有一个可能为空;
6.管理地图的生命周期
7.调整缩放比例走过的坑
1.要在地图加载完成以后设置
2.通过设置地理范围来设置调整地图显示位置及缩放比(之前方法太low了)
***********************************分割线***********************************
LatLngBounds.Builder builder = new LatLngBounds.Builder();
addWorkerMarker2Map(builder);
addCustomMarker2Map(builder);
final LatLngBounds bounds = builder.build();
mBaiduMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {
public void onMapLoaded() {
MapStatusUpdate update = MapStatusUpdateFactory.newLatLngBounds(bounds);
mBaiduMap.setMapStatus(update);
***********************************分割线***********************************
public class BaiduMapActivity extends BaseActivity implements View.OnClickListener {
@BindView(R.id.btnWalk)
ImageButton btnW
@BindView(R.id.btnBike)
ImageButton btnB
@BindView(R.id.btnBus)
ImageButton btnB
@BindView(R.id.btnDrive)
ImageButton btnD
@BindView(R.id.bmapView)
MapView mMapV
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 mBaiduM
private LatLng llS
private LatLng llE
private BDLocation mLocationS
private RoutePlanSearch mS
private GeoCoder mGeoS
private PlanNode stN
private PlanNode enN
private String endN
private String userC
private String userA
private int[] distanceArr = new int[]{20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 25000, 50000, 100000, 200000, 500000, 1000000, 2000000, 5000000, };
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 routeS
private String distanceS
private boolean
private String userN
private String userD
private BitmapDescriptor bitmapE
private BitmapDescriptor bitmapS
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));
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);
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() {
public void setMap() {
setLevel();
MyOnGetGeoCoderResultListener listener = new MyOnGetGeoCoderResultListener(lis);
mGeoSearch.setOnGetGeoCodeResultListener(listener);
* 当llEnd不为null是设置数据
interface OnGetResult {
void setMap();
private class MyOnGetGeoCoderResultListener implements OnGetGeoCoderResultListener {
private OnGetR
public MyOnGetGeoCoderResultListener(OnGetResult lis) {
this.lis =
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));
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) {
if (flag) {
lis.setMap();
MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(llEnd);
if (update != null) {
mBaiduMap.animateMapStatus(update);
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");
int span = 0;
option.setScanSpan(span);
option.setIsNeedAddress(true);
option.setOpenGps(true);
option.setLocationNotify(true);
option.setIsNeedLocationDescribe(true);
option.setIsNeedLocationPoiList(true);
option.setIgnoreKillProcess(false);
option.SetIgnoreCacheException(false);
option.setEnableSimulateGps(false);
mLocationClient.setLocOption(option);
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();
private class MyLocationListener implements BDLocationListener {
public void onReceiveLocation(BDLocation location) {
mLocationClient.stop();
mLocationStart =
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);
bitmapStart = BitmapDescriptorFactory
.fromBitmap(convertViewToBitmap(viewStart));
OverlayOptions option = new MarkerOptions()
.position(llStart)
.icon(bitmapStart);
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));
OverlayOptions option = new MarkerOptions()
.position(llEnd)
.icon(bitmapEnd);
mBaiduMap.addOverlay(option);
private void setLevel() {
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 = ;
for (int i = 0; i & distanceArr. i++) {
if (distanceArr[i] - distance & 0 && distanceArr[i] - distance & min) {
min = distanceArr[i] -
private class MyGetRoutePlanResultListener implements OnGetRoutePlanResultListener {
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) {
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&WalkingRouteLine.WalkingStep& step = result.getRouteLines().get(0).getAllStep();
routeStr = getWalkingRoute(step);
setBottomSheetDialog();
private String getWalkingRoute(List&WalkingRouteLine.WalkingStep& 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();
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) {
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&TransitRouteLine.TransitStep& step = result.getRouteLines().get(0).getAllStep();
routeStr = getTransitRoute(step);
setBottomSheetDialog();
private String getTransitRoute(List&TransitRouteLine.TransitStep& 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();
public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {
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) {
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&DrivingRouteLine.DrivingStep& step = result.getRouteLines().get(0).getAllStep();
routeStr = getDrivingRoute(step);
setBottomSheetDialog();
private String getDrivingRoute(List&DrivingRouteLine.DrivingStep& 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();
public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {
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) {
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&BikingRouteLine.BikingStep& step = result.getRouteLines().get(0).getAllStep();
routeStr = getBikingRoute(step);
setBottomSheetDialog();
private String getBikingRoute(List&BikingRouteLine.BikingStep& 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();
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() {
public void onClick(View v) {
checkNetWorkAvailable();
if (llStart == null || llEnd == null) {
if (isAvilible(BaiduMapActivity.this, "com.baidu.BaiduMap")) {
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());
AlertDialog.Builder builder = new AlertDialog.Builder(BaiduMapActivity.this);
builder.setTitle("提示");
builder.setMessage("是否安装百度地图");
builder.setIcon(R.drawable.ic_launcher);
builder.setPositiveButton("去安装", new DialogInterface.OnClickListener() {
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() {
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() {
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);
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnWalk:
checkNetWorkAvailable();
if (llStart == null || llEnd == null) {
if (mLocationClient != null) {
mLocationClient.start();
showToast(this, "网络错误", TastyToast.ERROR);
mSearch = preparePlanning();
mSearch.walkingSearch((new WalkingRoutePlanOption())
.from(stNode)
.to(enNode));
case R.id.btnBike:
checkNetWorkAvailable();
if (llStart == null || llEnd == null) {
if (mLocationClient != null) {
mLocationClient.start();
showToast(this, "网络错误", TastyToast.ERROR);
mSearch = preparePlanning();
mSearch.bikingSearch((new BikingRoutePlanOption())
.from(stNode)
.to(enNode));
case R.id.btnBus:
checkNetWorkAvailable();
if (llStart == null || llEnd == null) {
if (mLocationClient != null) {
mLocationClient.start();
showToast(this, "网络错误", TastyToast.ERROR);
mSearch = preparePlanning();
mSearch.transitSearch((new TransitRoutePlanOption())
.from(stNode)
.city(mLocationStart.getCity())
.to(enNode));
case R.id.btnDrive:
checkNetWorkAvailable();
if (llStart == null || llEnd == null) {
if (mLocationClient != null) {
mLocationClient.start();
showToast(this, "网络错误", TastyToast.ERROR);
mSearch = preparePlanning();
mSearch.drivingSearch((new DrivingRoutePlanOption())
.from(stNode)
.to(enNode));
protected void onResume() {
super.onResume();
mMapView.onResume();
protected void onPause() {
super.onPause();
mMapView.onPause();
protected void onDestroy() {
super.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);
* 网页版百度地图 有经纬度
* originLat
* originLon
* originName
-&注:必填
* destination
: 当给定region时,认为起点和终点都在同一城市,除非单独给定起点或终点的城市。--&注:必填,不填不会显示导航路线
public static String getWebBaiduMapUri(String originLat, String originLon, String originName, String desLat, String desLon, String destination, String region, String appName) {
String uri = "http://api./direction?origin=latlng:%1$s,%2$s|name:%3$s" +
"&destination=latlng:%4$s,%5$s|name:%6$s&mode=transit&region=%7$s&output=html" +
"&src=%8$s";
return String.format(uri, originLat, originLon, originName, desLat, desLon, destination, region, appName);
* 检查手机上是否安装了指定的软件
* packageName:应用包名
private boolean isAvilible(Context context, String packageName) {
final PackageManager packageManager = context.getPackageManager();
List&PackageInfo& packageInfos = packageManager.getInstalledPackages(0);
List&String& packageNames = new ArrayList&String&();
if (packageInfos != null) {
for (int i = 0; i & packageInfos.size(); i++) {
String packName = packageInfos.get(i).packageN
packageNames.add(packName);
return packageNames.contains(packageName);
private void checkPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
WRITE_COARSE_LOCATION_REQUEST_CODE);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
ACCESS_FINE_LOCATION);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
WRITE_EXTERNAL_STORAGE);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
READ_EXTERNAL_STORAGE);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE},
READ_PHONE_STATE);
百度官方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&OverlayOptions& mOverlayOptionList = null;
List&Overlay& mOverlayList = null;
* 通过一个BaiduMap 对象构造
* baiduMap
public OverlayManager(BaiduMap baiduMap) {
mBaiduMap = baiduM
if (mOverlayOptionList == null) {
mOverlayOptionList = new ArrayList&OverlayOptions&();
if (mOverlayList == null) {
mOverlayList = new ArrayList&Overlay&();
* 覆写此方法设置要管理的Overlay列表
* 管理的Overlay列表
public abstract List&OverlayOptions& getOverlayOptions();
* 将所有Overlay 添加到地图上
public final void addToMap() {
if (mBaiduMap == null) {
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) {
for (Overlay marker : mOverlayList) {
marker.remove();
mOverlayOptionList.clear();
mOverlayList.clear();
* 缩放地图,使所有Overlay都在合适的视野内
* 注: 该方法只对Marker类型的overlay有效
public void zoomToSpan() {
if (mBaiduMap == null) {
if (mOverlayList.size() & 0) {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Overlay overlay : mOverlayList) {
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);
* 设置路线数据。
public void setData(WalkingRouteLine line) {
mRouteLine =
public final List&OverlayOptions& getOverlayOptions() {
if (mRouteLine == null) {
return null;
List&OverlayOptions& overlayList = new ArrayList&OverlayOptions&();
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")));
if (mRouteLine.getStarting() != null) {
overlayList.add((new MarkerOptions())
.position(mRouteLine.getStarting().getLocation())
.icon(getStartMarker() != null ? getStartMarker() :
BitmapDescriptorFactory
.fromAssetWithDpi("Icon_start.png")).zIndex(10));
if (mRouteLine.getTerminal() != null) {
overlayList
.add((new MarkerOptions())
.position(mRouteLine.getTerminal().getLocation())
.icon(getTerminalMarker() != null ? getTerminalMarker() :
BitmapDescriptorFactory
.fromAssetWithDpi("Icon_end.png"))
.zIndex(10));
if (mRouteLine.getAllStep() != null
&& mRouteLine.getAllStep().size() & 0) {
LatLng lastStepLastPoint = null;
for (WalkingRouteLine.WalkingStep step : mRouteLine.getAllStep()) {
List&LatLng& watPoints = step.getWayPoints();
if (watPoints != null) {
List&LatLng& points = new ArrayList&LatLng&();
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 overlayL
private BitmapDescriptor startD
private BitmapDescriptor endD
* 覆写此方法以改变默认起点图标
* 起点图标
public BitmapDescriptor getStartMarker() {
return this.startD
public void setStartDescriptor(BitmapDescriptor startDescriptor) {
this.startDescriptor = startD
public void setEndDescriptor(BitmapDescriptor endDescriptor) {
this.endDescriptor = endD
public int getLineColor() {
* 覆写此方法以改变默认终点图标
* 终点图标
public BitmapDescriptor getTerminalMarker() {
return this.endD
* 处理点击事件
被点击的step在
{@link WalkingRouteLine#getAllStep()}
* 是否处理了该点击事件
public boolean onRouteNodeClick(int i) {
if (mRouteLine.getAllStep() != null
&& mRouteLine.getAllStep().get(i) != null) {
Log.i("baidumapsdk", "WalkingRouteOverlay onRouteNodeClick");
return false;
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;
public boolean onPolylineClick(Polyline polyline) {
return false;
* 用于显示骑行路线的Overlay
public class BikingRouteOverlay extends OverlayManager {
private BikingRouteLine mRouteLine = null;
public BikingRouteOverlay(BaiduMap baiduMap) {
super(baiduMap);
* 设置路线数据。
public void setData(BikingRouteLine line) {
mRouteLine =
public final List&OverlayOptions& getOverlayOptions() {
if (mRouteLine == null) {
return null;
List&OverlayOptions& overlayList = new ArrayList&OverlayOptions&();
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")));
if (mRouteLine.getStarting() != null) {
overlayList.add((new MarkerOptions())
.position(mRouteLine.getStarting().getLocation())
.icon(getStartMarker() != null ? getStartMarker() :
BitmapDescriptorFactory
.fromAssetWithDpi("Icon_start.png")).zIndex(10));
if (mRouteLine.getTerminal() != null) {
overlayList
.add((new MarkerOptions())
.position(mRouteLine.getTerminal().getLocation())
.icon(getTerminalMarker() != null ? getTerminalMarker() :
BitmapDescriptorFactory
.fromAssetWithDpi("Icon_end.png"))
.zIndex(10));
if (mRouteLine.getAllStep() != null
&& mRouteLine.getAllStep().size() & 0) {
LatLng lastStepLastPoint = null;
for (BikingRouteLine.BikingStep step : mRouteLine.getAllStep()) {
List&LatLng& watPoints = step.getWayPoints();
if (watPoints != null) {
List&LatLng& points = new ArrayList&LatLng&();
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 overlayL
private BitmapDescriptor startD
private BitmapDescriptor endD
* 覆写此方法以改变默认起点图标
* 起点图标
public BitmapDescriptor getStartMarker() {
return this.startD
public void setStartDescriptor(BitmapDescriptor startDescriptor) {
this.startDescriptor = startD
public void setEndDescriptor(BitmapDescriptor endDescriptor) {
this.endDescriptor = endD
public int getLineColor() {
* 覆写此方法以改变默认终点图标
* 终点图标
public BitmapDescriptor getTerminalMarker() {
return this.endD
* 处理点击事件
被点击的step在
{@link BikingRouteLine#getAllStep()}
* 是否处理了该点击事件
public boolean onRouteNodeClick(int i) {
if (mRouteLine.getAllStep() != null
&& mRouteLine.getAllStep().get(i) != null) {
Log.i("baidumapsdk", "BikingRouteOverlay onRouteNodeClick");
return false;
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;
public boolean onPolylineClick(Polyline polyline) {
return false;
* 用于显示换乘路线的Overlay,自3.4.0版本起可实例化多个添加在地图中显示
public class TransitRouteOverlay extends OverlayManager {
private TransitRouteLine mRouteLine = null;
* 构造函数
* baiduMap
该TransitRouteOverlay引用的 BaiduMap 对象
public TransitRouteOverlay(BaiduMap baiduMap) {
super(baiduMap);
public final List&OverlayOptions& getOverlayOptions() {
if (mRouteLine == null) {
return null;
List&OverlayOptions& overlayOptionses = new ArrayList&OverlayOptions&();
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));
if (mRouteLine.getAllStep() != null
&& mRouteLine.getAllStep().size() & 0) {
for (TransitRouteLine.TransitStep step : mRouteLine.getAllStep()) {
if (step.getWayPoints() == null) {
int color = 0;
if (step.getStepType() != TransitRouteLine.TransitStep.TransitRouteStepType.WAKLING) {
color = getLineColor() != 0 ? getLineColor() : Color.argb(178, 0, 78, 255);
color = getLineColor() != 0 ? getLineColor() : Color.argb(178, 88, 208, 0);
overlayOptionses.add(new PolylineOptions()
.points(step.getWayPoints()).width(10).color(color)
.zIndex(0));
return overlayO
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");
return null;
* 设置路线数据
* routeOverlay
public void setData(TransitRouteLine routeOverlay) {
this.mRouteLine = routeO
private BitmapDescriptor startD
private BitmapDescriptor endD
* 覆写此方法以改变默认起点图标
* 起点图标
public BitmapDescriptor getStartMarker() {
return this.startD
public void setStartDescriptor(BitmapDescriptor startDescriptor) {
this.startDescriptor = startD
public void setEndDescriptor(BitmapDescriptor endDescriptor) {
this.endDescriptor = endD
public int getLineColor() {
* 覆写此方法以改变默认终点图标
* 终点图标
public BitmapDescriptor getTerminalMarker() {
return this.endD
* 覆写此方法以改变起默认点击行为
被点击的step在
{@link TransitRouteLine#getAllStep()}
* 是否处理了该点击事件
public boolean onRouteNodeClick(int i) {
if (mRouteLine.getAllStep() != null
&& mRouteLine.getAllStep().get(i) != null) {
Log.i("baidumapsdk", "TransitRouteOverlay onRouteNodeClick");
return false;
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;
public boolean onPolylineClick(Polyline polyline) {
return false;
* 用于显示一条驾车路线的overlay,自3.4.0版本起可实例化多个添加在地图中显示,当数据中包含路况数据时,则默认使用路况纹理分段绘制
public class DrivingRouteOverlay extends OverlayManager {
private DrivingRouteLine mRouteLine = null;
boolean focus = false;
* 构造函数
* baiduMap
该DrivingRouteOvelray引用的 BaiduMap
public DrivingRouteOverlay(BaiduMap baiduMap) {
super(baiduMap);
public final List&OverlayOptions& getOverlayOptions() {
if (mRouteLine == null) {
return null;
List&OverlayOptions& overlayOptionses = new ArrayList&OverlayOptions&();
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));
if (mRouteLine.getAllStep() != null
&& mRouteLine.getAllStep().size() & 0) {
List&DrivingStep& steps = mRouteLine.getAllStep();
int stepNum = steps.size();
List&LatLng& points = new ArrayList&LatLng&();
ArrayList&Integer& traffics = new ArrayList&Integer&();
int totalTraffic = 0;
for (int i = 0; i & stepN i++) {
if (i == stepNum - 1) {
points.addAll(steps.get(i).getWayPoints());
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().j++) {
traffics.add(steps.get(i).getTrafficList()[j]);
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 overlayO
* 设置路线数据
* routeLine
public void setData(DrivingRouteLine routeLine) {
this.mRouteLine = routeL
private BitmapDescriptor startD
private BitmapDescriptor endD
* 覆写此方法以改变默认起点图标
* 起点图标
public BitmapDescriptor getStartMarker() {
return this.startD
public void setStartDescriptor(BitmapDescriptor startDescriptor) {
this.startDescriptor = startD
public void setEndDescriptor(BitmapDescriptor endDescriptor) {
this.endDescriptor = endD
* 覆写此方法以改变默认绘制颜色
public int getLineColor() {
public List&BitmapDescriptor& getCustomTextureList() {
ArrayList&BitmapDescriptor& list = new ArrayList&BitmapDescriptor&();
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"));
* 覆写此方法以改变默认终点图标
* 终点图标
public BitmapDescriptor getTerminalMarker() {
return this.endD
* 覆写此方法以改变默认点击处理
线路节点的 index
* 是否处理了该点击事件
public boolean onRouteNodeClick(int i) {
if (mRouteLine.getAllStep() != null
&& mRouteLine.getAllStep().get(i) != null) {
Log.i("baidumapsdk", "DrivingRouteOverlay onRouteNodeClick");
return false;
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;
public boolean onPolylineClick(Polyline polyline) {
boolean flag = false;
for (Overlay mPolyline : mOverlayList) {
if (mPolyline instanceof Polyline && mPolyline.equals(polyline)) {
flag = true;
setFocus(flag);
return true;
public void setFocus(boolean flag) {
for (Overlay mPolyline : mOverlayList) {
if (mPolyline instanceof Polyline) {
((Polyline) mPolyline).setFocus(flag);
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:1706次
排名:千里之外
原创:14篇
(6)(7)(3)(6)

我要回帖

更多关于 王者荣耀如何调整视野 的文章

 

随机推荐