diff --git a/gyp/platform-ios.gypi b/gyp/platform-ios.gypi index a8a827af657..cc436561fd3 100644 --- a/gyp/platform-ios.gypi +++ b/gyp/platform-ios.gypi @@ -18,6 +18,7 @@ '../platform/darwin/reachability.m', '../include/mbgl/ios/MGLMapView.h', '../platform/ios/MGLMapView.mm', + '../include/mbgl/ios/MGLAnnotation.h', '../include/mbgl/ios/MGLStyleFunctionValue.h', '../platform/ios/MGLStyleFunctionValue.m', '../include/mbgl/ios/MGLTypes.h', diff --git a/include/mbgl/ios/MGLAnnotation.h b/include/mbgl/ios/MGLAnnotation.h new file mode 100644 index 00000000000..e4907d9b943 --- /dev/null +++ b/include/mbgl/ios/MGLAnnotation.h @@ -0,0 +1,28 @@ +#import +#import + +/** The MGLAnnotation protocol is used to provide annotation-related information to a map view. To use this protocol, you adopt it in any custom objects that store or represent annotation data. Each object then serves as the source of information about a single map annotation and provides critical information, such as the annotation’s location on the map. Annotation objects do not provide the visual representation of the annotation but typically coordinate (in conjunction with the map view’s delegate) the creation of an appropriate objects to handle the display. +* +* An object that adopts this protocol must implement the `coordinate` property. The other methods of this protocol are optional. */ +@protocol MGLAnnotation + +/** @name Position Attributes */ + +/** The center point (specified as a map coordinate) of the annotation. (required) (read-only) */ +@property (nonatomic, readonly) CLLocationCoordinate2D coordinate; + +@optional + +/** @name Title Attributes */ + +/** The string containing the annotation’s title. +* +* Although this property is optional, if you support the selection of annotations in your map view, you are expected to provide this property. This string is displayed in the callout for the associated annotation. */ +@property (nonatomic, readonly, copy) NSString *title; + +/** The string containing the annotation’s subtitle. +* +* This string is displayed in the callout for the associated annotation. */ +@property (nonatomic, readonly, copy) NSString *subtitle; + +@end diff --git a/include/mbgl/ios/MGLMapView.h b/include/mbgl/ios/MGLMapView.h index 481e878edc7..3a6e622e12d 100644 --- a/include/mbgl/ios/MGLMapView.h +++ b/include/mbgl/ios/MGLMapView.h @@ -2,6 +2,7 @@ #import @protocol MGLMapViewDelegate; +@protocol MGLAnnotation; /** An MGLMapView object provides an embeddable map interface, similar to the one provided by Apple's MapKit. You use this class to display map information and to manipulate the map contents from your application. You can center the map on a given coordinate, specify the size of the area you want to display, and style the features of the map to fit your application's use case. * @@ -184,6 +185,55 @@ * @param styleName The map style name to use. */ - (void)useBundledStyleNamed:(NSString *)styleName; +#pragma mark - Annotating the Map + +/** @name Annotating the Map */ + +/** The complete list of annotations associated with the receiver. (read-only) +* +* The objects in this array must adopt the MGLAnnotation protocol. If no annotations are associated with the map view, the value of this property is `nil`. */ +@property (nonatomic, readonly) NSArray *annotations; + +/** Adds the specified annotation to the map view. +* @param annotation The annotation object to add to the receiver. This object must conform to the MGLAnnotation protocol. The map view retains the specified object. */ +- (void)addAnnotation:(id )annotation; + +/** Adds an array of annotation objects to the map view. +* @param annotations An array of annotation objects. Each object in the array must conform to the MGLAnnotation protocol. The map view retains the individual annotation objects. */ +- (void)addAnnotations:(NSArray *)annotations; + +/** Removes the specified annotation object from the map view. +* +* Removing an annotation object disassociates it from the map view entirely, preventing it from being displayed on the map. Thus, you would typically call this method only when you want to hide or delete a given annotation. +* +* @param annotation The annotation object to remove. This object must conform to the MGLAnnotation protocol. */ +- (void)removeAnnotation:(id )annotation; + +/** Removes an array of annotation objects from the map view. +* +* Removing annotation objects disassociates them from the map view entirely, preventing them from being displayed on the map. Thus, you would typically call this method only when you want to hide or delete the specified annotations. +* +* @param annotations The array of annotations to remove. Objects in the array must conform to the MGLAnnotation protocol. */ +- (void)removeAnnotations:(NSArray *)annotations; + +/** The annotations that are currently selected. +* +* Assigning a new array to this property selects only the first annotation in the array. */ +@property (nonatomic, copy) NSArray *selectedAnnotations; + +/** Selects the specified annotation and displays a callout view for it. +* +* If the specified annotation is not onscreen, this method has no effect. +* +* @param annotation The annotation object to select. +* @param animated If `YES`, the callout view is animated into position. */ +- (void)selectAnnotation:(id )annotation animated:(BOOL)animated; + +/** Deselects the specified annotation and hides its callout view. +* @param annotation The annotation object to deselect. +* @param animated If `YES`, the callout view is animated offscreen. */ +- (void)deselectAnnotation:(id )annotation animated:(BOOL)animated; + #pragma mark - Debugging /** @name Debugging */ @@ -201,11 +251,19 @@ @end -// TODO +/** The MGLMapViewDelegate protocol defines a set of optional methods that you can use to receive map-related update messages. Because many map operations require the MGLMapView class to load data asynchronously, the map view calls these methods to notify your application when specific operations complete. The map view also uses these methods to request annotation marker symbology and to manage interactions with those markers. */ @protocol MGLMapViewDelegate @optional +/** @name Managing the Display of Annotations */ + +/** Returns the style's symbol name to use for the marker for the specified point annotation object. +* @param mapView The map view that requested the annotation symbol name. +* @param annotation The object representing the annotation that is about to be displayed. +* @return The marker symbol to display for the specified annotation or `nil` if you want to display the default symbol. */ +- (NSString *)mapView:(MGLMapView *)mapView symbolNameForAnnotation:(id )annotation; + // Responding to Map Position Changes // TODO diff --git a/include/mbgl/util/geo.hpp b/include/mbgl/util/geo.hpp index b99a6e6614f..6ece6d4de91 100644 --- a/include/mbgl/util/geo.hpp +++ b/include/mbgl/util/geo.hpp @@ -32,6 +32,13 @@ struct LatLngBounds { if (point.longitude < sw.longitude) sw.longitude = point.longitude; if (point.longitude > ne.longitude) ne.longitude = point.longitude; } + + inline bool contains(const LatLng& point) { + return (point.latitude >= sw.latitude && + point.latitude <= ne.latitude && + point.longitude >= sw.longitude && + point.longitude <= ne.longitude); + } }; } diff --git a/ios/app/MBXViewController.mm b/ios/app/MBXViewController.mm index f0ad9e11539..e12964ac982 100644 --- a/ios/app/MBXViewController.mm +++ b/ios/app/MBXViewController.mm @@ -233,7 +233,7 @@ - (void)dealloc } } -#pragma mark - Location +#pragma mark - CLLocationManagerDelegate - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status { diff --git a/ios/docs/install_docs.sh b/ios/docs/install_docs.sh index 4d116c03328..cd6fcdda734 100755 --- a/ios/docs/install_docs.sh +++ b/ios/docs/install_docs.sh @@ -5,7 +5,7 @@ if [ -z `which appledoc` ]; then exit 1 fi -VERSION=$( git tag | sort -r | sed -n '1p' ) +VERSION=$( git tag | grep ^[0-9] | sort -r | sed -n '1p' ) echo "Creating new docs for $VERSION..." echo @@ -15,10 +15,4 @@ appledoc \ --project-company Mapbox \ --create-docset \ --company-id com.mapbox \ - --ignore app \ - --ignore dist \ - --ignore pkg \ - --ignore test \ - --ignore .m \ - --ignore .mm \ - . \ No newline at end of file + ../../include/mbgl/ios diff --git a/ios/docs/remove_docs.sh b/ios/docs/remove_docs.sh index bb8c008dc21..09e2c1d3996 100755 --- a/ios/docs/remove_docs.sh +++ b/ios/docs/remove_docs.sh @@ -4,4 +4,4 @@ echo echo "Removing docs from ~/Library/Developer/Shared/Documentation/DocSets..." echo -rm -rfv ~/Library/Developer/Shared/Documentation/DocSets/com.mapbox.Mapbox-GL-* \ No newline at end of file +rm -rfv ~/Library/Developer/Shared/Documentation/DocSets/com.mapbox.Mapbox-GL-* diff --git a/platform/ios/MGLMapView.mm b/platform/ios/MGLMapView.mm index 9b096315dd0..d61c4dad4f3 100644 --- a/platform/ios/MGLMapView.mm +++ b/platform/ios/MGLMapView.mm @@ -16,11 +16,13 @@ #import "MGLTypes.h" #import "MGLStyleFunctionValue.h" +#import "MGLAnnotation.h" #import "UIColor+MGLAdditions.h" #import "NSArray+MGLAdditions.h" #import "NSDictionary+MGLAdditions.h" +#import // Returns the path to the default cache database on this system. const std::string &defaultCacheDatabase() { @@ -39,6 +41,10 @@ static dispatch_once_t loadGLExtensions; +NSString *const MGLDefaultStyleName = @"Emerald"; +NSString *const MGLStyleVersion = @"v7"; +NSString *const MGLDefaultStyleMarkerSymbolName = @"default_marker"; + extern NSString *const MGLStyleKeyGeneric; extern NSString *const MGLStyleKeyFill; extern NSString *const MGLStyleKeyLine; @@ -52,6 +58,8 @@ NSTimeInterval const MGLAnimationDuration = 0.3; +NSString *const MGLAnnotationIDKey = @"MGLAnnotationIDKey"; + #pragma mark - Private - @interface MGLMapView () @@ -67,6 +75,9 @@ @interface MGLMapView () @property (nonatomic) UIRotationGestureRecognizer *rotate; @property (nonatomic) UILongPressGestureRecognizer *quickZoom; @property (nonatomic) NSMutableArray *bundledStyleNames; +@property (nonatomic) NSMapTable *annotationsStore; +@property (nonatomic) std::vector annotationsNearbyLastTap; +@property (nonatomic, weak) id selectedAnnotation; @property (nonatomic, readonly) NSDictionary *allowedStyleTypes; @property (nonatomic) CGPoint centerPoint; @property (nonatomic) CGFloat scale; @@ -175,7 +186,9 @@ - (void)setStyleJSON:(NSString *)styleJSON { if ( ! styleJSON) { - [self useBundledStyleNamed:@"emerald-v7"]; + [self useBundledStyleNamed:[[[MGLDefaultStyleName lowercaseString] + stringByAppendingString:@"-"] + stringByAppendingString:MGLStyleVersion]]; } else { @@ -266,6 +279,12 @@ - (BOOL)commonInit Reachability* reachability = [Reachability reachabilityForInternetConnection]; [reachability startNotifier]; + // setup annotations + // + _annotationsStore = [NSMapTable mapTableWithKeyOptions:NSMapTableStrongMemory valueOptions:NSMapTableStrongMemory]; + std::string defaultSymbolName([MGLDefaultStyleMarkerSymbolName cStringUsingEncoding:[NSString defaultCStringEncoding]]); + mbglMap->setDefaultPointAnnotationSymbol(defaultSymbolName); + // setup logo bug // _logoBug = [[UIImageView alloc] initWithImage:[MGLMapView resourceImageNamed:@"mapbox.png"]]; @@ -319,6 +338,10 @@ - (BOOL)commonInit doubleTap.numberOfTapsRequired = 2; [self addGestureRecognizer:doubleTap]; + UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTapGesture:)]; + [singleTap requireGestureRecognizerToFail:doubleTap]; + [self addGestureRecognizer:singleTap]; + UITapGestureRecognizer *twoFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTwoFingerTapGesture:)]; twoFingerTap.numberOfTouchesRequired = 2; [twoFingerTap requireGestureRecognizerToFail:_pinch]; @@ -684,6 +707,118 @@ - (void)handleRotateGesture:(UIRotationGestureRecognizer *)rotate } } +- (void)handleSingleTapGesture:(UITapGestureRecognizer *)singleTap +{ + CGPoint tapPoint = [singleTap locationInView:self]; + + // tolerances based on touch size & typical marker aspect ratio + CGFloat toleranceWidth = 50; + CGFloat toleranceHeight = 75; + + // setup a recognition area weighted 2/3 of the way above the point to account for average marker imagery + CGRect tapRect = CGRectMake(tapPoint.x - toleranceWidth / 2, tapPoint.y - 2 * toleranceHeight / 3, toleranceWidth, toleranceHeight); + CGPoint tapRectLowerLeft = CGPointMake(tapRect.origin.x, tapRect.origin.y + tapRect.size.height); + CGPoint tapRectUpperLeft = CGPointMake(tapRect.origin.x, tapRect.origin.y); + CGPoint tapRectUpperRight = CGPointMake(tapRect.origin.x + tapRect.size.width, tapRect.origin.y); + CGPoint tapRectLowerRight = CGPointMake(tapRect.origin.x + tapRect.size.width, tapRect.origin.y + tapRect.size.height); + + // figure out what that means in coordinate space + CLLocationCoordinate2D coordinate; + mbgl::LatLngBounds tapBounds; + + coordinate = [self convertPoint:tapRectLowerLeft toCoordinateFromView:self]; + tapBounds.extend(mbgl::LatLng(coordinate.latitude, coordinate.longitude)); + + coordinate = [self convertPoint:tapRectUpperLeft toCoordinateFromView:self]; + tapBounds.extend(mbgl::LatLng(coordinate.latitude, coordinate.longitude)); + + coordinate = [self convertPoint:tapRectUpperRight toCoordinateFromView:self]; + tapBounds.extend(mbgl::LatLng(coordinate.latitude, coordinate.longitude)); + + coordinate = [self convertPoint:tapRectLowerRight toCoordinateFromView:self]; + tapBounds.extend(mbgl::LatLng(coordinate.latitude, coordinate.longitude)); + + // query for nearby annotations + std::vector nearbyAnnotations = mbglMap->getAnnotationsInBounds(tapBounds); + + int32_t newSelectedAnnotationID = -1; + + if (nearbyAnnotations.size()) + { + // there is at least one nearby annotation; select one + // + // first, sort for comparison and iteration + std::sort(nearbyAnnotations.begin(), nearbyAnnotations.end()); + + if (nearbyAnnotations == self.annotationsNearbyLastTap) + { + // the selection candidates haven't changed; cycle through them + if (self.selectedAnnotation && + [[[self.annotationsStore objectForKey:self.selectedAnnotation] + objectForKey:MGLAnnotationIDKey] unsignedIntValue] == self.annotationsNearbyLastTap.back()) + { + // the selected annotation is the last in the set; cycle back to the first + // note: this could be the selected annotation if only one in set + newSelectedAnnotationID = self.annotationsNearbyLastTap.front(); + } + else if (self.selectedAnnotation) + { + // otherwise increment the selection through the candidates + uint32_t currentID = [[[self.annotationsStore objectForKey:self.selectedAnnotation] objectForKey:MGLAnnotationIDKey] unsignedIntValue]; + auto result = std::find(self.annotationsNearbyLastTap.begin(), self.annotationsNearbyLastTap.end(), currentID); + auto distance = std::distance(self.annotationsNearbyLastTap.begin(), result); + newSelectedAnnotationID = self.annotationsNearbyLastTap[distance + 1]; + } + else + { + // no current selection; select the first one + newSelectedAnnotationID = self.annotationsNearbyLastTap.front(); + } + } + else + { + // start tracking a new set of nearby annotations + self.annotationsNearbyLastTap = nearbyAnnotations; + + // select the first one + newSelectedAnnotationID = self.annotationsNearbyLastTap.front(); + } + } + else + { + // there are no nearby annotations; deselect if necessary + newSelectedAnnotationID = -1; + } + + if (newSelectedAnnotationID >= 0) + { + // find & select model object for selection + NSEnumerator *enumerator = self.annotationsStore.keyEnumerator; + + while (id annotation = enumerator.nextObject) + { + if ([[[self.annotationsStore objectForKey:annotation] objectForKey:MGLAnnotationIDKey] integerValue] == newSelectedAnnotationID) + { + // only change selection status if not the currently selected annotation + if ( ! [annotation isEqual:self.selectedAnnotation]) + { + [self selectAnnotation:annotation animated:YES]; + } + + // either way, we should stop enumerating + break; + } + } + } + else + { + // deselect any selected annotation + if (self.selectedAnnotation) [self deselectAnnotation:self.selectedAnnotation animated:YES]; + } + + NSLog(@"%i (%@)", newSelectedAnnotationID, self.selectedAnnotation.title); +} + - (void)handleDoubleTapGesture:(UITapGestureRecognizer *)doubleTap { if ( ! self.isZoomEnabled) return; @@ -840,7 +975,7 @@ - (void)setCenterCoordinate:(CLLocationCoordinate2D)coordinate animated:(BOOL)an { CGFloat duration = (animated ? MGLAnimationDuration : 0); - mbglMap->setLatLng(mbgl::LatLng(coordinate.latitude, coordinate.longitude), secondsAsDuration(duration)); + mbglMap->setLatLng(coordinateToLatLng(coordinate), secondsAsDuration(duration)); } - (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate @@ -850,16 +985,14 @@ - (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate - (CLLocationCoordinate2D)centerCoordinate { - mbgl::LatLng latLng = mbglMap->getLatLng(); - - return CLLocationCoordinate2DMake(latLng.latitude, latLng.longitude); + return latLngToCoordinate(mbglMap->getLatLng()); } - (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate zoomLevel:(double)zoomLevel animated:(BOOL)animated { CGFloat duration = (animated ? MGLAnimationDuration : 0); - mbglMap->setLatLngZoom(mbgl::LatLng(centerCoordinate.latitude, centerCoordinate.longitude), zoomLevel, secondsAsDuration(duration)); + mbglMap->setLatLngZoom(coordinateToLatLng(centerCoordinate), zoomLevel, secondsAsDuration(duration)); [self unrotateIfNeededAnimated:animated]; } @@ -915,9 +1048,7 @@ - (CLLocationCoordinate2D)convertPoint:(CGPoint)point toCoordinateFromView:(UIVi // convertedPoint.y = self.bounds.size.height - convertedPoint.y; - mbgl::LatLng latLng = mbglMap->latLngForPixel(mbgl::vec2(convertedPoint.x, convertedPoint.y)); - - return CLLocationCoordinate2DMake(latLng.latitude, latLng.longitude); + return latLngToCoordinate(mbglMap->latLngForPixel(mbgl::vec2(convertedPoint.x, convertedPoint.y))); } - (CGPoint)convertCoordinate:(CLLocationCoordinate2D)coordinate toPointToView:(UIView *)view @@ -936,6 +1067,32 @@ - (CLLocationDistance)metersPerPixelAtLatitude:(CLLocationDegrees)latitude return mbglMap->getMetersPerPixelAtLatitude(latitude, self.zoomLevel); } +mbgl::LatLng coordinateToLatLng(CLLocationCoordinate2D coordinate) +{ + return mbgl::LatLng(coordinate.latitude, coordinate.longitude); +} + +CLLocationCoordinate2D latLngToCoordinate(mbgl::LatLng latLng) +{ + return CLLocationCoordinate2DMake(latLng.latitude, latLng.longitude); +} + +- (mbgl::LatLngBounds)viewportBounds +{ + mbgl::LatLngBounds bounds; + + bounds.extend(coordinateToLatLng( + [self convertPoint:CGPointMake(0, 0) toCoordinateFromView:self])); + bounds.extend(coordinateToLatLng( + [self convertPoint:CGPointMake(self.bounds.size.width, 0) toCoordinateFromView:self])); + bounds.extend(coordinateToLatLng( + [self convertPoint:CGPointMake(0, self.bounds.size.height) toCoordinateFromView:self])); + bounds.extend(coordinateToLatLng( + [self convertPoint:CGPointMake(self.bounds.size.width, self.bounds.size.height) toCoordinateFromView:self])); + + return bounds; +} + #pragma mark - Styling - - (NSDictionary *)getRawStyle @@ -1395,6 +1552,122 @@ - (NSDictionary *)allowedStyleTypes return MGLStyleAllowedTypes; } +#pragma mark - Annotations - + +- (NSArray *)annotations +{ + if ([_annotationsStore count]) + { + NSMutableArray *result = [NSMutableArray array]; + + NSEnumerator *keyEnumerator = [_annotationsStore keyEnumerator]; + id annotation; + + while (annotation = [keyEnumerator nextObject]) + { + [result addObject:annotation]; + } + + return [NSArray arrayWithArray:result]; + } + + return nil; +} + +- (void)addAnnotation:(id )annotation +{ + // The core bulk add API is efficient with respect to indexing and + // screen refreshes, thus we should defer to it even for individual adds. + // + [self addAnnotations:@[ annotation ]]; +} + +- (void)addAnnotations:(NSArray *)annotations +{ + std::vector latLngs; + latLngs.reserve(annotations.count); + + std::vector symbols; + symbols.reserve(annotations.count); + + BOOL delegateImplementsSymbolLookup = [self.delegate respondsToSelector:@selector(mapView:symbolNameForAnnotation:)]; + + for (id annotation in annotations) + { + latLngs.push_back(coordinateToLatLng(annotation.coordinate)); + + NSString *symbolName = nil; + + if (delegateImplementsSymbolLookup) + { + symbolName = [self.delegate mapView:self symbolNameForAnnotation:annotation]; + } + + symbols.push_back((symbolName ? [symbolName cStringUsingEncoding:[NSString defaultCStringEncoding]] : "")); + } + + std::vector annotationIDs = mbglMap->addPointAnnotations(latLngs, symbols); + + for (size_t i = 0; i < annotationIDs.size(); ++i) + { + [self.annotationsStore setObject:@{ MGLAnnotationIDKey : @(annotationIDs[i]) } + forKey:annotations[i]]; + } +} + +- (void)removeAnnotation:(id )annotation +{ + // The core bulk deletion API is efficient with respect to indexing + // and screen refreshes, thus we should defer to it even for + // individual deletes. + // + [self removeAnnotations:@[ annotation ]]; +} + +- (void)removeAnnotations:(NSArray *)annotations +{ + std::vector annotationIDsToRemove; + annotationIDsToRemove.reserve(annotations.count); + + for (id annotation in annotations) + { + annotationIDsToRemove.push_back([[self.annotationsStore objectForKey:annotation] unsignedIntValue]); + [self.annotationsStore removeObjectForKey:annotation]; + } + + mbglMap->removeAnnotations(annotationIDsToRemove); +} + +- (NSArray *)selectedAnnotations +{ + return @[ self.selectedAnnotation ]; +} + +- (void)setSelectedAnnotations:(NSArray *)selectedAnnotations +{ + id firstAnnotation = selectedAnnotations[0]; + + if ( ! [self viewportBounds].contains(coordinateToLatLng(firstAnnotation.coordinate))) return; + + self.selectedAnnotation = firstAnnotation; +} + +- (void)selectAnnotation:(id )annotation animated:(BOOL)animated +{ + (void)animated; + + if ( ! [self viewportBounds].contains(coordinateToLatLng(annotation.coordinate))) return; + + self.selectedAnnotation = annotation; +} + +- (void)deselectAnnotation:(id )annotation animated:(BOOL)animated +{ + (void)animated; + + if ([self.selectedAnnotation isEqual:annotation]) self.selectedAnnotation = nil; +} + #pragma mark - Utility - + (CGFloat)degreesToRadians:(CGFloat)degrees diff --git a/src/mbgl/map/annotation.cpp b/src/mbgl/map/annotation.cpp index 0d6da5781ec..83739ab46a6 100644 --- a/src/mbgl/map/annotation.cpp +++ b/src/mbgl/map/annotation.cpp @@ -40,7 +40,9 @@ std::pair, std::vector> AnnotationManager::addPo uint16_t extent = 4096; - std::vector annotationIDs(points.size()); + std::vector annotationIDs; + annotationIDs.reserve(points.size()); + std::vector affectedTiles; for (uint32_t i = 0; i < points.size(); ++i) {