将用户位置定义为起始点MAPBOX

时间:2017-11-29 21:53:34

标签: android navigation mapbox mapbox-android

我目前正在尝试使用地图框导航

我做了什么:

  • 定义积分列表
  • 计算优化行程
  • 获取位置引擎的用户位置
  • 在导航ui参数
  • 上传递优化路线

我的问题是:如何将起点定义为位置引擎?

你知道如何继续吗?

我的代码:

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

    // Initialize list of Position objects and add the origin Position to the list


    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }


    mFusedLocationClient.getLastLocation()
            .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    // Got last known location. In some rare situations this can be null.
                    if (location != null) {
                       location.getLatitude();
                       location.getLongitude();

                    }
                }
            });


    // Setup the MapView
    mapView = (MapView) findViewById(R.id.mapView);
    mapView.onCreate(savedInstanceState);
    mapView.getMapAsync(new OnMapReadyCallback() {


        @Override
        public void onMapReady(MapboxMap mapboxMap) {
            map = mapboxMap;
            // Add origin and destination to the map

            getOptimizedRoute(stops);
            enableLocationPlugin();
            button = findViewById(R.id.startButton);
            button.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {

                    // Pass in your Amazon Polly pool id for speech synthesis using Amazon Polly
                    // Set to null to use the default Android speech synthesizer
                    String awsPoolId = null;

                    boolean simulateRoute = true;

                    NavigationLauncher.startNavigation(OptimizationRound.this, optimizedRoute, null, false);

                    DirectionsRoute  op=optimizedRoute;

                    Log.i("te","d"+op);


                }
            });
        }
    });
}



private boolean alreadyTwelveMarkersOnMap() {
    if (stops.size() == 12) {
        return true;
    } else {
        return false;
    }
}




private void addDestinationMarker() {
    map.addMarker(new MarkerOptions()
            .position(new LatLng(48.85661, 2.3522199999999884))
            .title("ajout d'un marker"));



    map.addMarker(new MarkerOptions()
            .position(new LatLng(48.863837885793835, 2.3865522753906134))
            .title("ajout d'un marker"));


}

private void addPointToStopsList() {
    List tripStops = new ArrayList<>();
    tripStops.add(Position.fromCoordinates(2.3522199999999884, 48.85661));
    tripStops.add(Position.fromCoordinates(2.3865522753906134, 48.863837885793835));
    ;


}


private DirectionsRoute getOptimizedRoute(List<Position> coordinates) {
    addDestinationMarker();
    List tripStops = new ArrayList<>();


    tripStops.add(Position.fromCoordinates(2.3522199999999884, 48.85661));
    tripStops.add(Position.fromCoordinates(2.3865522753906134, 48.863837885793835));


    optimizedClient = new MapboxOptimizedTrips.Builder()
            .setSource(FIRST)
            .setDestination(ANY)
            .setCoordinates(tripStops)
            .setOverview(DirectionsCriteria.OVERVIEW_FULL)
            .setProfile(DirectionsCriteria.PROFILE_DRIVING)
            .setAccessToken(Mapbox.getAccessToken())
            .build();

    optimizedClient.enqueueCall(new Callback<OptimizedTripsResponse>() {
        @Override
        public void onResponse(Call<OptimizedTripsResponse> call, Response<OptimizedTripsResponse> response) {
            if (!response.isSuccessful()) {
                Log.d("DirectionsActivity", "no succes");
                Toast.makeText(OptimizationRound.this, 't', Toast.LENGTH_SHORT).show();
                return;
            } else {
                if (response.body().getTrips().isEmpty()) {
                    Log.d("DirectionsActivity", "impossible de detrminer l'itineraire" + " size = "
                            + response.body().getTrips().size());
                    Toast.makeText(OptimizationRound.this, "route ok",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
            }

            // Get most optimized route from API response
            optimizedRoute = response.body().getTrips().get(0);
            drawOptimizedRoute(optimizedRoute);
        }

        @Override
        public void onFailure(Call<OptimizedTripsResponse> call, Throwable throwable) {
            Log.d("DirectionsActivity", "Error: " + throwable.getMessage());
        }
    });
    return null;
}

private void drawOptimizedRoute(DirectionsRoute route) {
    // Remove old polyline
    if (optimizedPolyline != null) {
        map.removePolyline(optimizedPolyline);
    }
    // Draw points on MapView
    LatLng[] pointsToDraw = convertLineStringToLatLng(route);
    optimizedPolyline = map.addPolyline(new PolylineOptions()
            .add(pointsToDraw)
            .color(Color.parseColor(TEAL_COLOR))
            .width(POLYLINE_WIDTH));
}

private LatLng[] convertLineStringToLatLng(DirectionsRoute route) {
    // Convert LineString coordinates into LatLng[]
    LineString lineString = LineString.fromPolyline(route.getGeometry(), PRECISION_6);
    List<Position> coordinates = lineString.getCoordinates();
    LatLng[] points = new LatLng[coordinates.size()];
    for (int i = 0; i < coordinates.size(); i++) {
        points[i] = new LatLng(
                coordinates.get(i).getLatitude(),
                coordinates.get(i).getLongitude());
    }
    return points;
}


@SuppressWarnings( {"MissingPermission"})
private void enableLocationPlugin() {
    // Check if permissions are enabled and if not request
    if (PermissionsManager.areLocationPermissionsGranted(this)) {
        // Create an instance of LOST location engine
        initializeLocationEngine();

        locationPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
        locationPlugin.setLocationLayerEnabled(LocationLayerMode.TRACKING);
    } else {
        permissionsManager = new PermissionsManager(this);
        permissionsManager.requestLocationPermissions(this);
    }
}

@SuppressWarnings( {"MissingPermission"})
private void initializeLocationEngine() {
    locationEngine = new LostLocationEngine(OptimizationRound.this);
    locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
    locationEngine.activate();

    Location lastLocation = locationEngine.getLastLocation();
    if (lastLocation != null) {
        originLocation = lastLocation;
        setCameraPosition(lastLocation);
    } else {
        locationEngine.addLocationEngineListener(this);
    }
}

private void setCameraPosition(Location location) {
    map.animateCamera(CameraUpdateFactory.newLatLngZoom(
            new LatLng(location.getLatitude(), location.getLongitude()), 13));
}

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

@Override
public void onExplanationNeeded(List<String> permissionsToExplain) {

}

@Override
public void onPermissionResult(boolean granted) {
    if (granted) {
        enableLocationPlugin();
    } else {
        finish();
    }
}

@Override
@SuppressWarnings( {"MissingPermission"})
public void onConnected() {
    locationEngine.requestLocationUpdates();
}

@Override
public void onLocationChanged(Location location) {
    if (location != null) {
        originLocation = location;
        setCameraPosition(location);
        locationEngine.removeLocationEngineListener(this);
    }
}

@Override
@SuppressWarnings( {"MissingPermission"})
protected void onStart() {
    super.onStart();
    if (locationEngine != null) {
        locationEngine.requestLocationUpdates();
    }
    if (locationPlugin != null) {
        locationPlugin.onStart();
    }
    mapView.onStart();
}

@Override
protected void onStop() {
    super.onStop();
    if (locationEngine != null) {
        locationEngine.removeLocationUpdates();
    }
    if (locationPlugin != null) {
        locationPlugin.onStop();
    }
    mapView.onStop();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    mapView.onDestroy();
    if (locationEngine != null) {
        locationEngine.deactivate();
    }
}

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

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

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

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    mapView.onSaveInstanceState(outState);
}

感谢支持

0 个答案:

没有答案