【问题标题】:Get latitude and longitude from onSuccess(LocationEngineResult result) [duplicate]从onSuccess(LocationEngineResult结果)获取纬度和经度[重复]
【发布时间】:2020-02-28 08:39:20
【问题描述】:

我通过覆盖方法获取用户当前位置

     public void onSuccess(LocationEngineResult result) {
     location = Point.fromLngLat(result.getLastLocation().getLongitude(),result.getLastLocation().getLatitude());
    }

但我不知道如何替换变量上的经纬度

private final Point ROUTE_ORIGIN=Point.fromLngLat(location.longitude(),location.latitude());

我从 public void onSuccess(LocationEngineResult result) 获得的位置有什么解决方案吗?

应用程序因错误而崩溃

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'double com.mapbox.geojson.Point.longitude()' on a null object reference

谁能给我一些想法或解决方案?我试图找到来源,但仍然无法解决。

    public class ArActivity extends BaseActivity implements RouteListener, ProgressChangeListener, OffRouteListener {

    private static final String TAG = ArActivity.class.getSimpleName();

    // Handles navigation.
    private MapboxNavigation mapboxNavigation;
    // Fetches route from points.
    private RouteFetcher routeFetcher;
    private RouteProgress lastRouteProgress;
    private PermissionsManager permissionsManager;
    private LocationEngine locationEngine;

    private LocationEngineCallback<LocationEngineResult> locationCallback;
    public Point location;

    private boolean visionManagerWasInit = false;
    private boolean navigationWasStarted = false;
    TextView tvlocation;

    // This dummy points will be used to build route. For real world test this needs to be changed to real values for
    // source and target location
    private final Point ROUTE_ORIGIN=Point.fromLngLat(location.longitude(),location.latitude());
    private final Point ROUTE_DESTINATION = Point.fromLngLat(101.769116, 2.923220);

    @Override
    protected void initViews() {

        setContentView(R.layout.activity_ar_navigation);
        tvlocation = findViewById(R.id.location);

    }

    @Override
    protected void onPermissionsGranted() {
        startVisionManager();
        startNavigation();

    }

    @Override
    protected void onStart() {
        super.onStart();
        startVisionManager();
        startNavigation();

    }

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

    private void startVisionManager() {
        if (allPermissionsGranted() && !visionManagerWasInit) {
            // Create and start VisionManager.

            VisionManager.create();
            VisionManager.setModelPerformanceConfig(new Merged(new On(ModelPerformanceMode.DYNAMIC, ModelPerformanceRate.LOW)));
            VisionManager.start();
            VisionManager.setVisionEventsListener(new VisionEventsListener() {
                @Override
                public void onAuthorizationStatusUpdated(@NotNull AuthorizationStatus authorizationStatus) {
                }

                @Override
                public void onFrameSegmentationUpdated(@NotNull FrameSegmentation frameSegmentation) {
                }

                @Override
                public void onFrameDetectionsUpdated(@NotNull FrameDetections frameDetections) {
                }

                @Override
                public void onFrameSignClassificationsUpdated(@NotNull FrameSignClassifications frameSignClassifications) {
                }

                @Override
                public void onRoadDescriptionUpdated(@NotNull RoadDescription roadDescription) {
                }

                @Override
                public void onWorldDescriptionUpdated(@NotNull WorldDescription worldDescription) {
                }

                @Override
                public void onVehicleStateUpdated(@NotNull VehicleState vehicleState) {
                }

                @Override
                public void onCameraUpdated(@NotNull Camera camera) {
                }

                @Override
                public void onCountryUpdated(@NotNull Country country) {
                }

                @Override
                public void onUpdateCompleted() {
                }
            });

            VisionArView visionArView = findViewById(R.id.mapbox_ar_view);

            // Create VisionArManager.
            VisionArManager.create(VisionManager.INSTANCE);
            visionArView.setArManager(VisionArManager.INSTANCE);
            visionArView.setFenceVisible(true);
            visionManagerWasInit = true;
        }
    }

    private void stopVisionManager() {
        if (visionManagerWasInit) {
            VisionArManager.destroy();
            VisionManager.stop();
            VisionManager.destroy();
            visionManagerWasInit = false;
        }
    }

    private void startNavigation() {
        if (allPermissionsGranted() && !navigationWasStarted) {
            // Initialize navigation with your Mapbox access token.
            mapboxNavigation = new MapboxNavigation(
                    this,
                    getString(R.string.mapbox_access_token),
                    MapboxNavigationOptions.builder().build()
            );

            // Initialize route fetcher with your Mapbox access token.
            routeFetcher = new RouteFetcher(this, getString(R.string.mapbox_access_token));
            routeFetcher.addRouteListener(this);

            locationEngine = LocationEngineProvider.getBestLocationEngine(this);

            LocationEngineRequest arLocationEngineRequest = new LocationEngineRequest.Builder(0)
                    .setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY)
                    .setFastestInterval(1000)
                    .build();


            locationCallback = new LocationEngineCallback<LocationEngineResult> () {
                @Override
                public void onSuccess(LocationEngineResult result) {

                        location = Point.fromLngLat(result.getLastLocation().getLongitude(),result.getLastLocation().getLatitude());
                                       }

                @Override
                public void onFailure(@NonNull Exception exception) {

                }
            };

            try {
                locationEngine.requestLocationUpdates(arLocationEngineRequest, locationCallback, Looper.getMainLooper());
            } catch (SecurityException se) {
                VisionLogger.Companion.e(TAG, se.toString());
            }

            initDirectionsRoute();

            // Route need to be reestablished if off route happens.
            mapboxNavigation.addOffRouteListener(this);
            mapboxNavigation.addProgressChangeListener(this);

            navigationWasStarted = true;
        }
    }

    private void stopNavigation() {
        if (navigationWasStarted) {
            locationEngine.removeLocationUpdates(locationCallback);

            mapboxNavigation.removeProgressChangeListener(this);
            mapboxNavigation.removeOffRouteListener(this);
            mapboxNavigation.stopNavigation();

            navigationWasStarted = false;
        }
    }

    private void initDirectionsRoute() {
        // Get route from predefined points.
        NavigationRoute.builder(this)
                .accessToken(getString(R.string.mapbox_access_token))
                .origin(ROUTE_ORIGIN)
                .destination(ROUTE_DESTINATION)
                .build()
                .getRoute(new Callback<DirectionsResponse>() {
                    @Override
                    public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
                        if (response.body() == null || response.body().routes().isEmpty()) {
                            return;
                        }

                        // Start navigation session with retrieved route.
                        DirectionsRoute route = response.body().routes().get(0);
                        mapboxNavigation.startNavigation(route);

                        // Set route progress.
                        VisionArManager.setRoute(new Route(
                                getRoutePoints(route),
                                route.duration().floatValue(),
                                "",
                                ""
                        ));
                    }

                    @Override
                    public void onFailure(Call<DirectionsResponse> call, Throwable t) {
                    }
                });
    }

    @Override
    public void onErrorReceived(Throwable throwable) {
        if (throwable != null) {
            throwable.printStackTrace();
        }

        mapboxNavigation.stopNavigation();
        Toast.makeText(this, "Can not calculate the route requested", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onResponseReceived(@NotNull DirectionsResponse response, RouteProgress routeProgress) {
        mapboxNavigation.stopNavigation();
        if (response.routes().isEmpty()) {
            Toast.makeText(this, "Can not calculate the route requested", Toast.LENGTH_SHORT).show();
        } else {
            DirectionsRoute route = response.routes().get(0);

            mapboxNavigation.startNavigation(route);

            // Set route progress.
            VisionArManager.setRoute(new Route(
                    getRoutePoints(route),
                    (float) routeProgress.durationRemaining(),
                    "",
                    ""
            ));
        }
    }

    @Override
    public void onProgressChange(Location location, RouteProgress routeProgress) {
        lastRouteProgress = routeProgress;
    }

    @Override
    public void userOffRoute(Location location) {
        routeFetcher.findRouteFromRouteProgress(location, lastRouteProgress);
    }



    private RoutePoint[] getRoutePoints(@NotNull DirectionsRoute route) {
        ArrayList<RoutePoint> routePoints = new ArrayList<>();

        List<RouteLeg> legs = route.legs();
        if (legs != null) {
            for (RouteLeg leg : legs) {

                List<LegStep> steps = leg.steps();
                if (steps != null) {
                    for (LegStep step : steps) {
                        RoutePoint point = new RoutePoint((new GeoCoordinate(
                                step.maneuver().location().latitude(),
                                step.maneuver().location().longitude()
                        )), mapToManeuverType(step.maneuver().type()));

                        routePoints.add(point);

                        List<Point> geometryPoints = buildStepPointsFromGeometry(step.geometry());
                        for (Point geometryPoint : geometryPoints) {
                            point = new RoutePoint((new GeoCoordinate(
                                    geometryPoint.latitude(),
                                    geometryPoint.longitude()
                            )), ManeuverType.None);

                            routePoints.add(point);
                        }
                    }
                }
            }
        }

        return routePoints.toArray(new RoutePoint[0]);
    }

    private List<Point> buildStepPointsFromGeometry(String geometry) {
        return PolylineUtils.decode(geometry, Constants.PRECISION_6);
    }

    private ManeuverType mapToManeuverType(@Nullable String maneuver) {
        if (maneuver == null) {
            return ManeuverType.None;
        }
        switch (maneuver) {
            case "turn":
                return ManeuverType.Turn;
            case "depart":
                return ManeuverType.Depart;
            case "arrive":
                return ManeuverType.Arrive;
            case "merge":
                return ManeuverType.Merge;
            case "on ramp":
                return ManeuverType.OnRamp;
            case "off ramp":
                return ManeuverType.OffRamp;
            case "fork":
                return ManeuverType.Fork;
            case "roundabout":
                return ManeuverType.Roundabout;
            case "exit roundabout":
                return ManeuverType.RoundaboutExit;
            case "end of road":
                return ManeuverType.EndOfRoad;
            case "new name":
                return ManeuverType.NewName;
            case "continue":
                return ManeuverType.Continue;
            case "rotary":
                return ManeuverType.Rotary;
            case "roundabout turn":
                return ManeuverType.RoundaboutTurn;
            case "notification":
                return ManeuverType.Notification;
            case "exit rotary":
                return ManeuverType.RotaryExit;
            default:
                return ManeuverType.None;
        }
    }

【问题讨论】:

    标签: java android nullpointerexception


    【解决方案1】:

    在实例化这一行时(即类加载时):

    private final Point ROUTE_ORIGIN=Point.fromLngLat(location.longitude(),location.latitude());
    

    您正在使用的 location 变量设置为空:

    public Point location;
    

    Aka,它是 null,你得到一个 NullPointerException。

    您不应该尝试使用 location 对象,直到它被实例化,稍后设置您的 routeOrigin。或者将ROUTE_ORIGIN 更改为使用静态位置,就像ROUTE_DESTINATION 一样。

    【讨论】:

    • 对不起,我是安卓新手。如果我想稍后设置我的ROUTE_ORIGIN,我该怎么办?因为我实际上想将我从location 得到的纬度和经度传递给ROUTE_ORIGIN,但我不知道该怎么做。
    • 查看lastRouteProgress 设置“稍后”的方式,这就是我的意思。你可以用if(routeOrigin != null)包围它,在你实例化它之前停止使用它
    • 它就像一个魅力!非常感谢你帮助我!!你不知道我一直在寻找解决方案多久。非常感谢,祝您有美好的一天! :)
    猜你喜欢
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 2011-04-01
    • 2018-06-26
    • 2014-01-25
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    相关资源
    最近更新 更多