如何在Mapbox中添加位置按钮,例如Google Maps的setMyLocationButtonEnabled?

问题描述 投票:0回答:1

我对编程非常陌生,我需要制作一个Android应用程序。我刚刚找到了一个不错的API,而不是Google Maps。它叫做Mapbox。因此,我一直在关注他们的文档和示例代码,但是,我认为他们的一些示例已经过时,并且已经弃用了一些类。因此,我已经能够初始化地图并将运行时权限放入程序中。

现在,我不知道该如何放置“位置按钮”,就像Google Maps API的用法一样。在使用Google Maps API之前,我已经对应用进行了编程,并且使用了mMap.getUISettings().setMyLocationEnabled(true)mMap.setMyLocationEnabled(true)显示位置按钮。当我浏览Internet时,似乎找不到在Mapbox中带来这种UI的代码。我发现了一些代码片段,但是正如我所说的那样,其中一些已经过时了。另外,它们有自己的.xml文件,而我没有这些文件,因此当我尝试复制其代码时,总是会遇到错误。

因此,如果您对如何编辑我的文件有任何想法,或者我需要在项目中添加某些文件,请帮助我。

我将在下面附加我的文件。谢谢!

您可以在我的GitHub存储库中找到文件:https://github.com/CyrilOlanolan/Tara-JMapbox

我的MainActivity.java:

package com.garate.tara_j;

//Mapbox imports
import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;

import com.mapbox.android.core.location.LocationEngine;
import com.mapbox.android.core.location.LocationEngineProvider;
import com.mapbox.android.core.permissions.PermissionsListener;
import com.mapbox.android.core.permissions.PermissionsManager;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.location.LocationComponent;
import com.mapbox.mapboxsdk.location.LocationComponentActivationOptions;
import com.mapbox.mapboxsdk.location.LocationComponentOptions;
import com.mapbox.mapboxsdk.location.OnCameraTrackingChangedListener;
import com.mapbox.mapboxsdk.location.OnLocationClickListener;
import com.mapbox.mapboxsdk.location.modes.CameraMode;
import com.mapbox.mapboxsdk.location.modes.RenderMode;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.maps.Style;
import com.mapbox.mapboxsdk.maps.UiSettings;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import java.util.List;

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, PermissionsListener {

    private MapView mapView;
    private MapboxMap mapboxMap;
    private PermissionsManager permissionsManager;
    private boolean isInTrackingMode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Mapbox.getInstance(getApplicationContext(), getString(R.string.mapbox_access_token));
        setContentView(R.layout.activity_main);
        mapView = findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);
        mapView.getMapAsync(this);
    }

    @Override
    public void onMapReady(@NonNull final MapboxMap mapboxMap) {
        MainActivity.this.mapboxMap = mapboxMap;
        //ADD Aster's Map Style
        //mapboxMap.setStyle(new Style.Builder().fromUri("mapbox://styles/cyrilolanolan/ck5gqdepj0u991io1g3743owe")
        mapboxMap.setStyle((Style.MAPBOX_STREETS), new Style.OnStyleLoaded() {
            @Override
            public void onStyleLoaded(@NonNull Style style) {

                // Map is set up and the style has loaded. Now you can add data or make other map adjustments.
                UiSettings uiSettings = mapboxMap.getUiSettings();
                uiSettings.setTiltGesturesEnabled(false);
                enableLocationComponent(style);

            }
        });
    }

    @SuppressWarnings( {"MissingPermission"})
    private void enableLocationComponent(@NonNull Style loadedMapStyle) {
        if (PermissionsManager.areLocationPermissionsGranted(this)) {

            // Permission sensitive logic called here, such as activating the Maps SDK's LocationComponent to show the device's location
            // Create and customize the LocationComponent's options
            LocationComponentOptions customLocationComponentOptions = LocationComponentOptions.builder(this)
                    .elevation(5)
                    .accuracyAlpha(.6f)
                    .accuracyColor(Color.BLUE)
                    .build();

            LocationComponentActivationOptions locationComponentActivationOptions =
                    LocationComponentActivationOptions.builder(this, loadedMapStyle)
                            .locationComponentOptions(customLocationComponentOptions)
                            .build();

            // Get an instance of the component
            final LocationComponent locationComponent = mapboxMap.getLocationComponent();

            // Activate with options
            locationComponent.activateLocationComponent(locationComponentActivationOptions);

            // Enable to make component visible
            locationComponent.setLocationComponentEnabled(true);

            // Set the component's render mode
            locationComponent.setRenderMode(RenderMode.COMPASS);
        } else {
            permissionsManager = new PermissionsManager(this);
            permissionsManager.requestLocationPermissions(this);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onExplanationNeeded(List<String> permissionsToExplain) {
        Toast.makeText(this, "Tara-J needs permission to function", Toast.LENGTH_SHORT);
    }

    @Override
    public void onPermissionResult(boolean granted) {
        if (granted) {
            mapboxMap.getStyle(new Style.OnStyleLoaded() {
                @Override
                public void onStyleLoaded(@NonNull Style style) {
                    enableLocationComponent(style);
                }
            });
        } else {
            Toast.makeText(this, "Permissions are required. Please restart Tara-J.", Toast.LENGTH_SHORT);
            finish();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        mapView.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        mapView.onStop();
    }

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

我的activity_main.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:mapbox="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.mapbox.mapboxsdk.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        mapbox:mapbox_cameraTargetLat="7.0707"
        mapbox:mapbox_cameraTargetLng="125.6087"
        mapbox:mapbox_cameraZoom="13" />

</androidx.constraintlayout.widget.ConstraintLayout>
java android google-maps user-interface mapbox
1个回答
0
投票

您的LocationComponent设置代码看起来不错! Mapbox没有提供内置的UI按钮。您需要将其添加到XML布局中。在按钮的onClick()中,获取LocationComponent的最后一个已知位置,并将摄像机动画化为最后一个已知位置的坐标:

findViewById(R.id.device_button).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

      Location lastKnownLocation = mapboxMap.getLocationComponent().getLastKnownLocation();

      if (lastKnownLocation != null) {

        CameraPosition position = new CameraPosition.Builder()
          .target(new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude())) // Sets the new camera position
          .zoom(16)
          .bearing(0)
          .tilt(0)
          .build(); // Creates a CameraPosition from the builder

        mapboxMap.animateCamera(CameraUpdateFactory
          .newCameraPosition(position), 7000);
      }

    }
  });

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.