Vas
Vas

Reputation: 2064

Mapbox polylines not working

I am trying to draw a path using Mapbox's polylines. However, no lines appear to get drawn. I decided to add markers as well, just to see if they would get added. Adding markers works. Why not polylines? Here's my code:

@Override
public void onMyLocationChange(@Nullable Location location) {
    LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
    Log.e("MAP", location.getLatitude()+", "+location.getLongitude());
    mapView.addPolyline(new PolylineOptions()
            .width(60f)
            .color(Color.GREEN)
            .alpha(1f)
            .add(loc));
    mapView.addMarker(new MarkerOptions()
            .title("HERE")
            .position(loc));
}

Upvotes: 0

Views: 3186

Answers (2)

Aryo
Aryo

Reputation: 4508

One marker requires one LatLng point information only, therefore it's working perfectly. However, a line connects between two points or more, polyline connects two or more consecutive points. In your code, you only put one point, which is not enough to make even one (poly)line. You need to add more points to the PolylineOptions, like the following example:

ArrayList<LatLng> points = new ArrayList<>();

// add two or more different LatLng points
points.add(new LatLng(-7.955, 112.613));
points.add(new LatLng(-7.956, 112.616));
points.add(new LatLng(-7.958, 112.619));

// or add from other collections
for(TrackPoint trackPoint: this.trackPoints)
    points.add(new LatLng(trackPoint.latitude, trackPoint.longitude));

// create new PolylineOptions from all points
PolylineOptions polylineOptions = new PolylineOptions()
    .addAll(points)
    .color(Color.RED)
    .width(3f);

// add polyline to MapboxMap object
this.mapboxMap.addPolyline(polylineOptions);

Hope this helps.

Upvotes: 2

cammace
cammace

Reputation: 3168

I haven't tried your code but I believe what you are trying to accomplish is every time the location of the user changes, you want to extend a polyline from previous coordinate to new coordinate, resulting in a polyline that traces the users past movement. In this case, you have two problems.

First being that you are creating a new polyline every time the users locations changes rather then adding a new point to a polyline when onMyLocationChange() is called. fix this by creating the polyline initially in your onCreate() method or somewhere else in the activity lifecycle. Once you created the polyline assign it a name and make it global. Now every time the user location changes, just add a new point to the polyline.

Your second problem, which kind of relates to the first, is that you're only adding one point to your polyline, LatLng loc, rather then a list of points. Polylines need at least 2 points in order to be drawn, a beginning and end point. Change LatLng loc to a list and add to it the new location as the users location changes.

Hope this helps!

Upvotes: 4

Related Questions