Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 另一个活动中的Mapbox片段_Java_Android_Android Studio_Android Fragments_Mapbox Android - Fatal编程技术网

Java 另一个活动中的Mapbox片段

Java 另一个活动中的Mapbox片段,java,android,android-studio,android-fragments,mapbox-android,Java,Android,Android Studio,Android Fragments,Mapbox Android,我正在尝试创建一个应用程序,它可以在驾驶时跟踪用户的眼睛,还可以显示逐轮导航。将在与地图相同的屏幕上进行相机预览,类似于下图,其中相机预览位于左上方,地图位于下方 我有一个MapBox活动在一个单独的文件MapsActivity.java中工作。我想在activty test.java中的一个片段中运行Mapbox活动,该片段执行眼睛跟踪 我已经阅读了教程和在线资源,但无法找到如何使其适用于我的特定代码。抱歉,如果这是一个简单的问题,这是我的第一个应用程序 MapsActivity.java

我正在尝试创建一个应用程序,它可以在驾驶时跟踪用户的眼睛,还可以显示逐轮导航。将在与地图相同的屏幕上进行相机预览,类似于下图,其中相机预览位于左上方,地图位于下方

我有一个MapBox活动在一个单独的文件MapsActivity.java中工作。我想在activty test.java中的一个片段中运行Mapbox活动,该片段执行眼睛跟踪

我已经阅读了教程和在线资源,但无法找到如何使其适用于我的特定代码。抱歉,如果这是一个简单的问题,这是我的第一个应用程序

MapsActivity.java

package com.example.drivesafely;

import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

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

import com.mapbox.android.core.permissions.PermissionsListener;
import com.mapbox.android.core.permissions.PermissionsManager;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import com.mapbox.geojson.Feature;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.location.LocationComponent;
import com.mapbox.mapboxsdk.location.modes.CameraMode;
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.style.layers.SymbolLayer;
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncher;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncherOptions;
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconAllowOverlap;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconIgnorePlacement;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconImage;

// classes needed to initialize map
// classes needed to add the location component
// classes needed to add a marker
// classes to calculate a route
// classes needed to launch navigation UI


public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback, MapboxMap.OnMapClickListener, PermissionsListener {
    // 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;

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

    @Override
    public void onMapReady(@NonNull final MapboxMap mapboxMap) {
        this.mapboxMap = mapboxMap;
        mapboxMap.setStyle(getString(R.string.navigation_guidance_day), new Style.OnStyleLoaded() {
            @Override
            public void onStyleLoaded(@NonNull Style style) {
                enableLocationComponent(style);

                addDestinationIconSymbolLayer(style);

                mapboxMap.addOnMapClickListener(MapsActivity.this);
                button = findViewById(R.id.startButton);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        boolean simulateRoute = true;
                        NavigationLauncherOptions options = NavigationLauncherOptions.builder()
                                .directionsRoute(currentRoute)
                                .shouldSimulateRoute(simulateRoute)
                                .build();
// Call this method with Context from within an Activity
                        NavigationLauncher.startNavigation(MapsActivity.this, options);
                    }
                });
            }
        });
    }

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

    @SuppressWarnings( {"MissingPermission"})
    @Override
    public boolean onMapClick(@NonNull LatLng point) {

        Point destinationPoint = Point.fromLngLat(point.getLongitude(), point.getLatitude());
        Point originPoint = Point.fromLngLat(locationComponent.getLastKnownLocation().getLongitude(),
                locationComponent.getLastKnownLocation().getLatitude());

        GeoJsonSource source = mapboxMap.getStyle().getSourceAs("destination-source-id");
        if (source != null) {
            source.setGeoJson(Feature.fromGeometry(destinationPoint));
        }

        getRoute(originPoint, destinationPoint);
        button.setEnabled(true);
        button.setBackgroundResource(R.color.mapboxBlue);
        return true;
    }

    private void getRoute(Point origin, Point destination) {
        NavigationRoute.builder(this)
                .accessToken(Mapbox.getAccessToken())
                .origin(origin)
                .destination(destination)
                .build()
                .getRoute(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;
                        } 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);
                    }

                    @Override
                    public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
                        Log.e(TAG, "Error: " + throwable.getMessage());
                    }
                });
    }

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

    @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, R.string.user_location_permission_explanation, Toast.LENGTH_LONG).show();
    }

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

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

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

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

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

    @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();
    }
}
package com.example.drivesafe;
导入android.graphics.BitmapFactory;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.view;
导入android.widget.Button;
导入android.widget.Toast;
导入androidx.annotation.NonNull;
导入androidx.appcompat.app.appcompat活动;
导入com.mapbox.android.core.permissions.PermissionsListener;
导入com.mapbox.android.core.permissions.PermissionsManager;
导入com.mapbox.api.directions.v5.models.DirectionsResponse;
导入com.mapbox.api.directions.v5.models.DirectionsRoute;
导入com.mapbox.geojson.Feature;
导入com.mapbox.geojson.Point;
导入com.mapbox.mapboxsdk.mapbox;
导入com.mapbox.mapboxsdk.geometry.LatLng;
导入com.mapbox.mapboxsdk.location.LocationComponent;
导入com.mapbox.mapboxsdk.location.modes.CameraMode;
导入com.mapbox.mapboxsdk.maps.MapView;
导入com.mapbox.mapboxsdk.maps.MapboxMap;
导入com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
导入com.mapbox.mapboxsdk.maps.Style;
导入com.mapbox.mapboxsdk.style.layers.symbolayer;
导入com.mapbox.mapboxsdk.style.sources.GeoJsonSource;
导入com.mapbox.services.android.navigation.ui.v5.NavigationLauncher;
导入com.mapbox.services.android.navigation.ui.v5.NavigationLauncherOptions;
导入com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
导入com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
导入java.util.List;
2.电话;;
2.回拨;
2.回应;;
导入静态com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconAllowOverlap;
导入静态com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconIgnorePlacement;
导入静态com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconImage;
//初始化映射所需的类
//添加位置组件所需的类
//类需要添加标记
//类来计算路线
//启动导航UI所需的类
公共类MapsActivity扩展了AppCompativeActivity在MapReadyCallback、MapboxMap.OnMapClickListener、PermissionsListener上的实现{
//用于添加位置层的变量
私有地图视图;
私有MapboxMap MapboxMap;
//用于添加位置层的变量
私人许可证管理人许可证管理人;
专用位置组件位置组件;
//用于计算和绘制路线的变量
专用方向路由当前路由;
私有静态最终字符串TAG=“DirectionsActivity”;
专用导航地图路线导航地图路线;
//初始化导航所需的变量
私人按钮;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
getInstance(这个,getString(R.string.access_令牌));
setContentView(R.layout.activity_映射);
mapView=findViewById(R.id.mapView);
onCreate(savedInstanceState);
getMapAsync(这个);
}
@凌驾
mapready上的公共无效(@NonNull final MapboxMap MapboxMap){
this.mapboxMap=mapboxMap;
mapboxMap.setStyle(getString(R.string.navigation\u Guidence\u day),新样式.OnStyleLoaded(){
@凌驾
已加载的公共void onstyled(@NonNull Style){
enableLocationComponent(样式);
AddDestinationSymbolLayer(样式);
addOnMapClickListener(MapsActivity.this);
按钮=findViewById(R.id.startButton);
setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
布尔模拟器输出=真;
NavigationLauncherOptions=NavigationLauncherOptions.builder()
.方向路线(当前路线)
.shouldSimulatorOute(SimulatorOute)
.build();
//在活动中使用上下文调用此方法
NavigationLauncher.startNavigation(MapsActivity.this,选项);
}
});
}
});
}
私有void addDestinationSymbolLayer(@NonNull Style loadedMapStyle){
loadedMapStyle.addImage(“目标图标id”,
BitmapFactory.decodeResource(this.getResources(),R.drawable.mapbox\u marker\u icon\u default));
GeoJsonSource GeoJsonSource=新的GeoJsonSource(“目标源id”);
loadedMapStyle.addSource(geoJsonSource);
SymbolLayer destinationSymbolLayer=新的SymbolLayer(“目标符号层id”,“目标源id”);
destinationSymbolLayer.withProperties(
图标图像(“目标图标id”),
iconAllowOverlap(真),
iconIgnorePlacement(真)
);
loadedMapStyle.addLayer(destinationSymbolLayer);
}
@SuppressWarnings({“MissingPermission”})
@凌驾
公共布尔onmaplick(@NonNull LatLng point){
Point destinationPoint=Point.fromLngLat(Point.getLongitude(),Point.getLatitude());
Point originPoint=Point.fromLngLat(locationComponent.getLastKnownLocation().getLongitude(),
<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.mapbox.mapboxsdk.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        mapbox:mapbox_cameraTargetLat="38.9098"
        mapbox:mapbox_cameraTargetLng="-77.0295"
        mapbox:mapbox_cameraZoom="12" />

    <Button
        android:id="@+id/startButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:background="@color/mapboxGrayLight"
        android:enabled="false"
        android:text="Start navigation"
        android:textColor="@color/mapboxWhite"
        mapbox:layout_constraintStart_toStartOf="parent"
        mapbox:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
 <?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:id="@+id/background"
    android:background="#fcfcfc"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:keepScreenOn="true"
    tools:context=".test">


    <com.mapbox.mapboxsdk.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="400dp"
        android:layout_height="300dp"
        android:background="#f567"
        mapbox:layout_constraintTop_toBottomOf="@+id/preview"
        mapbox:mapbox_cameraTargetLat="38.9098"
        mapbox:mapbox_cameraTargetLng="-77.0295"
        mapbox:mapbox_cameraZoom="12" />

    <Button
        android:id="@+id/startButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="260dp"
        android:layout_marginEnd="16dp"
        android:background="@color/mapboxGrayLight"
        android:enabled="false"
        android:text="Start navigation"
        android:textColor="@color/mapboxWhite"
        tools:layout_constraintStart_toStartOf="parent"
        tools:layout_constraintTop_toTopOf="parent" />


    <RelativeLayout
        android:id="@+id/relativeLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="bottom">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="false"
            android:layout_alignParentTop="false"
            android:layout_alignParentBottom="true"
            android:layout_weight="0"
            android:background="#19b5fe"
            android:gravity="center|center_horizontal"
            android:weightSum="2">


            <Button
                android:id="@+id/button"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="35dp"
                android:layout_marginRight="5dp"
                android:background="#E0E0E0"
                android:text="@string/end" />

            <ToggleButton
                android:id="@+id/toggleButton"
                android:layout_width="200dp"
                android:layout_height="40dp"
                android:background="@drawable/rounded_corners"
                android:checked="false"
                android:text="New ToggleButton"
                android:textColor="#ffff"
                android:textOff="@string/turn_preview_off"
                android:textSize="12dp" />

            <TextView
                android:id="@+id/textView3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:text="Status: "
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/textView4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceSmall" />

        </TableRow>


    </RelativeLayout>


    <com.example.drivesafely.CameraSourcePreview
        android:id="@+id/preview"
        android:layout_width="200dp"
        android:layout_height="300dp"
        android:layout_gravity="center_horizontal">

        <com.example.drivesafely.GraphicOverlay
            android:id="@+id/faceOverlay"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </com.example.drivesafely.CameraSourcePreview>


</androidx.constraintlayout.widget.ConstraintLayout>