Java 我试图导航优化路线,但在Logcat中出错

Java 我试图导航优化路线,但在Logcat中出错,java,android,navigation,mapbox,Java,Android,Navigation,Mapbox,“使用默认里程碑要求路线方向包含路线选项对象” 公共类MainActivity扩展了AppCompativeActivity在MapReadyCallback、PermissionsListener、MapboxMap.OnMapClickListener、MapboxMap.OnMapLongClickListener上实现{ 私人许可证管理人许可证管理人; 私有MapboxMap MapboxMap; 私有地图视图; 位置组件位置组件; 双拉特,朗格; 浮动操作按钮浮动操作按钮,浮动操作按钮

“使用默认里程碑要求路线方向包含路线选项对象”

公共类MainActivity扩展了AppCompativeActivity在MapReadyCallback、PermissionsListener、MapboxMap.OnMapClickListener、MapboxMap.OnMapLongClickListener上实现{
私人许可证管理人许可证管理人;
私有MapboxMap MapboxMap;
私有地图视图;
位置组件位置组件;
双拉特,朗格;
浮动操作按钮浮动操作按钮,浮动操作按钮激活;
警报对话框警报对话框;
公共MapboxOptimizedClient;
公共导向路线;
私人点源;
专用导航地图路线导航地图路线;
私人指令视图指令视图;
private List stops=new ArrayList();
私有静态最终字符串ICON\u GEOJSON\u SOURCE\u ID=“ICON SOURCE ID”;
私有静态最终字符串FIRST=“FIRST”;
私有静态最终字符串ANY=“ANY”;
私有静态最终字符串TEAL_COLOR=“#23D2BE”;
专用静态最终浮动多段线_宽度=5;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
getInstance(这个,getString(R.string.access_令牌));
已配置令牌。 setContentView(R.layout.activity_main)

mapView=findviewbyd(R.id.mapView);
onCreate(savedInstanceState);
getMapAsync(这个);
floatingActionButton=findViewById(R.id.floatingActionButtonforsaveloc);
floatingActionButton.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
opendialoyge();
}
});
}
@凌驾
mapready上的公共无效(@NonNull final MapboxMap MapboxMap){
MainActivity.this.mapboxMap=mapboxMap;
mapboxMap.setStyle(新样式.Builder().fromUri(“mapbox://styles/mapbox/satellite-streets-v11"),
新样式。OnStyleLoaded(){
@凌驾
已加载的公共void onstyled(@NonNull Style){
enableLocationComponent(样式);
AddFirstStopToStopList();
initMarkerIconSymbolLayer(Objects.requirennull(style));
InitTelinelayer(样式);
Toast.makeText(MainActivity.this,R.string.click_指令,Toast.LENGTH_SHORT.show();
mapboxMap.addOnMapClickListener(MainActivity.this);
mapboxMap.addOnMapLongClickListener(MainActivity.this);
floatingActionButtonnavigate=findViewById(R.id.floatingActionButtonnavigate);
floatingActionButtonnavigate.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
布尔模拟器输出=真;
NavigationLauncherOptions=NavigationLauncherOptions.builder()
.方向路线(优化)
.shouldSimulatorOute(SimulatorOute)
.build();
NavigationLauncher.startNavigation(MainActivity.this,选项);
}
});
}
});
}
私有void addFirstStopToStopList(){
原点=Point.fromLngLat(locationComponent.getLastKnownLocation().Get经度(),locationComponent.getLastKnownLocation().getLatitude());
停止。添加(原点);
}
私有void initMarkerIconSymbolLayer(@NonNull Style-loadedMapStyle){
loadedMapStyle.addImage(“图标图像”,BitmapFactory.decodeResource(
this.getResources(),R.drawable.mapbox_marker_icon_default));
loadedMapStyle.addSource(新的GeoJsonSource(图标\u GEOJSON\u SOURCE\u ID,
Feature.fromGeometry(Point.fromLngLat(origin.longitude(),origin.latitude());
loadedMapStyle.addLayer(新的符号层(“图标层id”,图标\u GEOJSON\u源\u id)。withProperties(
图标图像(“图标图像”),
iconSize(1f),
iconAllowOverlap(真),
iconIgnorePlacement(正确),
iconOffset(新浮点[]{0f,-4f})
));
}
私有void InitTelineLayer(@NonNull Style loadedMapStyle){
loadedMapStyle.addSource(新的GeoJsonSource(“优化路由源id”);
loadedMapStyle.AddLayerBlow(新图层(“优化布线图层id”、“优化布线源id”)
.带物业(
lineColor(Color.parseColor(TEAL_Color)),
线宽(多段线宽度)
),“图标层id”);
}
@SuppressWarnings({“MissingPermission”})
私有void enableLocationComponent(@NonNull Style loadedMapStyle){
if(许可证管理人areLocationPermissionsGranted(本)){
locationComponent=mapboxMap.getLocationComponent();
locationComponent.activateLocationComponent(
LocationComponentActivationOptions.builder(这是loadedMapStyle.build());
locationComponent.setLocationComponentEnabled(true);
locationComponent.setCameraMode(CameraMode.TRACKING);
locationComponent.setRenderMode(RenderMode.COMPASS);
}否则{
permissionsManager=新的permissionsManager(此);
permissionsManager.requestLocationPermissions(此);
}
}
@凌驾
public void onRequestPermissionsResult(int-requestCode,@NonNull-String[]permissions,@NonNull-int[]grantResults){
permissionsManager.onRequestPermissionsResult(请求代码、权限、grantResults);
}
@凌驾
public void OneExplanationRequired(列出许可证解释){
Toast.makeText(this,R.string.user_位置_权限_解释,Toast.LENGTH_LONG).show();
}
@凌驾
public void onPermissionResult(已授予布尔值){
如果(授予){
mapboxMap.getStyle(新样式.OnStyleLoaded(){
@凌驾
已加载公共void onStyleLoaded(@NonNull样式)
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, PermissionsListener , MapboxMap.OnMapClickListener , MapboxMap.OnMapLongClickListener{

private PermissionsManager permissionsManager;
private MapboxMap mapboxMap;
private MapView mapView;
LocationComponent locationComponent;
Double lattt, langgg;
FloatingActionButton floatingActionButton , floatingActionButtonnavigate;
AlertDialog alertDialog;

public MapboxOptimization optimizedClient;
public DirectionsRoute optimizedRoute;
private Point origin;
private NavigationMapRoute navigationMapRoute;
private InstructionView instructionView;


private List<Point> stops = new ArrayList<>();
private static final String ICON_GEOJSON_SOURCE_ID = "icon-source-id";
private static final String FIRST = "first";
private static final String ANY = "any";
private static final String TEAL_COLOR = "#23D2BE";
private static final float POLYLINE_WIDTH = 5;

@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    Mapbox.getInstance(this, getString(R.string.access_token));
    mapView = findViewById(R.id.mapView);
    mapView.onCreate(savedInstanceState);
    mapView.getMapAsync(this);

    floatingActionButton = findViewById(R.id.floatingActionButtonforsaveloc);
    floatingActionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            opendialoyge();
        }
    });

}

@Override
public void onMapReady(@NonNull final MapboxMap mapboxMap) {
    MainActivity.this.mapboxMap = mapboxMap;
    mapboxMap.setStyle(new Style.Builder().fromUri("mapbox://styles/mapbox/satellite-streets-v11"),
            new Style.OnStyleLoaded() {
                @Override
                public void onStyleLoaded(@NonNull Style style) {
                    enableLocationComponent(style);

                    addFirstStopToStopsList();
                    initMarkerIconSymbolLayer(Objects.requireNonNull(style));
                    initOptimizedRouteLineLayer(style);
                    Toast.makeText(MainActivity.this, R.string.click_instructions, Toast.LENGTH_SHORT).show();
                    mapboxMap.addOnMapClickListener(MainActivity.this);
                    mapboxMap.addOnMapLongClickListener(MainActivity.this);


                    floatingActionButtonnavigate=findViewById(R.id.floatingActionButtonnavigation);
                    floatingActionButtonnavigate.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                            boolean simulateRoute = true;
                            NavigationLauncherOptions options = NavigationLauncherOptions.builder()
                                    .directionsRoute(optimizedRoute)
                                    .shouldSimulateRoute(simulateRoute)
                                    .build();

                            NavigationLauncher.startNavigation(MainActivity.this, options);


                        }
                    });
                }
            });

}

private void addFirstStopToStopsList() {

    origin = Point.fromLngLat(locationComponent.getLastKnownLocation().getLongitude(), locationComponent.getLastKnownLocation().getLatitude());
    stops.add(origin);
}
private void initMarkerIconSymbolLayer(@NonNull Style loadedMapStyle) {

    loadedMapStyle.addImage("icon-image", BitmapFactory.decodeResource(
            this.getResources(), R.drawable.mapbox_marker_icon_default));


    loadedMapStyle.addSource(new GeoJsonSource(ICON_GEOJSON_SOURCE_ID,
            Feature.fromGeometry(Point.fromLngLat(origin.longitude(), origin.latitude()))));

    loadedMapStyle.addLayer(new SymbolLayer("icon-layer-id", ICON_GEOJSON_SOURCE_ID).withProperties(
            iconImage("icon-image"),
            iconSize(1f),
            iconAllowOverlap(true),
            iconIgnorePlacement(true),
            iconOffset(new Float[] {0f, -4f})
    ));
}


private void initOptimizedRouteLineLayer(@NonNull Style loadedMapStyle) {
    loadedMapStyle.addSource(new GeoJsonSource("optimized-route-source-id"));
    loadedMapStyle.addLayerBelow(new LineLayer("optimized-route-layer-id", "optimized-route-source-id")
            .withProperties(
                    lineColor(Color.parseColor(TEAL_COLOR)),
                    lineWidth(POLYLINE_WIDTH)
            ), "icon-layer-id");
}

@SuppressWarnings({"MissingPermission"})
private void enableLocationComponent(@NonNull Style loadedMapStyle) {

    if (PermissionsManager.areLocationPermissionsGranted(this)) {

        locationComponent = mapboxMap.getLocationComponent();

        locationComponent.activateLocationComponent(
                LocationComponentActivationOptions.builder(this, loadedMapStyle).build());



        locationComponent.setLocationComponentEnabled(true);


        locationComponent.setCameraMode(CameraMode.TRACKING);


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

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



public void opendialoyge() {


    AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
    LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
    final View mView = inflater.inflate(R.layout.custome_dialouge, null);

    final EditText txt_input = mView.findViewById(R.id.entertext);
    Button btn_cancle = (Button) mView.findViewById(R.id.butcancle);
    Button btn_ok = (Button) mView.findViewById(R.id.butok);

    alert.setView(mView);
    alertDialog = alert.create();
    alertDialog.show();
    alertDialog.setCanceledOnTouchOutside(false);

    btn_cancle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            alertDialog.dismiss();
        }
    });

    btn_ok.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String text = txt_input.getText().toString();


            if (!text.isEmpty()) {




                assert locationComponent.getLastKnownLocation() != null;
                lattt = locationComponent.getLastKnownLocation().getLatitude();
                langgg = locationComponent.getLastKnownLocation().getLongitude();

                FirebaseDatabase database = FirebaseDatabase.getInstance();
                DatabaseReference myRef = database.getReference("Hajj&Umrah_App");

                myRef.child(text).child("lattt").setValue(lattt.toString());
                myRef.child(text).child("lang").setValue(langgg.toString());


            } else {
                Toast.makeText(MainActivity.this, "Please Enter group Name", Toast.LENGTH_SHORT).show();

            }

        }
    });
}

@Override
public boolean onMapClick(@NonNull LatLng point) {



    if (alreadyTwelveMarkersOnMap()) {
        Toast.makeText(MainActivity.this, R.string.only_twelve_stops_allowed, Toast.LENGTH_LONG).show();
    } else {
        Style style = mapboxMap.getStyle();
        if (style != null) {
            addDestinationMarker(style, point);
            addPointToStopsList(point);
            getOptimizedRoute(style, stops);
        }
    }

    return true;
}

@Override
public boolean onMapLongClick(@NonNull LatLng point) {
    stops.clear();
    if (mapboxMap != null) {
        Style style = mapboxMap.getStyle();
        if (style != null) {
            resetDestinationMarkers(style);
            removeOptimizedRoute(style);
            addFirstStopToStopsList();
            return true;
        }
    }
    return false;
}
private void resetDestinationMarkers(@NonNull Style style) {
    GeoJsonSource optimizedLineSource = style.getSourceAs(ICON_GEOJSON_SOURCE_ID);
    if (optimizedLineSource != null) {
        optimizedLineSource.setGeoJson(Point.fromLngLat(origin.longitude(), origin.latitude()));
    }
}

private void removeOptimizedRoute(@NonNull Style style) {
    GeoJsonSource optimizedLineSource = style.getSourceAs("optimized-route-source-id");
    if (optimizedLineSource != null) {
        optimizedLineSource.setGeoJson(FeatureCollection.fromFeatures(new Feature[] {}));
    }
}

private boolean alreadyTwelveMarkersOnMap() {
    return stops.size() == 3;
}

private void addDestinationMarker(@NonNull Style style, LatLng point) {
    List<Feature> destinationMarkerList = new ArrayList<>();
    for (Point singlePoint : stops) {
        destinationMarkerList.add(Feature.fromGeometry(
                Point.fromLngLat(singlePoint.longitude(), singlePoint.latitude())));
    }
    destinationMarkerList.add(Feature.fromGeometry(Point.fromLngLat(point.getLongitude(), point.getLatitude())));
    GeoJsonSource iconSource = style.getSourceAs(ICON_GEOJSON_SOURCE_ID);
    if (iconSource != null) {
        iconSource.setGeoJson(FeatureCollection.fromFeatures(destinationMarkerList));
    }
}

private void addPointToStopsList(LatLng point) {
    stops.add(Point.fromLngLat(point.getLongitude(), point.getLatitude()));
}


private void getOptimizedRoute(@NonNull final Style style, List<Point> coordinates) {
             NavigationRoute.builder(this);
             optimizedClient = MapboxOptimization.builder()
            .source(FIRST)
            .destination(ANY)
            .coordinates(coordinates)
            .overview(DirectionsCriteria.OVERVIEW_FULL)
            .profile(DirectionsCriteria.PROFILE_DRIVING)
            .accessToken(Mapbox.getAccessToken())
            .build();

    optimizedClient.enqueueCall(new Callback<OptimizationResponse>() {
        @Override
        public void onResponse(Call<OptimizationResponse> call, Response<OptimizationResponse> response) {
            if (!response.isSuccessful()) {
                Timber.d( getString(R.string.no_success));
                Toast.makeText(MainActivity.this, R.string.no_success, Toast.LENGTH_SHORT).show();
                return;
            } else {
                if (response.body().trips().isEmpty()) {
                    Timber.d("%s size = %s", getString(R.string.successful_but_no_routes), response.body().trips().size());

                    Toast.makeText(MainActivity.this, R.string.successful_but_no_routes,
                            Toast.LENGTH_SHORT).show();
                    return;
                }
            }

            optimizedRoute = Objects.requireNonNull(response.body().trips()).get(0);

            if (navigationMapRoute!=null){
                navigationMapRoute.removeRoute();
            }
            else {
                navigationMapRoute = new NavigationMapRoute(null,mapView,mapboxMap,R.style.NavigationMapRoute);
            }

            drawOptimizedRoute(style, optimizedRoute);

        }

        @Override
        public void onFailure(Call<OptimizationResponse> call, Throwable throwable) {
            Timber.d("Error: %s", throwable.getMessage());
        }
    });
}

private void drawOptimizedRoute(@NonNull Style style, DirectionsRoute route) {
    GeoJsonSource optimizedLineSource = style.getSourceAs("optimized-route-source-id");
    if (optimizedLineSource != null) {
        optimizedLineSource.setGeoJson(FeatureCollection.fromFeature(Feature.fromGeometry(
                LineString.fromPolyline(route.geometry(), PRECISION_6))));
    }
}


@Override
@SuppressWarnings({"MissingPermission"})
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();
    if (optimizedClient != null) {
        optimizedClient.cancelCall();
    }
    if (mapboxMap != null) {
        mapboxMap.removeOnMapClickListener(this);
    }
    mapView.onDestroy();
}

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