准备工作
1.Mapbox 的账户和 access token(项目中需要用到)
2.一个包含了 Mapbox Android SDK 的安卓应用
安装导航SDK
在模块级别的 build.gradle 中添加依赖,如下:
repositories {
mavenCentral()
maven { url 'https://mapbox.bintray.com/mapbox' }
}
dependencies {
implementation 'com.mapbox.mapboxsdk:mapbox-android-navigation-ui:0.41.0'
}
注意,导入 navigation-ui SDK 之后,会自动导入对应版本的 Mapbox 的 Navigation SDK 和 Maps SDK,所以在此处只需要声明一个即可。
另外,最好不要手动额外添加明确版本的 Maps SDK 在 build.gradle 中,以免出现版本不适配等未知的错误。
初始化地图
1.AndroidManifest.xml :设置权限,Application的组成(例如Activity)
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
2.activity_main.xml :样式文件,我们将会在里面添加一个 MapView 对象,用以初始化地图
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mapbox="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.mapbox.mapboxsdk.maps.MapView
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
mapbox:mapbox_cameraTargetLat="38.9098"
mapbox:mapbox_cameraTargetLng="-77.0295"
mapbox:mapbox_cameraZoom="12" />
</android.support.constraint.ConstraintLayout>
3.strings.xml :存放字符常量的文件,用于配置项目的名字和 access token
<resources>
<string name="app_name">Navigation map</string>
<string name="access_token" translatable="false">YOUR_MAPBOX_ACCESS_TOKEN</string>
<string name="user_location_permission_explanation">This app needs location permissions to show its functionality.</string>
<string name="user_location_permission_not_granted">You didn\'t grant location permissions.</string>
</resources>
4.MainActivity.java :实行定位和导航功能,初始化代码和最终的文件结构如下
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, MapboxMap.OnMapClickListener, PermissionsListener {
// variables for adding location layer
private MapView mapView;
private MapboxMap mapboxMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.access_token));
setContentView(R.layout.activity_main);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
// 异步加载地图,回调方法
@Override
public void onMapReady(@NonNull final MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
mapboxMap.setStyle(getString(R.string.navigation_guidance_day), new Style.OnStyleLoaded() {
});
}
private void addDestinationIconSymbolLayer(@NonNull Style loadedMapStyle) {
}
@SuppressWarnings( {"MissingPermission"})
@Override
public boolean onMapClick(@NonNull LatLng point) {
}
private void getRoute(Point origin, Point destination) {
}
@SuppressWarnings( {"MissingPermission"})
private void enableLocationComponent(@NonNull Style loadedMapStyle) {
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
}
@Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
}
@Override
public void onPermissionResult(boolean granted) {
}
// 生命周期方法
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
5.import packages:导入 java 文件需要的相关 package,可以提起导入,可以之后再声明
import android.graphics.BitmapFactory;
import android.os.Bundle;
import java.util.List;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
// classes needed to initialize map
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.Style;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
定位用户位置
实现定位功能需要确保此前已经给与真机或模拟器位置权限。
1.导入相关的 package
// classes needed to add the location component
import com.mapbox.android.core.permissions.PermissionsListener;
import com.mapbox.android.core.permissions.PermissionsManager;
import com.mapbox.mapboxsdk.location.LocationComponent;
import com.mapbox.mapboxsdk.location.modes.CameraMode;
2.声明变量
// variables for adding location layer
private PermissionsManager permissionsManager;
private LocationComponent locationComponent;
3.相关函数
// 动态检查权限
@SuppressWarnings( {"MissingPermission"})
private void enableLocationComponent(@NonNull Style loadedMapStyle) {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
// Activate the MapboxMap LocationComponent to show user location
// Adding in LocationComponentOptions is also an optional parameter
locationComponent = mapboxMap.getLocationComponent();
locationComponent.activateLocationComponent(this, loadedMapStyle);
locationComponent.setLocationComponentEnabled(true);
// Set the component's camera mode
locationComponent.setCameraMode(CameraMode.TRACKING);
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
// 调出提示标语
@Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
Toast.makeText(this, R.string.user_location_permission_explanation, Toast.LENGTH_LONG).show();
}
// 判断权限开启结果
@Override
public void onPermissionResult(boolean granted) {
if (granted) {
enableLocationComponent(mapboxMap.getStyle());
} else {
Toast.makeText(this, R.string.user_location_permission_not_granted, Toast.LENGTH_LONG).show();
finish();
}
}
4.在 onMapReady 方法中调用 enableLocationComponent(),以在地图加载完毕后,获取用户的位置
@Override
public void onMapReady(@NonNull final MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
mapboxMap.setStyle(getString(R.string.navigation_guidance_day), new Style.OnStyleLoaded() {
@Override
public void onStyleLoaded(@NonNull Style style) {
enableLocationComponent(style);
}
});
}
打开应用APP后,可以发现在地图上,自己的当前位置被用蓝色圆圈标记了出来。
点击地图进行标记
在实现路径导航之前,需要先行获取用户的目的地,此处使用的方法是用户点击地图上的任意位置,设置标记点。
1.导入相关的 package
// classes needed to add a marker
import com.mapbox.geojson.Feature;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.style.layers.SymbolLayer;
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconAllowOverlap;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconIgnorePlacement;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconImage;
2.监听地图点击事件
@SuppressWarnings( {"MissingPermission"})
@Override
public boolean onMapClick(@NonNull LatLng point) {
Point destinationPoint = Point.fromLngLat(point.getLongitude(), point.getLatitude());
Point originPoint = Point.fromLngLat(locationComponent.getLastKnownLocation().getLongitude(),
locationComponent.getLastKnownLocation().getLatitude());
GeoJsonSource source = mapboxMap.getStyle().getSourceAs("destination-source-id");
if (source != null) {
source.setGeoJson(Feature.fromGeometry(destinationPoint));
}
return true;
}
3.添加图层,用于放置Marker
private void addDestinationIconSymbolLayer(@NonNull Style loadedMapStyle) {
loadedMapStyle.addImage("destination-icon-id",
BitmapFactory.decodeResource(this.getResources(), R.drawable.mapbox_marker_icon_default));
GeoJsonSource geoJsonSource = new GeoJsonSource("destination-source-id");
loadedMapStyle.addSource(geoJsonSource);
SymbolLayer destinationSymbolLayer = new SymbolLayer("destination-symbol-layer-id", "destination-source-id");
destinationSymbolLayer.withProperties(
iconImage("destination-icon-id"),
iconAllowOverlap(true),
iconIgnorePlacement(true)
);
loadedMapStyle.addLayer(destinationSymbolLayer);
}
4.在 OnMapReady 方法中调用 addDestinationIconSymbolLayer(),设置监听器
@Override
public void onMapReady(@NonNull final MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
mapboxMap.setStyle(getString(R.string.navigation_guidance_day), new Style.OnStyleLoaded() {
@Override
public void onStyleLoaded(@NonNull Style style) {
enableLocationComponent(style); // 获取位置
addDestinationIconSymbolLayer(style); // 添加标记图层
mapboxMap.addOnMapClickListener(MainActivity.this); // 监听点击事件
}
});
}
现在,点击地图上任意位置,就可以设置Marker标记了。
获取路径
1.导入相关 package
// classes to calculate a route
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncherOptions;
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import android.util.Log;
2.定义相关变量
// variables for calculating and drawing a route
private DirectionsRoute currentRoute;
private static final String TAG = "DirectionsActivity";
private NavigationMapRoute navigationMapRoute;
3.在 getRoute() 方法中获取 currentRoute,并添加到地图上
private void getRoute(Point origin, Point destination) {
NavigationRoute.builder(this)
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
@Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().routes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
currentRoute = response.body().routes().get(0);
// 在地图上绘制出路线
if (navigationMapRoute != null) {
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(null, mapView, mapboxMap, R.style.NavigationMapRoute);
}
navigationMapRoute.addRoute(currentRoute);
}
@Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
}
});
}
4.在 OnMapClick 监听方法中使用 getRoute(),实时更新路径
@SuppressWarnings( {"MissingPermission"})
@Override
public boolean onMapClick(@NonNull LatLng point) {
Point destinationPoint = Point.fromLngLat(point.getLongitude(), point.getLatitude());
Point originPoint = Point.fromLngLat(locationComponent.getLastKnownLocation().getLongitude(),
locationComponent.getLastKnownLocation().getLatitude());
GeoJsonSource source = mapboxMap.getStyle().getSourceAs("destination-source-id");
if (source != null) {
source.setGeoJson(Feature.fromGeometry(destinationPoint));
}
getRoute(originPoint, destinationPoint);
return true;
}
效果图:
导航
我们在地图界面添加一个按钮,当用户点击地图确认目的地,并获取路线后,点击按钮可以跳转到导航页面。
1.修改 colors.xml 定义按钮等颜色样式
<color name="colorPrimary">#33C377</color>
<color name="colorPrimaryDark">#FF218450</color>
<color name="colorAccent">#FF4081</color>
<color name="mapboxWhite">#ffffff</color>
<color name="mapboxBlue">#4264fb</color>
<color name="mapboxGrayLight">#c6d2e1</color>
<color name="mapboxPink">#ee4e8b</color>
<color name="mapboxYellow">#d9d838</color>
<color name="mapboxRed">#b43b71</color>
2.在 activity_main.xml 中添加按钮 Button 组件,在App刚刚的时候,按钮呈灰色(不可点击状态)
<Button
android:id="@+id/startButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:background="@color/mapboxGrayLight"
android:enabled="false"
android:text="Start navigation"
android:textColor="@color/mapboxWhite"
mapbox:layout_constraintStart_toStartOf="parent"
mapbox:layout_constraintTop_toTopOf="parent" />
3.导入相关的package
// classes needed to launch navigation UI
import android.view.View;
import android.widget.Button;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncher;
4.声明变量
// variables needed to initialize navigation
private Button button;
5.在 OnMapReady 方法中注册 Button,并绑定监听事件
@Override
public void onMapReady(@NonNull final MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
mapboxMap.setStyle(getString(R.string.navigation_guidance_day), new Style.OnStyleLoaded() {
@Override
public void onStyleLoaded(@NonNull Style style) {
enableLocationComponent(style); // 获取位置
addDestinationIconSymbolLayer(style); // 添加标记图层
mapboxMap.addOnMapClickListener(MainActivity.this); // 监听点击事件
button = findViewById(R.id.startButton); // 点击按钮,开启导航
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean simulateRoute = true;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(currentRoute)
.shouldSimulateRoute(simulateRoute)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(MainActivity.this, options);
}
});
}
});
}
6.在 OnMapClick 监听方法中设置激活 Button
@SuppressWarnings( {"MissingPermission"})
@Override
public boolean onMapClick(@NonNull LatLng point) {
Point destinationPoint = Point.fromLngLat(point.getLongitude(), point.getLatitude());
Point originPoint = Point.fromLngLat(locationComponent.getLastKnownLocation().getLongitude(),
locationComponent.getLastKnownLocation().getLatitude());
GeoJsonSource source = mapboxMap.getStyle().getSourceAs("destination-source-id");
if (source != null) {
source.setGeoJson(Feature.fromGeometry(destinationPoint));
}
getRoute(originPoint, destinationPoint);
button.setEnabled(true);
button.setBackgroundResource(R.color.mapboxBlue);
return true;
}
效果图如下:
隐藏 logo
参考 UiSettings API ( https://docs.mapbox.com/android/api/map-sdk/8.3.0/com/mapbox/mapboxsdk/maps/UiSettings.html)可以找到解决方案:在OnMapReady方法中禁用归属和标识,添加如下代码
mapboxMap.getUiSettings().setAttributionEnabled(false);
mapboxMap.getUiSettings().setLogoEnabled(false);