SCTaylor
SCTaylor

Reputation: 141

Drawing a polyline from my location to a marker

I am using Mapbox (4.2.1) to draw a line from my position to a target position. I have the intention of using the straight line as an extremely basic navigation aid. As such I am re-drawing the guide line OnMyLocationChanged(). However it appears that as my location changes it will draw the line to my new location but MyLocationView (User icon) does not update in accordance (See image below).

They will eventually end up meeting again but it takes some time. It seems that the line is getting drawn inside the accuracy radius, however I would prefer if it could draw the line straight from the user icon.

Is there a simple way to draw a line between the user (The actual icon on the map) and a location which updates as the user moves?

My OnMyLocationChanged is:

MapboxMap.OnMyLocationChangeListener listner = new MapboxMap.OnMyLocationChangeListener(){
        @Override
        public void onMyLocationChange(final @Nullable Location locationChanged) {
            //If we are not targeting anything or we are not tracking location
            if(target == null || !map.isMyLocationEnabled()) return;

            mapView.getMapAsync(new OnMapReadyCallback() {
                @Override
                public void onMapReady(MapboxMap mapboxMap) {
                    //Log.i("LOC-MAPLINE", "Drawing from mapLoc call");

                    //Error if we don't have a location
                    if(!mapboxMap.isMyLocationEnabled() || locationChanged == null) return;

                    LatLng[] points = new LatLng[2];

                    final Location myLoc = locationChanged;

                    LatLng loc = new LatLng(myLoc.getLatitude(), myLoc.getLongitude());
                    LatLng dest = new LatLng(target.getLatitude(), target.getLongitude());
                    points[0] = loc;
                    points[1] = dest;

                    mapboxMap.removeAnnotations();

                    loadMarker(target);


                    PolylineOptions poly = new PolylineOptions()
                            .add(points)
                            .color(Color.parseColor("#3887be"))
                            .width(5);
                    line = mapboxMap.addPolyline(poly);
                }
            });
        }
    };

Line error

Any assistance is greatly appreciated, thank you!

EDIT (In regards to possible duplicate question - Google direction route from current location to known location) I believe my question is different for a few reasons.

  1. I am more concerned on getting the location of the user icon overlay rather than actual location (Accuracy issue)

  2. I am not interested in getting turn for turn directions (Like those from a directions API)

  3. I am using Mapbox rather than google maps (Not too sure but there could be some differences).

Nevertheless that question does not seem to answer my question

Upvotes: 0

Views: 3497

Answers (1)

Mina Fawzy
Mina Fawzy

Reputation: 21452

According to documentation you need only implement this method passing your currentLocation (origin) and destination

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

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

    client.enqueueCall(new Callback<DirectionsResponse>() {
      @Override
      public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
        // You can get the generic HTTP info about the response
        Log.d(TAG, "Response code: " + response.code());
        if (response.body() == null) {
          Log.e(TAG, "No routes found, make sure you set the right user and access token.");
          return;
        } else if (response.body().getRoutes().size() < 1) {
          Log.e(TAG, "No routes found");
          return;
        }

        // Print some info about the route
        currentRoute = response.body().getRoutes().get(0);
        Log.d(TAG, "Distance: " + currentRoute.getDistance());
        Toast.makeText(
          DirectionsActivity.this,
          "Route is " + currentRoute.getDistance() + " meters long.",
          Toast.LENGTH_SHORT).show();

        // Draw the route on the map
        drawRoute(currentRoute);
      }

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

private void drawRoute(DirectionsRoute route) {
    // Convert LineString coordinates into 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());
    }

    // Draw Points on MapView
    map.addPolyline(new PolylineOptions()
      .add(points)
      .color(Color.parseColor("#009688"))
      .width(5));
  }

reference https://www.mapbox.com/android-sdk/examples/directions/

Upvotes: 1

Related Questions