当前位置: 首页 > 面试题库 >

Mapbox Android:如何获取从当前位置到您选择的目的地的路线?

周锐
2023-03-14
问题内容

好的,所以我对Mapbox还是很陌生,在此之前我曾经使用过GMaps,但是我发现Mapbox能够满足我的需要,问题是我碰壁了。

我使用了他们网站上可用示例的组合

https://www.mapbox.com/android-
sdk/examples/geocoding
和 https://www.mapbox.com/android-
sdk/examples/directions

我试图让用户搜索目的地,然后将其转换为坐标,以用于在地图上进行绘制。然后,我想画一条从他们当前位置到目的地的路线,这就是我的问题所在。

 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();
}

因此,这是我的问题,我无法在网上找到太多有关Mapbox的信息,因为它们的新SDK与以前的版本有很大不同,主要是因为MapView和MapboxMap现在是分开的(这仍然令我感到困惑)。

任何帮助将不胜感激:D

:Edit:我主要是在设置目的地方面苦苦挣扎,因此,我当前的很多变量都混在一起了。如果您需要解释,我会很高兴。


问题答案:

您的代码中存在一些错误,最大的错误是您仍在使用MapView时仍在获取位置信息MapboxMap。这是一些粗糙的代码,可以满足您的要求。它不会像您应该检查的那样检查用户权限,但会向您显示如何执行Mapbox的操作。

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();
}

希望这可以帮助!



 类似资料:
  • 问题内容: 我在这个项目中使用该类。在我的地图上,您可以看到许多标记。我有许多已知的位置,但是在我的代码中,例如,我仅显示两个位置。 我不明白如何使用方向API和JSON。如何显示从当前位置(更改)到已知位置(恒定)的路线,距离和行进时间? 问题答案: 看一下本教程: 使用Google Map Android API V2中的Google Directions在两个位置之间绘制行车路线 它显示了如

  • 我试图实现当前位置地图应用程序,我正在加载地图碎片,但它需要纬度和经度值来定位地址...如何实现当前位置地图功能...提前感谢.. 这是我的地图片段。

  • 本文向大家介绍JS获取当前地理位置的方法,包括了JS获取当前地理位置的方法的使用技巧和注意事项,需要的朋友参考一下 本文实例为大家分享了JS获取当前地理位置方法的具体代码,供大家参考,具体内容如下 1.手机定位 前提要引入百度API: <script src="http://api.map.baidu.com/api?v=1.4" type="text/javascript"></script>

  • ap.getLocation(OPTION, CALLBACK) 获取当前的地理位置信息。 OPTION 参数说明 名称 类型 必填 描述 cacheTimeout Number 否 钱包经纬度定位缓存过期时间,单位秒。默认 30s。使用缓存会加快定位速度,缓存过期会重新定位 type Number 否 支持 0:详细逆地理编码,带周边信;1:逆地理编码到城市;2:仅获取经纬度、速度和精度。默认为

  • 我有困难在提交时在烧瓶应用程序的WTForm页面中获取当前选择的项目。提交时,form.tableselector.data值始终等于1,无论选择了SseltField中的哪个项目(并且所有选项都具有表单(1,'table_name')1-10中的唯一表id,其中1是整数。 以下是当前代码: 意见。派克 form.py 桌面视图。html 我注意到,在调试表单时,wtf元对象csrf属性等于Tru

  • 问题内容: 我正在编写一个Eclipse插件,它将在Java项目的上下文菜单中显示一个菜单项。我已将plugin.xml编写如下: 因此,我现在尝试编写扩展的类,以便可以创建动态菜单,并且该菜单的内容将基于Java项目根目录中存在的一组文件。但是我一直试图从方法中获取到根目录的路径。 基于plugin.xml文件,我可以确保仅在选择了单个Java项目的情况下才调用该方法,因此,我要做的就是获取当前