Mapbox的初始化等操作此篇文章不贅述,直接忽略,直接用代碼說明怎麼使用MapBox的路線規劃
1.導入
implementation 'com.mapbox.mapboxsdk:mapbox-android-sdk:6.3.0'
implementation 'com.mapbox.mapboxsdk:mapbox-android-navigation:0.41.0'
目前MapBox只提供以下四種類型的路線規劃
2.大概流程就是通過傳經緯度和路線類型請求數據,然後根據請求回來的數據進行畫線,以下完整代碼是根據“步行”和“駕車”兩種方法規劃出不同的路線,並且繪製出不同顏色。
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap mapboxMap) {
map = mapboxMap;
LatLng latLng = new LatLng(“起點緯度”,"起點經度");
MarkerOptions options = new MarkerOptions();
Icon icon = IconFactory.getInstance(MapActivity.this).fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.map_icon_school));
options.setIcon(icon);
options.setPosition(latLng);
mapboxMap.addMarker(options);
mapboxMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mapboxMap.addMarker(
new MarkerOptions()
.icon(IconFactory.getInstance(MapActivity.this).fromResource(R.mipmap.map_icon_home))
.position(new LatLng(“終點緯度”,"終點經度");
//特別注意,這裏是經度在前,緯度在後
getRoute(Point.fromLngLat(“起點經度”, “起點緯度”),
Point.fromLngLat(“終點經度”, “終點緯度”));
}
});
private void getRoute(Point origin, Point destination) throws ServicesException {
for (int i = 0; i < 2; i++) {
String profile = "";
switch (i) {
case 0:
profile = DirectionsCriteria.PROFILE_WALKING;
break;
case 1:
profile = DirectionsCriteria.PROFILE_DRIVING;
break;
}
MapboxDirections client = MapboxDirections.builder()
.origin(origin)
.destination(destination)
.profile(profile)
.destination(destination)
.accessToken(getString(R.string.mapbox_access_token)).
build();
String finalProfile = profile;
client.enqueueCall(new Callback<DirectionsResponse>() {
@Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
if (response.body() == null) {
return;
}
// Print some info about the route
DirectionsRoute currentRoute = response.body().routes().get(0);
// Draw the route on the map
drawRoute(currentRoute, finalProfile);
}
@Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
Toast.makeText(MapActivity.this, "Error: " + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
private void drawRoute(DirectionsRoute route, String profile) {
// Convert LineString coordinates into LatLng[]
LineString lineString = LineString.fromPolyline(route.geometry(), Constants.PRECISION_5);
List<Point> coordinates = lineString.coordinates();
LatLng[] points = new LatLng[coordinates.size()];
for (int i = 0; i < coordinates.size(); i++) {
points[i] = new LatLng(
coordinates.get(i).latitude() / 10,
coordinates.get(i).longitude()
/ 10
);
}
String color = "#30d176";
switch (profile) {
case DirectionsCriteria.PROFILE_WALKING:
color = "#30d176";
break;
case DirectionsCriteria.PROFILE_DRIVING:
color = "#48bef3";
break;
}
// Draw Points on MapView
map.addPolyline(new PolylineOptions()
.add(points)
.color(Color.parseColor(color))
.width(5));
}