Mapbox Reroute при прохождении через маркер - PullRequest
0 голосов
/ 11 марта 2019

Привет всем Добрый день .. может кто-нибудь, пожалуйста, помогите мне с моим текущим проектом для моей школы. в настоящее время я использую mapbox для направления и навигации по маршруту ... но есть ли способ перенаправить мое направление, если на его пути есть маркер .. вот пример изображения и исходный код проекта

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback, LocationEngineListener,
    PermissionsListener, MapboxMap.OnMapClickListener {

private LatLng locationOne;
private LatLng locationTwo;

private static final LatLngBounds LEGAZPI_DARAGA = new LatLngBounds.Builder()
        .include(new LatLng(13.172012, 123.687115))
        .include(new LatLng(13.118521, 123.781905))
        .build();

private MapView mapView;
private Button startButon;
private MapboxMap map;
private PermissionsManager permissionsManager;
private LocationEngine locationEngine;
private LocationLayerPlugin locationLayerPlugin;
private Location originLocation;
private Point originPosition;
private Point destinationPosition;
private Marker destinationMarker;
private NavigationMapRoute navigationMapRoute;
private static final String TAG = "MainActivity";

private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";


private static final String TAG_USERID = "user_id";
private static final String TAG_LATT = "latt";
private static final String TAG_LNG = "lng";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_DATE_FROM = "date_from";
private static final String TAG_DATE_TO = "date_to";
private static final String TAG_TYPE = "type";

String message;
int success;
String tag_json_obj = "json_obj_req";
ProgressDialog pDialog;
ConnectivityManager conMgr;
Icon icon;
LatLng latLng;
String user_id, latt, lng, description, date_from, date_to, type;

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

    Mapbox.getInstance(this, "pk.eyJ1Ijoia2lrczA3ODkiLCJhIjoiY2pxbWJ4YnBjMTh2dzQybTA1amN1amN3MiJ9.JlaA5vtXfbGaVk7ZLWfijw");
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    startButon = findViewById(R.id.startButton);
    mapView = findViewById(R.id.mapView);
    mapView.onCreate(savedInstanceState);

    mapView.getMapAsync(this);

    startButon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            NavigationLauncherOptions options = NavigationLauncherOptions.builder()
                    .origin(originPosition)
                    .destination(destinationPosition)
                    //.shouldSimulateRoute(true)
                    .build();
            NavigationLauncher.startNavigation(MainActivity.this, options);
        }
    });
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}


@Override
public void onMapReady(MapboxMap mapboxMap) {
    map = mapboxMap;
    map.addOnMapClickListener(this);
    enabledLocation();

    locationOne = new LatLng(13.165400, 123.702463);
    locationTwo = new LatLng(13.134649, 123.762822);

    //mapboxMap.addMarker(new MarkerOptions()
    //    .position(locationOne));

    //mapboxMap.addMarker(new MarkerOptions()
    //    .position(locationTwo));

    // Toast instructing user to tap on the map to start animation and set bounds
    Toast.makeText(
            MainActivity.this,
            getString(R.string.tap_on_map_instruction),
            Toast.LENGTH_LONG
    ).show();
    mapboxMap.addOnMapClickListener(this);

    mapboxMap.setLatLngBoundsForCameraTarget(LEGAZPI_DARAGA);
    mapboxMap.setMinZoomPreference(2);

    getMarkers(mapboxMap);




}
private void getRoute(Point origin, Point destination){
    NavigationRoute.builder()
            .accessToken(Mapbox.getAccessToken())
            .origin(origin)
            .destination(destination)
            .build()
            .getRoute(new Callback<DirectionsResponse>() {
                @Override
                public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
                    if(response.body() == null){
                        Log.e(TAG, "no routes found! check right user access token");
                        return;
                    }
                    else if(response.body().routes().size() == 0){
                        Log.e(TAG, "no routes found");
                        return;
                    }
                    DirectionsRoute currentRoute = response.body().routes().get(0);

                    if(navigationMapRoute != null){
                        navigationMapRoute.removeRoute();
                    }

                    else{
                        navigationMapRoute = new NavigationMapRoute(null, mapView, map);
                    }


                    navigationMapRoute.addRoute(currentRoute);
                }

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

private void getMarkers(MapboxMap mapboxMap) {
    String url2 = Server.URL + "get-markers.php";
    StringRequest strReq = new StringRequest(Request.Method.POST, url2, new com.android.volley.Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.e("Response: ", response.toString());

            try {
                JSONObject jObj = new JSONObject(response);
                String getObject = jObj.getString("markers");

                JSONArray jsonArray = new JSONArray(getObject);

                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);

                    user_id = jsonObject.getString(TAG_USERID);
                    latt = jsonObject.getString(TAG_LATT);
                    lng = jsonObject.getString(TAG_LNG);
                    description = jsonObject.getString(TAG_DESCRIPTION);
                    date_from = jsonObject.getString(TAG_DATE_FROM);
                    date_to = jsonObject.getString(TAG_DATE_TO);
                    type = jsonObject.getString(TAG_TYPE);

                    latLng = new LatLng(Double.parseDouble(jsonObject.getString(TAG_LATT)), Double.parseDouble(jsonObject.getString(TAG_LNG)));
                    // Toast.makeText(getApplicationContext(),""+latLng, Toast.LENGTH_LONG).show();
                    //  Adds a data marker to show to google map
                    addMarker(latLng,description,mapboxMap);



                }

            } catch (JSONException e) {
                // JSON error
                e.printStackTrace();
            }

        }
    }, new com.android.volley.Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplicationContext(), "Try Again!", Toast.LENGTH_LONG).show();
        }
    });


    AppController.getInstance().addToRequestQueue(strReq, tag_json_obj);
}

private void addMarker(LatLng latLng, String description, MapboxMap mapboxMap) {

    if(type.contains("works")){
        icon = IconFactory.getInstance(MainActivity.this).fromResource(R.drawable.men_at_work);
    }
    else if(type.contains("safety")){
        icon = IconFactory.getInstance(MainActivity.this).fromResource(R.drawable.noentry1);
    }
    else if(type.contains("city")){
        icon = IconFactory.getInstance(MainActivity.this).fromResource(R.drawable.road);
    }
    else{
        icon = IconFactory.getInstance(MainActivity.this).fromResource(R.drawable.user);
    }
    mapboxMap.addMarker(new MarkerOptions()
            .position(latLng)
            .title(description)
            .snippet(getString(R.string.draw_marker_options_snippet))
            .icon(icon));
}

Заранее спасибо, ваша помощь будет оценена :)

enter image description here

...