一、概述
这一章我们学习高德地图的路线规划,主要分为驾车路线,步行路线,公交路线,骑行路线。在高德地图中数据的获取使用方式都比较相似,本章的路线规划查询也不例外。需要一个查询实列,然后设置查询条件,查询结果在监听方法中回调。
二、本章内容
通过RouteSearch类,来进行路线的查询
routeSearch = new RouteSearch(this);
routeSearch.setRouteSearchListener(this);
//实现不同路线查询的回调方法
@Override
public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {
}
@Override
public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {
}
@Override
public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {
}
@Override
public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {
}
1.驾车路线
//构建开始点与终止点的经纬度数据
RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
new LatLonPoint(start.getLat(), start.getLng()),
new LatLonPoint(end.getLat(), end.getLng()));
// fromAndTo包含路径规划的起点和终点,drivingMode表示驾车模式
// 第三个参数表示途经点(最多支持16个), 第四个参数表示避让区域(最多支持32个),第五个参数表示避让道路
RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(
fromAndTo, DRIVING_SINGLE_DEFAULT, null, null, "");
routeSearch.calculateDriveRouteAsyn(query);
RouteSearch.DriveRouteQuery构造方法的第二个参数为驾车模式,即驾车策略
2.步行路线
RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
new LatLonPoint(start.getLat(), start.getLng()),
new LatLonPoint(end.getLat(), end.getLng()));
RouteSearch.WalkRouteQuery query = new RouteSearch.WalkRouteQuery(
fromAndTo, RouteSearch.WALK_DEFAULT);
routeSearch.calculateWalkRouteAsyn(query);
在步行路线中提供了两种模式 RouteSearch.WALK_DEFAULT 和 RouteSearch.WALK_MULTI_PATH。
3.公交路线
RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
new LatLonPoint(start.getLat(), start.getLng()),
new LatLonPoint(end.getLat(), end.getLng()));
RouteSearch.BusRouteQuery query = new
// 第三个参数表示公交查询城市区号,第四个参数表示是否计算夜班车,
//0表示不计算,1表示计算RouteSearch.BusRouteQuery(
fromAndTo, RouteSearch.BUS_LEASE_WALK, "028", 0);
routeSearch.calculateBusRouteAsyn(query);
注意:公交路线在查询后返回结果可能有多条路线,每一条路线又被分为了很多段,例如:到达目的地可能会换成公交,步行等。在这每一段中会有步行数据与公交数据,因为定位开始与结束不一定就在公交站附近,所以一般的拼接整个路线时,把步行数据点放在前面然后再添加公交路线的点,最后一段一般没有公交路线点的数据,只有步行点的数据
4.骑行路线
RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
new LatLonPoint(start.getLat(), start.getLng()),
new LatLonPoint(end.getLat(), end.getLng()));
RouteSearch.RideRouteQuery query = new RouteSearch.RideRouteQuery(
fromAndTo, RouteSearch.RIDING_DEFAULT);
routeSearch.calculateRideRouteAsyn(query);
代码:
路线显示Activity
public class RouteActivity extends BaseActivity implements RouteSearch.OnRouteSearchListener {
@BindView(R.id.route_map_view)
MapView routeMapView;
@BindView(R.id.route_start_text)
TextView routeStartText;
@BindView(R.id.route_start_edit)
EditText routeStartEdit;
@BindView(R.id.route_end_text)
TextView routeEndText;
@BindView(R.id.route_end_edit)
EditText routeEndEdit;
@BindView(R.id.route_rg)
RadioGroup routeRg;
@BindView(R.id.route_start_location_btn)
ImageView routeStartLocationBtn;
@BindView(R.id.route_end_location_btn)
ImageView routeEndLocationBtn;
@BindView(R.id.route_search_btn)
Button routeSearchBtn;
private final static int START_POSITION = 100;
private final static int END_POSITION = 101;
private Unbinder binder;
private AMap aMap;
private RouteSearch routeSearch;
//开始点的数据
private DataLocation start;
//结束点的数据
private DataLocation end;
@Override
public void setContentView(@Nullable Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_route);
binder = ButterKnife.bind(this);
routeMapView.onCreate(savedInstanceState);
}
@Override
public void initData() {
aMap = routeMapView.getMap();
routeSearch = new RouteSearch(this);
routeSearch.setRouteSearchListener(this);
moveToDefaultPosition();
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onDestroy() {
if (binder != null)
binder.unbind();
super.onDestroy();
}
/**
* 移动到默认的位置
* */
private void moveToDefaultPosition() {
//移动到marker位置
CameraUpdate mCameraUpdate = CameraUpdateFactory.newCameraPosition(
new CameraPosition(
new LatLng(30.665, 104.065),
15,
0,
0
)
);
aMap.moveCamera(mCameraUpdate);
}
/**
* 移动到指定经纬度位置,此经纬度只限高德地图中获取的火星坐标
* */
private void moveToPosition(double lat, double lng) {
//移动到marker位置
CameraUpdate mCameraUpdate = CameraUpdateFactory.newCameraPosition(
new CameraPosition(
new LatLng(lat, lng),
13,
0,
0
)
);
aMap.moveCamera(mCameraUpdate);
}
@Override
public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {
Log.e("CF", "onBusRouteSearched: " + i);
aMap.clear();
//几种公交路线
List busPathList = busRouteResult.getPaths();
//选择第一条
List busSteps = busPathList.get(0).getSteps();
for (BusStep bs : busSteps) {
//获取该条路线某段公交路程步行的点
RouteBusWalkItem routeBusWalkItem = bs.getWalk();
if(routeBusWalkItem != null){
List wsList = routeBusWalkItem.getSteps();
ArrayList walkPoint = new ArrayList<>();
for (WalkStep ws :wsList){
List points = ws.getPolyline();
for (LatLonPoint lp : points){
walkPoint.add(new LatLng(lp.getLatitude(),lp.getLongitude()));
}
}
//添加步行点
aMap.addPolyline(new PolylineOptions()
.addAll(walkPoint)
.width(40)
//是否开启纹理贴图
.setUseTexture(true)
//绘制成大地线
.geodesic(false)
//设置纹理样式
.setCustomTexture(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.custtexture2)))
//设置画线的颜色
.color(Color.argb(200, 0, 0, 0)));
}
//获取该条路线某段公交路路程的点
List rbli = bs.getBusLines();
ArrayList busPoint = new ArrayList<>();
for (RouteBusLineItem one: rbli){
List points = one.getPolyline();
for (LatLonPoint lp : points){
busPoint.add(new LatLng(lp.getLatitude(),lp.getLongitude()));
}
}
//添加公交路线点
aMap.addPolyline(new PolylineOptions()
.addAll(busPoint)
.width(40)
//是否开启纹理贴图
.setUseTexture(true)
//绘制成大地线
.geodesic(false)
//设置纹理样式
.setCustomTexture(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.custtexture)))
//设置画线的颜色
.color(Color.argb(200, 0, 0, 0)));
}
}
@Override
public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {
Log.e("CF", "onDriveRouteSearched: " + i);
List pathList = driveRouteResult.getPaths();
List driverPath = new ArrayList<>();
for (DrivePath dp : pathList) {
List stepList = dp.getSteps();
for (DriveStep ds : stepList) {
List points = ds.getPolyline();
for (LatLonPoint llp : points) {
driverPath.add(new LatLng(llp.getLatitude(), llp.getLongitude()));
}
}
}
aMap.clear();
aMap.addPolyline(new PolylineOptions()
.addAll(driverPath)
.width(40)
//是否开启纹理贴图
.setUseTexture(true)
//绘制成大地线
.geodesic(false)
//设置纹理样式
.setCustomTexture(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.custtexture)))
//设置画线的颜色
.color(Color.argb(200, 0, 0, 0)));
}
@Override
public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {
List pathList = walkRouteResult.getPaths();
List walkPaths = new ArrayList<>();
for (WalkPath dp : pathList) {
List stepList = dp.getSteps();
for (WalkStep ds : stepList) {
List points = ds.getPolyline();
for (LatLonPoint llp : points) {
walkPaths.add(new LatLng(llp.getLatitude(), llp.getLongitude()));
}
}
}
aMap.clear();
aMap.addPolyline(new PolylineOptions()
.addAll(walkPaths)
.width(40)
//是否开启纹理贴图
.setUseTexture(true)
//绘制成大地线
.geodesic(false)
//设置纹理样式
.setCustomTexture(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.custtexture)))
//设置画线的颜色
.color(Color.argb(200, 0, 0, 0)));
}
@Override
public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {
List pathList = rideRouteResult.getPaths();
List walkPaths = new ArrayList<>();
for (RidePath dp : pathList) {
List stepList = dp.getSteps();
for (RideStep ds : stepList) {
List points = ds.getPolyline();
for (LatLonPoint llp : points) {
walkPaths.add(new LatLng(llp.getLatitude(), llp.getLongitude()));
}
}
}
aMap.clear();
aMap.addPolyline(new PolylineOptions()
.addAll(walkPaths)
.width(40)
//是否开启纹理贴图
.setUseTexture(true)
//绘制成大地线
.geodesic(false)
//设置纹理样式
.setCustomTexture(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.custtexture)))
//设置画线的颜色
.color(Color.argb(200, 0, 0, 0)));
}
@OnClick({R.id.route_start_location_btn, R.id.route_end_location_btn})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.route_start_location_btn:
Intent intent = new Intent(RouteActivity.this, LocationActivity.class);
intent.putExtra("request_code", START_POSITION);
startActivityForResult(intent, START_POSITION);
break;
case R.id.route_end_location_btn:
Intent intent2 = new Intent(RouteActivity.this, LocationActivity.class);
intent2.putExtra("request_code", END_POSITION);
startActivityForResult(intent2, END_POSITION);
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
DataLocation dl = (DataLocation) data.getSerializableExtra("data");
if (resultCode == START_POSITION) {
routeStartEdit.setText("");
routeStartEdit.setText(dl.getAddress());
start = dl;
moveToPosition(dl.getLat(),dl.getLng());
} else if (resultCode == END_POSITION) {
routeEndEdit.setText("");
routeEndEdit.setText(dl.getAddress());
end = dl;
}
}
@OnClick(R.id.route_search_btn)
public void onViewClicked() {
switch (routeRg.getCheckedRadioButtonId()) {
case R.id.route_driver_rb:
if (start != null && end != null) {
RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(new LatLonPoint(start.getLat(), start.getLng()),
new LatLonPoint(end.getLat(), end.getLng()));
RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, DRIVING_SINGLE_DEFAULT, null, null, "");
routeSearch.calculateDriveRouteAsyn(query);
} else {
Toast.makeText(this, "驾车定位数据无效", Toast.LENGTH_SHORT).show();
}
break;
case R.id.route_bus_rb:
if (start != null && end != null) {
RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
new LatLonPoint(start.getLat(), start.getLng()),
new LatLonPoint(end.getLat(), end.getLng()));
RouteSearch.BusRouteQuery query = new RouteSearch.BusRouteQuery(
fromAndTo, RouteSearch.BUS_LEASE_WALK, "028", 0);
routeSearch.calculateBusRouteAsyn(query);
} else {
Toast.makeText(this, "公交定位数据无效", Toast.LENGTH_SHORT).show();
}
break;
case R.id.route_walk_rb:
if (start != null && end != null) {
RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
new LatLonPoint(start.getLat(), start.getLng()),
new LatLonPoint(end.getLat(), end.getLng()));
RouteSearch.WalkRouteQuery query = new RouteSearch.WalkRouteQuery(
fromAndTo, RouteSearch.WALK_DEFAULT);
routeSearch.calculateWalkRouteAsyn(query);
} else {
Toast.makeText(this, "步行定位数据无效", Toast.LENGTH_SHORT).show();
}
break;
case R.id.route_ride_rb:
if (start != null && end != null) {
RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
new LatLonPoint(start.getLat(), start.getLng()),
new LatLonPoint(end.getLat(), end.getLng()));
RouteSearch.RideRouteQuery query = new RouteSearch.RideRouteQuery(
fromAndTo, RouteSearch.RIDING_DEFAULT);
routeSearch.calculateRideRouteAsyn(query);
} else {
Toast.makeText(this, "骑行定位数据无效", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
}
定位Activity
public class LocationActivity extends BaseActivity implements AMap.OnCameraChangeListener, GeocodeSearch.OnGeocodeSearchListener {
@BindView(R.id.location_map_view)
MapView locationMapView;
@BindView(R.id.location_location)
ImageView routeLocation;
@BindView(R.id.location_sure_btn)
Button locationSureBtn;
private Unbinder binder;
private AMap aMap;
private GeocodeSearch geocodeSearch;
private Marker marker;
private int requestCode;
@Override
public void setContentView(@Nullable Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_location);
binder = ButterKnife.bind(this);
locationMapView.onCreate(savedInstanceState);
}
@Override
public void initData() {
aMap = locationMapView.getMap();
aMap.setOnCameraChangeListener(this);
geocodeSearch = new GeocodeSearch(this);
geocodeSearch.setOnGeocodeSearchListener(this);
requestCode = getIntent().getIntExtra("request_code", -1);
moveToDefaultPosition();
}
private void moveToDefaultPosition() {
//移动到marker位置
CameraUpdate mCameraUpdate = CameraUpdateFactory.newCameraPosition(
new CameraPosition(
new LatLng(30.665, 104.065),
15,
0,
0
)
);
aMap.moveCamera(mCameraUpdate);
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onDestroy() {
if (binder != null)
binder.unbind();
super.onDestroy();
}
@Override
public void onCameraChange(CameraPosition cameraPosition) {
LatLng latLng = cameraPosition.target;
Log.e("CF", "onCameraChange: Lat=" + latLng.latitude + " lng=" + latLng.longitude);
aMap.clear();
if (marker != null) {
marker.destroy();
marker = null;
}
}
@Override
public void onCameraChangeFinish(CameraPosition cameraPosition) {
//获取屏幕中心点在高德地图上的经纬度
LatLng latLng = cameraPosition.target;
Log.e("CF", "onCameraChangeFinish: Lat=" + latLng.latitude + " lng=" + latLng.longitude);
MarkerOptions mo = new MarkerOptions();
mo.position(latLng)
//设置透明度
.alpha(1.0f)
//设置title
.title("自定义标题")
//设置内容
.snippet("自定义内容")
//设置锚点,锚点是marker图标的位置,(0,0)-(1,1)
.anchor(0.5f, 1.0f)
//是否可见
.visible(true)
//是否可拖动,注意这里需要长按marker后,才可以拖动
.draggable(true)
//添加自定义marker图标
.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.location2)))
//是否平贴地图,倾斜地图,感觉marker不是竖直而是粘贴在地面上
.setFlat(false)
//是否允许显示infoWindow
.infoWindowEnable(true)
//z轴方向的值,重叠
.zIndex(10)
//设置marker图片旋转角度,正北开始逆时针方向计算
.rotateAngle(0.0f)
//设置infoWindow的偏移位置
.setInfoWindowOffset(0, 0);
marker = aMap.addMarker(mo);
RegeocodeQuery query = new RegeocodeQuery(new LatLonPoint(latLng.latitude, latLng.longitude), 10f, GeocodeSearch.AMAP);
//异步查询
geocodeSearch.getFromLocationAsyn(query);
}
@Override
public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
RegeocodeAddress regeocodeAddress = regeocodeResult.getRegeocodeAddress();
String formatAddress = regeocodeAddress.getFormatAddress();
String city = regeocodeAddress.getCity();
if (marker != null) {
marker.setTitle(city);
marker.setSnippet(formatAddress);
marker.showInfoWindow();
}
}
@Override
public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
}
@OnClick(R.id.location_sure_btn)
public void onViewClicked() {
if (marker != null) {
String address = marker.getSnippet();
if (address != null && address.length() > 0 && requestCode != -1) {
Intent intent = new Intent();
DataLocation dl = new DataLocation();
dl.setAddress(address);
dl.setLat(marker.getPosition().latitude);
dl.setLng(marker.getPosition().longitude);
intent.putExtra("data", dl);
setResult(requestCode, intent);
finish();
return;
}
}
Toast.makeText(this, "定位不成功", Toast.LENGTH_SHORT).show();
}
}
//Activity通信数据结构
public class DataLocation implements Serializable{
private String address;
private double lat;
private double lng;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
}