【问题标题】:How to get origin and destination points while searching with mapbox使用 mapbox 搜索时如何获取起点和终点
【发布时间】:2020-09-30 00:28:47
【问题描述】:
  1. 公共类 MainActivity 扩展 AppCompatActivity 实现 OnMapReadyCallback, PermissionsListener {

    private static final int REQUEST_CODE_AUTOCOMPLETE = 1;
    // variables for adding location layer
    private MapView mapView;
    private MapboxMap mapboxMap;
    
    // variables for adding location layer
    private PermissionsManager permissionsManager;
    private LocationComponent locationComponent;
    
    // variables for calculating and drawing a route
    private DirectionsRoute currentRoute;
    private static final String TAG = "DirectionsActivity";
    private NavigationMapRoute navigationMapRoute;
    
    // variables needed to initialize navigation
    private Button button;
    private CarmenFeature home;
    private CarmenFeature work;
    private String geojsonSourceLayerId = "geojsonSourceLayerId";
    private String symbolIconId = "symbolIconId";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        // Mapbox access token is configured here. This needs to be called either in your application
        // object or in the same activity which contains the mapview.
        Mapbox.getInstance(this, getString(R.string.access_token));
    
        // This contains the MapView in XML and needs to be called after the access token is configured.
        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(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
            @Override
            public void onStyleLoaded(@NonNull Style style) {
    
                enableLocationComponent(style);
                addDestinationIconSymbolLayer(style);
    
                initSearchFab();
    
                addUserLocations();
    
                // Add the symbol layer icon to map for future use
                style.addImage(symbolIconId, BitmapFactory.decodeResource(
                        MainActivity.this.getResources(), R.drawable.mapbox_marker_icon_default));
    
                // Create an empty GeoJSON source using the empty feature collection
                setUpSource(style);
    
                // Set up a new symbol layer for displaying the searched location's feature coordinates
                setupLayer(style);
            }
        });
    }
    
    //search
    private void initSearchFab() {
        findViewById(R.id.fab_location_search).setOnClickListener(new
    

    View.OnClickListener() { @覆盖 public void onClick(查看视图){ 意图意图 = 新 PlaceAutocomplete.IntentBuilder() .accessToken(Mapbox.getAccessToken() != null ? Mapbox.getAccessToken() : getString(R.string.access_token)) .placeOptions(PlaceOptions.builder() .backgroundColor(Color.parseColor("#EEEEEE")) .limit(10) .addInjectedFeature(主页) .addInjectedFeature(工作) .build(PlaceOptions.MODE_CARDS)) .build(MainActivity.this); startActivityForResult(意图,REQUEST_CODE_AUTOCOMPLETE); } }); }

    //home and work
    private void addUserLocations() {
        home = CarmenFeature.builder().text("Mapbox SF Office")
                .geometry(Point.fromLngLat(-122.3964485, 37.7912561))
                .placeName("50 Beale St, San Francisco, CA")
                .id("mapbox-sf")
                .properties(new JsonObject())
                .build();
    
        work = CarmenFeature.builder().text("Mapbox DC Office")
                .placeName("740 15th Street NW, Washington DC")
                .geometry(Point.fromLngLat(-77.0338348, 38.899750))
                .id("mapbox-dc")
                .properties(new JsonObject())
                .build();
    }
    
    private void setUpSource(@NonNull Style loadedMapStyle) {
        loadedMapStyle.addSource(new GeoJsonSource(geojsonSourceLayerId));
    }
    
    private void setupLayer(@NonNull Style loadedMapStyle) {
        loadedMapStyle.addLayer(new SymbolLayer("SYMBOL_LAYER_ID", geojsonSourceLayerId).withProperties(
                iconImage(symbolIconId),
                iconOffset(new Float[] {0f, -8f})
        ));
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_AUTOCOMPLETE) {
    
            // Retrieve selected location's CarmenFeature
            CarmenFeature selectedCarmenFeature = PlaceAutocomplete.getPlace(data);
    
            // Create a new FeatureCollection and add a new Feature to it using selectedCarmenFeature above.
            // Then retrieve and update the source designated for showing a selected location's symbol layer icon
    
            if (mapboxMap != null) {
                Style style = mapboxMap.getStyle();
                if (style != null) {
                    GeoJsonSource source = style.getSourceAs(geojsonSourceLayerId);
                    if (source != null) {
                        source.setGeoJson(FeatureCollection.fromFeatures(
                                new Feature[] {Feature.fromJson(selectedCarmenFeature.toJson())}));
                    }
    
                    // Move map camera to the selected location
                    mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(
                            new CameraPosition.Builder()
                                    .target(new LatLng(((Point) selectedCarmenFeature.geometry()).latitude(),
                                            ((Point) selectedCarmenFeature.geometry()).longitude()))
                                    .zoom(14)
                                    .build()), 4000);
                }
            }
        }
    }
    
    
    //getRoute
    private void getRoute(Point origin, Point destination)
    {
        NavigationRoute.builder(this)
                .accessToken(Mapbox.getAccessToken())
                .origin(origin)
                .destination(destination)
                .build()
                .getRoute(new Callback<DirectionsResponse>()
                {
                    //onResponse
                    @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);
    
                        // Draw the route on the map
                        if (navigationMapRoute != null)
                        {
                            navigationMapRoute.removeRoute();
                        }
                        else
                        {
                            navigationMapRoute = new NavigationMapRoute(null, mapView, mapboxMap,
    

    R.style.NavigationMapRoute); } navigationMapRoute.addRoute(currentRoute); }//onResponse结束

                    //onFailure
                    @Override
                    public void onFailure(Call<DirectionsResponse> call, Throwable throwable)
                    {
                        Log.e(TAG, "Error: " + throwable.getMessage());
                    }//end of onFailure
                });
    }//end of getRoute
    
    //addDestinationIconSymbolLayer
    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);
    }//end of addDestinationIconSymbolLayer
    
    //enableLocationComponent
    @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);
        }
    }//end of enableLocationComponent
    
    //onRequestPermissionsResult
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }//end of onRequestPermissionsResult
    
    //onExplanationNeeded
    @Override
    public void onExplanationNeeded(List<String> permissionsToExplain)
    {
        Toast.makeText(this, R.string.user_location_permission_explanation,
    

    Toast.LENGTH_LONG).show(); }//onExplanationNeeded结束

    //onPermissionResult
    @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(); 结束(); } }//onPermissionResult 结束

    // Add the mapView lifecycle to the activity's lifecycle methods
    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }
    
    @Override
    protected void onStart() {
        super.onStart();
        mapView.onStart();
    }
    
    @Override
    protected void onStop() {
        super.onStop();
        mapView.onStop();
    }
    
    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }
    
    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    } }
    

【问题讨论】:

    标签: java mapbox


    【解决方案1】:

    您能否详细说明您想要实现的目标?

    起点和终点只是地图上的 2 个位置。您可以通过多种方式检索这些。您可以通过单击地图来选择它们,将地址输入地理编码器,该地址会将地址转换为地理位置。因此您可以使用Mapbox Places Plugin.

    此示例允许您通过单击来选择地图的要素。您可以对其进行调整并返回地理位置,然后您可以将其用作您的目的地:https://docs.mapbox.com/android/maps/examples/query-a-map-feature/

    您可以使用 Mapbox locationComponent 并检索当前设备位置,您可以将其用作您的原点。 看这个例子:https://docs.mapbox.com/android/maps/examples/show-a-users-location/

    在下面的 sn-p 中,您可以使用位置 loc 作为原点:

          private void enableLocationComponent(@NonNull Style loadedMapStyle) {
    
            if (PermissionsManager.areLocationPermissionsGranted(this)) {
    
               LocationComponent locationComponent = map.getLocationComponent();
               Location loc = locationComponent.getLastKnownLocation();

    【讨论】:

    • 嗨,我已经设法搜索了我的目的地,但我不知道如何使它等于我的目的地点,所以我可以创建一条从用户最后知道的位置到有已被搜索。
    猜你喜欢
    • 1970-01-01
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多