Sathya Baman
Sathya Baman

Reputation: 3515

Drawing polygons on google Map using array[] - Android

i am trying to draw a polygon on the Google map depending on the array list. first check for the array length then i manually add points to draw the polygon. the below code works fine.

since the .add(new LatLng(array[0].a, array[0].b)) is a single line statement i am unable to loop it.

Is there any way i can do this in a loop.

private void drawpolygon(DistanceInfo  array[]) {

    int lengh = array.length;
    if(lengh==2){
        mMap.addPolygon(new PolygonOptions()
            .add(new LatLng(9.6632139, 80.0133258))
        .add(new LatLng(array[0].a, array[0].b))
        .add(new LatLng(array[1].a, array[1].b))
       .fillColor(Color.GRAY)); 
    }
    else if(lengh==4){
        mMap.addPolygon(new PolygonOptions()

        .add(new LatLng(9.6632139, 80.0133258))
        .add(new LatLng(array[0].a, array[0].b))
        .add(new LatLng(array[1].a, array[1].b))
        .add(new LatLng(array[2].a, array[2].b))
        .add(new LatLng(array[3].a, array[3].b))
       .fillColor(Color.GRAY));
    }
}

Upvotes: 0

Views: 2178

Answers (1)

Unknownweirdo
Unknownweirdo

Reputation: 495

Try

private void drawpolygon(DistanceInfo  array[]) {

    int length = array.length;

    // Optional length checks. Modify yourself.
    if(length == 0) 
    {
       // Do whatever you like then get out. Do not run the following.
       return;
    }

    // We have a length of not 0 so...    
    PolygonOptions poly = new PolygonOptions();
    poly.fillColor(Color.GRAY);

    // Initial point
    poly.add(new LatLng(9.6632139, 80.0133258);

    // ... then the rest.
    for(int i = 0; i < length; i++)
    {
        poly.add(new LatLng(array[i].a, array[i].b));
    }

    // Done! Add to map.
    mMap.addPolygon(poly);
}

Note that this allows array[] to be of any length (except 0). Please add your own code for length checking :)

Upvotes: 4

Related Questions