gpt4 book ai didi

java - 如何在使用mapbox搜索时获取出发点和目的地点

转载 作者:行者123 更新时间:2023-12-01 16:19:47 25 4
gpt4 key购买 nike

  1. 公共(public)类 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)无效onClick(查看 View ){ 意图意图 = new PlaceAutocomplete.IntentBuilder() .accessToken(Mapbox.getAccessToken() != null ? Mapbox.getAccessToken() : getString(R.string.access_token)) .placeOptions(PlaceOptions.builder() .backgroundColor(Color.parseColor("#EEEEEE")) .限制(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); } 导航MapRoute.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);
    } }

最佳答案

您能详细说明一下您希望实现什么目标吗?

出发地和目的地只是 map 上的两个位置。您可以通过多种方式检索这些内容。您可以通过单击 map 来选择它们,将地址输入到地理编码器中,地理编码器会将地址转换为地理位置。因此您可以利用Mapbox Places Plugin.

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

您可以使用 Mapbox locationComponent 并检索当前设备位置,您可以将其用作原点。请参阅此示例:https://docs.mapbox.com/android/maps/examples/show-a-users-location/

在下面的代码片段中,您可以使用位置 loc 作为源:

      private void enableLocationComponent(@NonNull Style loadedMapStyle) {

if (PermissionsManager.areLocationPermissionsGranted(this)) {

LocationComponent locationComponent = map.getLocationComponent();
Location loc = locationComponent.getLastKnownLocation();

关于java - 如何在使用mapbox搜索时获取出发点和目的地点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62306141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com