当前位置: 首页 > 知识库问答 >
问题:

如何在mapbox搜索时获得起点和终点

慕高阳
2023-03-14

>

  • 公共类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(){@override public void onClick(View View){Intent Intent=new PlaceAutoComplete.IntentBuilder().AccessToken(Mapbox.GetAccessToken()!=null?Mapbox.GetAccessToken():getString(R.String.Access_Token).PlaceOptions.Builder().BackgroundColor(Color.ParseColor(“#Eeeeeee”).Limit(10).AddinjectedFeature(home).

    //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();finish();}}//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);
    } }
    
  • 共有1个答案

    陶锋
    2023-03-14

    你能详细说明你想要达到的目标吗?

    出发地和目的地只是地图上的两个位置。您可以通过多种方式检索这些。您可以通过点击地图选择它们,在地理编码器中输入地址,然后将地址转换为地理位置。因此,您可以使用Mapbox Places插件。

    此示例允许您通过单击地图来选择地图的特征。您可以调整它并返回地理位置,然后您可以将其用作您的目的地: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();
     类似资料:
    • 在Elasticsearch中,您可以执行返回点击的搜索,同时在一个响应中返回与点击分开的聚合结果。这是非常强大和有效的,因为您可以运行查询和多个聚合,并一次获得两个(或其中一个)操作的结果,避免使用简洁和简化的API进行网络往返。 我想执行搜索,当我对聚合有查询时返回点击。但我不确定如何才能做到以上几点? 我正在使用以下查询:

    • 我正在使用Mongoostic,它工作得很好,但我面临的问题是,如何从方法并将其传递给方法? 例如: 你们是怎么解决这个问题的?这是一个非常基本的搜索,用户搜索时,它会将用户重定向到另一个页面,在那里它要么显示已找到的结果,要么未找到。

    • 我的要求是,如果用户使用Lucene搜索搜索“页码”,搜索结果应注意将结果中的页码与列表顶部的精确页码匹配。 现在在我的例子中,我尝试使用SortField进行排序- 假设我搜索了术语'5',然后在搜索结果中,而不是在列表的顶部显示精确页码匹配,它显示搜索的术语'5',它存在于每个页面上。 有人能建议如何在列表顶部的Lucene搜索结果中包含页码吗。 我的代码-

    • 所以我试图在搜索一个名字后,点击该表,然后在其他表中编辑它,问题是我没有得到正确的id,而是只得到了前面的id。 JTable 行动中的搜索 Id错误 编辑代码 搜索代码

    • 当跨多个索引进行搜索时,elasticsearch的“多重匹配”查询将返回搜索结果中的索引名称。 响应包含字段,该字段告诉结果来自的索引 spring-data-elasticsearch中用于的类是和具有字段、、用于获取与elasticsearch查询相似的数据。但它不包含用于存储字段信息的相关字段。 还支持吗?我需要根据哪个客户端应用程序将生成一些URL发送搜索命中类型(name)。 这是我使

    • 问题内容: 我已经多次重温了这个问题,但我从未真正找到合适的答案。 是否可以执行MySQL搜索,以按相关性返回ACTUAL准确排序的结果? 我试图创建一个ajax搜索表单,当用户在输入字段中键入内容时提出建议,并且仅使用纯MySQL查询还没有找到合适的解决方案。我知道有可用的搜索服务器,例如ElasticSearch,我想知道如何仅使用原始MySQL查询来实现。 我有一张学校科目表。少于1200行