Search code examples
javaandroidroutesmapboxdirections

Mapbox (android) does not show directions


As a user, I want to use an android application to navigate through the map using routes. Once I get the route going, I would develop other ways to organize the navigation, but as of yet, I can't show a route in my map.

I am using this tutorial given by Mapbox themselves: https://www.mapbox.com/android-sdk/examples/directions/ . There are no messages error, in fact, the toast message that shows the route distance is visible after I access the map view. ("Route is 0.0 meters long.") I have checked the logs, the generic HTML code is 200 (Which is the okay one) and the debug message shows a 0.0 meter long route. There are no errors found in the log besides that.

I have double checked the code for a week for any mistake I have made, but I did not find anything that could provoke the error to not show the route. I have debugged the code as well, and it reaches the drawRoute function without no problems, I have checked the token as well, and it works just fine.

What have I done to not show the route? Thanks a lot!

Image example when you try to see a route.

Java code:

public class Mapa extends Activity {
private static final String TAG = "Mapa"; //Tag para usar no log de debug e error

private MapView mapView;
private MapboxMap map;
private DirectionsRoute currentRoute;

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

    // Mapbox usa esse token de acesso atraves de uma conta do mapbox, so precisa ser configurado uma vez!
    MapboxAccountManager.start(this,getString(R.string.access_token));

    // Contem o mapview exposto em XML e precisa ser chamado LOGO APOS o account manager
    setContentView(R.layout.activity_main);

    // Funcao que pede permissao para o usuario no seu celular -- TODO
    PedePermissao();

    // Origem: Rodoviaria
    final Position origin = Position.fromCoordinates(-15.794082, -47.882645);
    // Destino: Reitoria
    final Position destination = Position.fromCoordinates(-15.762604, -47.866611);


    //Configuracao do mapa
    mapView = (MapView) findViewById(R.id.mapView);
    mapView.onCreate(savedInstanceState);
    mapView.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(MapboxMap mapboxMap) {
            map = mapboxMap;

            // Criacao e declaracao do icone
            IconFactory iconFactory = IconFactory.getInstance(Mapa.this);
            Drawable iconDrawable = ContextCompat.getDrawable(Mapa.this, R.drawable.infoicon);
            Icon icon = iconFactory.fromDrawable(iconDrawable);
            Drawable iconeDrawableRota = ContextCompat.getDrawable(Mapa.this, R.drawable.infoicon_rota);
            Icon iconeRota = iconFactory.fromDrawable(iconeDrawableRota);

            //Marcadores das instalacoes
            mapboxMap.addMarker(new MarkerViewOptions()
                    .position(new LatLng(-15.76363, -47.86949))
                    .title("ICC Centro")
                    .snippet(getString(R.string.desc_ICC_Centro))
                    .icon(icon));

            mapboxMap.addMarker(new MarkerViewOptions()
                    .position(new LatLng(-15.7629936, -47.86717415))
                    .title("Reitoria")
                    .snippet(getString(R.string.desc_Reitoria))
                    .icon(icon));

            mapboxMap.addMarker(new MarkerViewOptions()
                    .position(new LatLng(-15.76196106, -47.87008166))
                    .title("FAU")
                    .snippet(getString(R.string.desc_FAU))
                    .icon(icon));

            // Adicionando os marcadores de destino da rota
            mapboxMap.addMarker(new MarkerOptions()
                    .position(new LatLng(origin.getLatitude(), origin.getLongitude()))
                    .title("Origem")
                    .icon(iconeRota));
            mapboxMap.addMarker(new MarkerOptions()
                    .position(new LatLng(destination.getLatitude(), destination.getLongitude()))
                    .title("Destino")
                    .icon(iconeRota));

            try {
                getRoute(origin, destination);
            } catch (ServicesException servicesException) {
                servicesException.printStackTrace();
            }

            //Dados da janela (infowindow) quando clicar em um ponteiro (marker)
            mapboxMap.setInfoWindowAdapter(new MapboxMap.InfoWindowAdapter() {
                    //...
                }
            });
        }
    });
}

private void getRoute(Position origin, Position destination) throws ServicesException {

    MapboxDirections client = new MapboxDirections.Builder()
            .setOrigin(origin)
            .setDestination(destination)
            .setProfile(DirectionsCriteria.PROFILE_DRIVING)
            .setAccessToken(MapboxAccountManager.getInstance().getAccessToken())
            .build();


    client.enqueueCall(new Callback<DirectionsResponse>() {
        @Override
        public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {

            // Voce pode pegar mensagens de erro genericas do http sobre o response

            Log.d(TAG, "Codigo de resposta: " + response.code());
            if (response.body() == null) {
                Log.e(TAG, "Sem rotas encontradas, porém sem o uso do token, verifique o token de acesso");
                return;
            } else if (response.body().getRoutes().size() < 1) {
                Log.e(TAG, "Sem rotas encontradas!");
                return;
            }

            // Printa algumas informacoes sobre a rota
            currentRoute = response.body().getRoutes().get(0);
            Log.d(TAG, "Distancia: " + currentRoute.getDistance());
            Toast.makeText(
                    Mapa.this,
                    "A rota tem " + currentRoute.getDistance() + " metros de distância.",
                    Toast.LENGTH_SHORT).show();

            // Desenhar a rota no mapa
            drawRoute(currentRoute);
        }

        @Override
        public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
            Log.e(TAG, "Erro: " + throwable.getMessage());
            Toast.makeText(Mapa.this, "Erro: " + throwable.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });
}

private void drawRoute(DirectionsRoute route) {

    // Converter as coordenadas LineString em LatLng[]
    LineString lineString = LineString.fromPolyline(route.getGeometry(), Constants.OSRM_PRECISION_V5);
    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());
    }

    // Escrever os pontos no MapView
    map.addPolyline(new PolylineOptions()
            .add(points)
            .color(Color.parseColor("#009688"))
            .width(5));
}

Solution

  • You coordinates are in the incorrect order. While LatLng is created in the latitude, longitude order, Position is xy ordering or longitude, latitude. So your origin and destination should be:

    // Origem: Rodoviaria
    final Position origin = Position.fromCoordinates(-47.882645, -15.794082);
    // Destino: Reitoria
    final Position destination = Position.fromCoordinates(-47.866611, -15.762604);