Java Mapbox Android:如何获取从当前位置到您选择的目的地的方向?
好吧,我对Mapbox还比较陌生,在这之前我使用过GMAP,但我发现Mapbox更能满足我的需要,问题是我遇到了一些麻烦 我使用了他们网站上的示例组合,例如 及 我试图允许用户搜索目的地,然后将其转换为坐标,用于在地图中绘图。然后我想画一条从他们当前位置到目的地的路线,这就是我的问题所在Java Mapbox Android:如何获取从当前位置到您选择的目的地的方向?,java,android,dictionary,mapbox,directions,Java,Android,Dictionary,Mapbox,Directions,好吧,我对Mapbox还比较陌生,在这之前我使用过GMAP,但我发现Mapbox更能满足我的需要,问题是我遇到了一些麻烦 我使用了他们网站上的示例组合,例如 及 我试图允许用户搜索目的地,然后将其转换为坐标,用于在地图中绘图。然后我想画一条从他们当前位置到目的地的路线,这就是我的问题所在 mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(MapboxM
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap mapboxMap) {
map = mapboxMap;
// Set the origin waypoint to the devices location
Position origin = Position.fromCoordinates(mapboxMap.getMyLocation().getLongitude(), mapboxMap.getMyLocation().getLatitude());
// Set the destination waypoint to the location point long clicked by the user
final Position destination = updateMap(feature.getLongitude(), feature.getLatitude());
mapboxMap.addMarker(new MarkerOptions()
.position(new LatLng(origin.getLatitude(), origin.getLongitude()))
.title("Origin")
.snippet("Alhambra"));
mapboxMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, destination.getLongitude()))
.title("Destination")
.snippet("Plaza del Triunfo"));
// Get route from API
try {
getRoute(origin, destination);
} catch (ServicesException e) {
e.printStackTrace();
}
}
});
AndroidGeocoder geocoder = new AndroidGeocoder(context, Locale.getDefault());
geocoder.setAccessToken(MAPBOX_ACCESS_TOKEN);
addresses = geocoder.getFromLocation(
location.getLatitude(),
location.getLongitude(),
1);
// Set up autocomplete widget
GeocoderAutoCompleteView autocomplete = (GeocoderAutoCompleteView) findViewById(R.id.query);
autocomplete.setAccessToken("pk.eyJ1IjoiYmV1dHJveCIsImEiOiJjaW5ybzlwYnQwMGlqdnhtMno3cmtwNTlqIn0.y16mZzmertL4-eEfQNGeqQ");
autocomplete.setType(GeocodingCriteria.TYPE_POI);
autocomplete.setOnFeatureListener(new GeocoderAutoCompleteView.OnFeatureListener() {
@Override
public void OnFeatureClick(GeocodingFeature feature) {
Position position = feature.asPosition();
updateMap(position.getLatitude(), position.getLongitude());
}
});
}
private void getRoute(Position origin, Position destination) throws ServicesException {
MapboxDirections client = new MapboxDirections.Builder()
.setOrigin(origin)
.setDestination(destination)
.setProfile(DirectionsCriteria.PROFILE_CYCLING)
.setAccessToken("pk.eyJ1IjoiYmV1dHJveCIsImEiOiJjaW5ybzlwYnQwMGlqdnhtMno3cmtwNTlqIn0.y16mZzmertL4-eEfQNGeqQ")
.build();
client.enqueueCall(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;
}
// Display some info about the route
currentRoute = response.body().getRoutes().get(0);
Log.d(TAG, "Distance: " + currentRoute.getDistance());
Toast.makeText(MainActivity.this, "Route is " + currentRoute.getDistance() + " meters long.", Toast.LENGTH_SHORT).show();
// Draw the route on the map
drawRoute(currentRoute);
}
@Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
Log.e(TAG, "Error: " + t.getMessage());
Toast.makeText(MainActivity.this, "Error: " + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void drawRoute(DirectionsRoute route) {
// Convert LineString coordinates into LatLng[]
LineString lineString = LineString.fromPolyline(route.getGeometry(), Constants.OSRM_PRECISION_V5);
List<Position> coordinates = lineString.getCoordinates();
LatLng[] points = new LatLng[coordinates.size()];
for (int i = 0; i < coordinates.size(); i++) {
points[i] = new LatLng(
coordinates.get(i).getLatitude(),
coordinates.get(i).getLongitude());
}
// Draw Points on MapView
map.addPolyline(new PolylineOptions()
.add(points)
.color(Color.parseColor("#009688"))
.width(5));
}
private void myLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mapView.setMyLocationEnabled(true);
mapView.setMyLocationTrackingMode(MyLocationTracking.TRACKING_FOLLOW);
mapView.getMyLocation();
}
mapView.getMapAsync(新的OnMapReadyCallback(){
@凌驾
mapready上的公共无效(MapboxMap MapboxMap){
map=mapboxMap;
//将原点航路点设置到设备位置
位置原点=位置.fromCoordinates(mapboxMap.getMyLocation().GetLength(),mapboxMap.getMyLocation().getLatitude());
//将目的地航路点设置为用户长时间单击的位置点
最终位置目标=更新映射(feature.getLongitude(),feature.getLatitude());
addMarker(新的MarkerOptions()
.位置(新车床(origin.getLatitude(),origin.getLongitude())
.名称(“来源”)
.片段(“阿罕布拉”);
addMarker(新的MarkerOptions()
.position(新LatLng(纬度,目的地.getLongitude()))
.标题(“目的地”)
.片段(“Triunfo广场”);
//从API获取路由
试一试{
getRoute(起点、终点);
}捕获(服务异常e){
e、 printStackTrace();
}
}
});
AndroidGeocoder geocoder=新的AndroidGeocoder(上下文,Locale.getDefault());
geocoder.setAccessToken(MAPBOX\u ACCESS\u TOKEN);
地址=geocoder.getFromLocation(
location.getLatitude(),
location.getLongitude(),
1);
//设置自动完成小部件
GeocoderAutoCompleteView自动完成=(GeocoderAutoCompleteView)findViewById(R.id.query);
autocomplete.setAccessToken(“pk.eyj1ijoiymv1dhjvecismeioijjaw5ybzlwynqwmglqdnhtmno3cmtwntlqin0.y16mZzmertL4 eEfQNGeqQ”);
自动完成.setType(地理编码标准.TYPE_POI);
autocomplete.setOnFeatureListener(新的地理代码rautoCompleteView.OnFeatureListener(){
@凌驾
公共void on功能单击(地理编码功能){
位置=特征.asPosition();
updateMap(position.getLatitude(),position.getLatitude());
}
});
}
私有void getRoute(位置原点、位置目标)引发ServicesException{
MapboxDirections客户端=新建MapboxDirections.Builder()
.setOrigin(origin)
.setDestination(目的地)
.setProfile(方向标准.PROFILE\U循环)
.setAccessToken(“pk.eyj1ijoiymv1dhjvecisimeijjaw5ybzlwynqwmglqdnhtmno3cmtwntlqin0.y16mZzmertL4 eEfQNGeqQ”)
.build();
client.enqueueCall(新回调(){
@凌驾
公共void onResponse(调用、响应){
//您可以获取有关响应的通用HTTP信息
Log.d(标签,“响应代码:”+Response.code());
if(response.body()==null){
Log.e(标记“未找到路由,请确保设置了正确的用户和访问令牌”);
返回;
}
//显示有关路线的一些信息
currentRoute=response.body().getRoutes().get(0);
Log.d(标记“距离:+currentRoute.getDistance());
Toast.makeText(MainActivity.this,“路由为”+currentRoute.getDistance()+“米长”,Toast.LENGTH_SHORT).show();
//在地图上画出路线
提取路线(当前路线);
}
@凌驾
失败时公共无效(调用调用,可丢弃的t){
Log.e(标记“Error:+t.getMessage());
Toast.makeText(MainActivity.this,“错误:+t.getMessage(),Toast.LENGTH\u SHORT.show();
}
});
}
专用空位提取路线(方向路线){
//将线串坐标转换为LatLng[]
LineString LineString=LineString.fromPolyline(route.getGeometry(),Constants.OSRM\u PRECISION\u V5);
列表坐标=lineString.getCoordinates();
LatLng[]点=新的LatLng[coordinates.size()];
对于(int i=0;i
所以这里的某个地方是我的问题,我无法在网上找到关于Mapbox的很多信息,因为他们的新sdk与以前的版本有很大的不同,主要是因为MapView和MapboxMap没有
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
import com.mapbox.mapboxsdk.annotations.PolylineOptions;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.services.Constants;
import com.mapbox.services.android.geocoder.ui.GeocoderAutoCompleteView;
import com.mapbox.services.commons.ServicesException;
import com.mapbox.services.commons.geojson.LineString;
import com.mapbox.services.commons.models.Position;
import com.mapbox.services.directions.v5.DirectionsCriteria;
import com.mapbox.services.directions.v5.MapboxDirections;
import com.mapbox.services.directions.v5.models.DirectionsResponse;
import com.mapbox.services.directions.v5.models.DirectionsRoute;
import com.mapbox.services.geocoding.v5.GeocodingCriteria;
import com.mapbox.services.geocoding.v5.models.GeocodingFeature;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends Activity {
private final static String TAG = "MainActivity";
private MapView mapView;
private MapboxMap map;
private DirectionsRoute currentRoute;
private Position origin;
private Position destination;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Setup the MapView
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(MapboxMap mapboxMap) {
map = mapboxMap;
mapboxMap.setMyLocationEnabled(true);
// Set up autocomplete widget
GeocoderAutoCompleteView autocomplete = (GeocoderAutoCompleteView) findViewById(R.id.query);
autocomplete.setAccessToken("<your access token>");
autocomplete.setType(GeocodingCriteria.TYPE_POI);
autocomplete.setOnFeatureListener(new GeocoderAutoCompleteView.OnFeatureListener() {
@Override
public void OnFeatureClick(GeocodingFeature feature) {
if(map.getMyLocation() != null) {
// Set the origin as user location only if we can get their location
origin = Position.fromCoordinates(map.getMyLocation().getLongitude(), map.getMyLocation().getLatitude());
}else{
return;
}
destination = feature.asPosition();
// Add origin and destination to the map
map.addMarker(new MarkerOptions()
.position(new LatLng(origin.getLatitude(), origin.getLongitude())));
map.addMarker(new MarkerOptions()
.position(new LatLng(destination.getLatitude(), destination.getLongitude())));
// Get route from API
try {
getRoute(origin, destination);
} catch (ServicesException e) {
e.printStackTrace();
}
}
});
}
});
}
private void getRoute(Position origin, Position destination) throws ServicesException {
MapboxDirections client = new MapboxDirections.Builder()
.setOrigin(origin)
.setDestination(destination)
.setProfile(DirectionsCriteria.PROFILE_CYCLING)
.setAccessToken("<your access token>")
.build();
client.enqueueCall(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;
}
// Print some info about the route
currentRoute = response.body().getRoutes().get(0);
Log.d(TAG, "Distance: " + currentRoute.getDistance());
Toast.makeText(MainActivity.this, "Route is " + currentRoute.getDistance() + " meters long.", Toast.LENGTH_SHORT).show();
// Draw the route on the map
drawRoute(currentRoute);
}
@Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
Log.e(TAG, "Error: " + t.getMessage());
Toast.makeText(MainActivity.this, "Error: " + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void drawRoute(DirectionsRoute route) {
// Convert LineString coordinates into LatLng[]
LineString lineString = LineString.fromPolyline(route.getGeometry(), Constants.OSRM_PRECISION_V5);
List<Position> coordinates = lineString.getCoordinates();
LatLng[] points = new LatLng[coordinates.size()];
for (int i = 0; i < coordinates.size(); i++) {
points[i] = new LatLng(
coordinates.get(i).getLatitude(),
coordinates.get(i).getLongitude());
}
// Draw Points on MapView
map.addPolyline(new PolylineOptions()
.add(points)
.color(Color.parseColor("#009688"))
.width(5));
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@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();
}