I have such enum which I'd like to assign to the pins, so that depending on this enum value, the pin image is different:
typedef NS_ENUM(NSInteger, MyType) {
MyTypeUnknown = 0,
MyTypeOne,
MyTypeTwo,
};
I've got my layer for non-clustered pins:
MGLSymbolStyleLayer *markerLayer = [[MGLSymbolStyleLayer alloc] initWithIdentifier:@"markerLayerId" source:source];
markerLayer.predicate = [NSPredicate predicateWithFormat:@"cluster != YES"];
[style addLayer: markerLayer];
and I know I want to add various images based on type
of the pin. The only thing I'm sure about is that I need to add those images to the layer:
[style setImage:[UIImage imageNamed:@"img0"] forName:@"img0id"];
[style setImage:[UIImage imageNamed:@"img1"] forName:@"img1id"];
[style setImage:[UIImage imageNamed:@"img2"] forName:@"img2id"];
Now I should set the name, but I'm not sure how:
markerLayer.iconImageName = [NSExpression expressionForConstantValue:@"???"]; // or withFormat..?
I've overridden their class to add my custom properties:
@objc class MyPointFeature: MGLPointFeature {
@objc var type: MyType = .unknown
}
And I'm really lost how to switch on that type
property to set the image of the pin. Any help please?
Firstly we need to have a variable, which can be used for accessing the values. To make it most readable, let's create a variable for our needs (later, eg when selecting a pin) and the entry for MapBox needs at once:
@objc class MyPointFeature: MGLPointFeature {
@objc var type: MyType = .unknown {
didSet {
self.attributes = ["myType": MyPointFeature .staticTypeKey(dynamicType: type)]
}
}
// This is made without dynamic property name to string cast, because
// the values shouldn't be changed so easily and a developer without
// suspecting it's a key somewhere could accidentally create a bug
// PS. if you have swift-only code, you can make it in MyType enum
@objc static func staticTypeKey(dynamicType: MyType) -> String {
switch dynamicType {
case .one:
return "one"
case .two:
return "two"
default:
return "unknown"
}
}
}
Now we want to register image names to given keys:
[style setImage:[UIImage imageNamed:@"img0"] forName:@"img0Key"];
[style setImage:[UIImage imageNamed:@"img1"] forName:@"img1Key"];
[style setImage:[UIImage imageNamed:@"img2"] forName:@"img2Key"];
Finally, let's bind the image name keys with assigned previously attribute:
NSDictionary *typeIcons = @{[MyPointFeature staticTypeKeyWithDynamicType:MyTypeUnknown]: @"img0Key",
[MyPointFeature staticTypeKeyWithDynamicType:MyTypeOne]: @"img1Key",
[MyPointFeature staticTypeKeyWithDynamicType:MyTypeTwo]: @"img2Key"};
myLayer.iconImageName = [NSExpression expressionWithFormat:@"FUNCTION(%@, 'valueForKeyPath:', myType)", typeIcons];
Obviously, key names should be wrapped in some constants etc, but refactoring is left for the reader, that's the simplest working solution.