Abd Al Rahman Hamdan
Abd Al Rahman Hamdan

Reputation: 31

Drawing all possible Polylines between multiple google maps markers?

I have an Arraylist containing latitudes and longitudes (retrieved from sqlite database) which I am using to set markers on the map, I'm currently trying to draw all possible Polylines between those markers using this code:

for (int i = 0; i < list.size() - 1; i++) {
            LatLng src = list.get(i);
            LatLng dest = list.get(i + 1);

            // mMap is the Map Object
            Polyline line = CalRout.mMap.addPolyline(
                    new PolylineOptions().add(
                            new LatLng(src.latitude, src.longitude),
                            new LatLng(dest.latitude,dest.longitude)
                    ).width(3).color(color)
            );
        }

..but as you can see in the screenshot below I am not getting all possible Polylines.

Screenshot of result

I am thinking nested loop, but I am not sure how do I go about implementing it, help is much appreciated!

Upvotes: 0

Views: 480

Answers (2)

qwerty
qwerty

Reputation: 116

Your idea is correct. To implement nested loop, simply insert another loop inside original.

for (int i = 0; i < list.size() - 1; i++) {
    for (int j = 0; j < list.size() - 1; j++) {
        if (j != i) { // skip same point
            LatLng src = list.get(i);
            LatLng dest = list.get(j);

            // mMap is the Map Object
            Polyline line = CalRout.mMap.addPolyline(
                new PolylineOptions().add(
                    new LatLng(src.latitude, src.longitude),
                    new LatLng(dest.latitude,dest.longitude)
                    ).width(3).color(color)
            );
        }
    }
}

Upvotes: 0

antonio
antonio

Reputation: 18262

Random random = new Random();
for (LatLng positionI : list) {
    for (LatLng positionJ : list) {
        int color = Color.rgb(random.nextInt(255), random.nextInt(255), random.nextInt(255));
        if (positionI != positionJ) {
            Polyline line = CalRout.mMap.addPolyline(
                    new PolylineOptions().add(
                            positionI,
                            positionJ
                    ).width(3).color(color)
            );
        }
    }
}

Upvotes: 1

Related Questions