iPhone - MapKit : How may I customize the color and alpha of an overlay on the fly?
I have a MapView onto which I put some overlays (MKPolygon).
I have to maintain groups of MKPolygon.For this, I have a PolyGonGroupClass that keeps each poly and the color and alpha that should be used to display all these polygons.
So, each time I find a poly, I add it as a map overlay and memorize in into the correct group of polys.
All my groups of poly are kepts into an instance var.[self.mapView addOverlay:poly];
[thecorrectpolygroup addObj开发者_如何学编程ect:poly];
...
[self.mypolygroups addObject:thecorrectpolygroup];
@interface PolyGonGroupClass : NSObject {
UIColor* __color;
float __alpha;
NSMutableArray* __polygons;
}
Well...
At this point, how may I tell to the MapView the color and alpha of each poly and update them on the fly when one of these color change ?
I found a - (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
method, but I don't see how I may use it to retrieve the values I put into the memorised values.
I guess I should use the overlay parameter, but how may I retrieve the correct group of poly that correspond to that overlay ?
In viewForOverlay
, you can loop through your mypolygroups
array and check if the overlay is in that group's polygons
array:
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
if ([overlay isKindOfClass:[MKPolygon class]])
{
MKPolygonView *pv = [[[MKPolygonView alloc] initWithPolygon:overlay] autorelease];
for (PolyGonGroupClass *pgc in mypolygroups)
{
if ([pgc.polygons containsObject:overlay])
{
pv.fillColor = pgc.color;
pv.alpha = pgc.alpha;
break;
}
}
return pv;
}
return nil;
}
However, for this to work right, you'll have to slightly change where you call addOverlay
. In the code you've shown, you are calling addOverlay
before adding it to the polygons array and before adding the group to the mypolygroups array. This can cause viewForOverlay
to fire before the arrays contain data.
Instead, move just the addOverlay
calls to after the mypolygroups
array is fully populated. So after adding the last group to mypolygroups
:
...
[self.mypolygroups addObject:theLastPolygroup];
for (PolyGonGroupClass *pgc in mypolygroups)
{
for (MKPolygon *p in pgc.polygons)
{
[mapView addOverlay:p];
}
}
Finally, to update a group's color and alpha later after it's already on the map, you can do something like this:
//pgc is some instance of PolyGonGroupClass
pgc.alpha = newAlpha;
pgc.color = newColor;
for (MKPolygon *p in pgc.polygons)
{
MKPolygonView *pv = (MKPolygonView *)[mapView viewForOverlay:p];
pv.alpha = pgc.alpha;
pv.fillColor = pgc.color;
}
精彩评论