diff --git a/.gitmodules b/.gitmodules index 19de5b6f7..9e5265a6a 100644 --- a/.gitmodules +++ b/.gitmodules @@ -13,3 +13,7 @@ [submodule "test/ios/KIF"] path = test/ios/KIF url = https://github.com/mapbox/KIF.git + +[submodule "platform/ios/vendor/SMCalloutView"] + path = platform/ios/vendor/SMCalloutView + url = https://github.com/nfarina/calloutview.git diff --git a/LICENSE.md b/LICENSE.md index 845f31169..e5ed29c9a 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -22,3 +22,34 @@ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=========================================================================== + +Mapbox GL uses portions of the Mapbox iOS SDK, which was derived from the +Route-Me open source project, including the Alpstein fork of it. + +The Route-Me license appears below. + +Copyright (c) 2008-2013, Route-Me Contributors +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/Makefile b/Makefile index 33135ae96..4c830fd83 100644 --- a/Makefile +++ b/Makefile @@ -25,10 +25,13 @@ config/%.gypi: configure styles/styles: git submodule update --init styles +SMCalloutView: + git submodule update --init platform/ios/vendor/SMCalloutView + #### Library builds ############################################################ .PRECIOUS: Makefile/mbgl -Makefile/mbgl: config/$(HOST).gypi styles/styles +Makefile/mbgl: config/$(HOST).gypi styles/styles SMCalloutView deps/run_gyp mbgl.gyp $(CONFIG_$(HOST)) $(LIBS_$(HOST)) --generator-output=./build/$(HOST) -f make mbgl: Makefile/mbgl @@ -41,13 +44,13 @@ install: Makefile/mbgl LINK=`pwd`/gyp/link.py $(MAKE) -C build/$(HOST) BUILDTYPE=$(BUILDTYPE) install .PRECIOUS: Xcode/mbgl -Xcode/mbgl: config/$(HOST).gypi styles/styles +Xcode/mbgl: config/$(HOST).gypi styles/styles SMCalloutView deps/run_gyp mbgl.gyp $(CONFIG_$(HOST)) $(LIBS_$(HOST)) --generator-output=./build/$(HOST) -f xcode ##### Test builds ############################################################## .PRECIOUS: Makefile/test -Makefile/test: test/test.gyp config/$(HOST).gypi styles/styles +Makefile/test: test/test.gyp config/$(HOST).gypi styles/styles SMCalloutView deps/run_gyp test/test.gyp $(CONFIG_$(HOST)) $(LIBS_$(HOST)) --generator-output=./build/$(HOST) -f make test: Makefile/test @@ -58,7 +61,7 @@ test-%: test .PRECIOUS: Xcode/test -Xcode/test: test/test.gyp config/osx.gypi styles/styles +Xcode/test: test/test.gyp config/osx.gypi styles/styles SMCalloutView deps/run_gyp test/test.gyp $(CONFIG_osx) $(LIBS_osx) --generator-output=./build/osx -f xcode .PHONY: lproj lbuild run-xlinux @@ -108,7 +111,7 @@ xproj: xosx-proj #### iOS application builds #################################################### .PRECIOUS: Xcode/ios -Xcode/ios: ios/app/mapboxgl-app.gyp config/ios.gypi styles/styles +Xcode/ios: ios/app/mapboxgl-app.gyp config/ios.gypi styles/styles SMCalloutView deps/run_gyp ios/app/mapboxgl-app.gyp $(CONFIG_ios) $(LIBS_ios) --generator-output=./build/ios -f xcode .PHONY: ios-proj ios run-ios diff --git a/README.md b/README.md index 09759d84e..f48a72b99 100644 --- a/README.md +++ b/README.md @@ -55,9 +55,11 @@ If you merely want to install the library for iOS and try it out as an Objective - `MapboxGL.bundle` is in your target's *Copy Bundle Resources* build phase. - `libMapboxGL.a` is in your target's *Link Binary With Libraries* build phase. 3. Add the following Cocoa framework dependencies to your target's *Link Binary With Libraries* build phase: + - `CoreTelephony.framework` - `GLKit.framework` - `ImageIO.framework` - `MobileCoreServices.framework` + - `QuartzCore.framework` - `SystemConfiguration.framework` - `libc++.dylib` - `libsqlite3.dylib` diff --git a/android/cpp/jni.cpp b/android/cpp/jni.cpp index 9cde5d385..ce61a01bf 100644 --- a/android/cpp/jni.cpp +++ b/android/cpp/jni.cpp @@ -160,7 +160,7 @@ jobject std_vector_string_to_jobject(JNIEnv *env, std::vector vecto return nullptr; } - for (std::string str : vector) { + for (const auto& str : vector) { env->CallBooleanMethod(jlist, arrayListAddId, std_string_to_jstring(env, str)); if (env->ExceptionCheck()) { env->ExceptionDescribe(); diff --git a/gyp/platform-ios.gypi b/gyp/platform-ios.gypi index 73f611a8e..9965db57a 100644 --- a/gyp/platform-ios.gypi +++ b/gyp/platform-ios.gypi @@ -22,18 +22,16 @@ '../include/mbgl/ios/MGLMapView.h', '../platform/ios/MGLMapView.mm', '../include/mbgl/ios/MGLAnnotation.h', + '../include/mbgl/ios/MGLUserLocation.h', + '../platform/ios/MGLUserLocation_Private.h', + '../platform/ios/MGLUserLocation.m', + '../platform/ios/MGLUserLocationAnnotationView.h', + '../platform/ios/MGLUserLocationAnnotationView.m', '../include/mbgl/ios/MGLMetricsLocationManager.h', '../platform/ios/MGLMetricsLocationManager.m', - '../include/mbgl/ios/MGLStyleFunctionValue.h', - '../platform/ios/MGLStyleFunctionValue.m', '../include/mbgl/ios/MGLTypes.h', - '../platform/ios/MGLTypes.m', - '../include/mbgl/ios/NSArray+MGLAdditions.h', - '../platform/ios/NSArray+MGLAdditions.m', - '../include/mbgl/ios/NSDictionary+MGLAdditions.h', - '../platform/ios/NSDictionary+MGLAdditions.m', - '../include/mbgl/ios/UIColor+MGLAdditions.h', - '../platform/ios/UIColor+MGLAdditions.m', + '../platform/ios/vendor/SMCalloutView/SMCalloutView.h', + '../platform/ios/vendor/SMCalloutView/SMCalloutView.m', ], 'variables': { @@ -45,15 +43,13 @@ '<@(uv_static_libs)', ], 'ldflags': [ - '-framework CoreGraphics', '-framework CoreLocation', '-framework CoreTelephony', - '-framework ImageIO', '-framework GLKit', + '-framework ImageIO', '-framework MobileCoreServices', - '-framework OpenGLES', + '-framework QuartzCore', '-framework SystemConfiguration', - '-framework UIKit', ], }, @@ -64,6 +60,7 @@ 'xcode_settings': { 'OTHER_CPLUSPLUSFLAGS': [ '<@(cflags_cc)' ], 'CLANG_ENABLE_OBJC_ARC': 'YES', + 'CLANG_ENABLE_MODULES': 'YES', }, 'link_settings': { diff --git a/gyp/platform-osx.gypi b/gyp/platform-osx.gypi index 39e18bb83..aecb05859 100644 --- a/gyp/platform-osx.gypi +++ b/gyp/platform-osx.gypi @@ -26,7 +26,6 @@ '<@(uv_static_libs)', ], 'ldflags': [ - '-framework Foundation', '-framework ImageIO', '-framework CoreServices', '-framework OpenGL', @@ -42,6 +41,7 @@ 'xcode_settings': { 'OTHER_CPLUSPLUSFLAGS': [ '<@(cflags_cc)' ], 'CLANG_ENABLE_OBJC_ARC': 'YES', + 'CLANG_ENABLE_MODULES': 'YES', }, 'link_settings': { diff --git a/include/mbgl/ios/MGLMapView.h b/include/mbgl/ios/MGLMapView.h index 3a6e622e1..bacef9d33 100644 --- a/include/mbgl/ios/MGLMapView.h +++ b/include/mbgl/ios/MGLMapView.h @@ -1,6 +1,10 @@ +#import "MGLTypes.h" + #import #import +@class MGLUserLocation; + @protocol MGLMapViewDelegate; @protocol MGLAnnotation; @@ -29,6 +33,13 @@ * @return An initialized map view, or `nil` if the map view was unable to be initialized. */ - (instancetype)initWithFrame:(CGRect)frame accessToken:(NSString *)accessToken bundledStyleNamed:(NSString *)styleName; +/** Initialize a map view with a given frame, style URL, and access token. +* @param frame The frame with which to initialize the map view. +* @param accessToken A Mapbox API access token. +* @param styleURL The map style URL to use. Can be either an HTTP/HTTPS URL or a Mapbox map ID style URL (`mapbox://`). +* @return An initialized map view, or `nil` if the map view was unable to be initialized. */ +- (instancetype)initWithFrame:(CGRect)frame accessToken:(NSString *)accessToken styleURL:(NSURL *)styleURL; + /** Initialize a map view with a given frame, the default style, and an access token. * @param frame The frame with which to initialize the map view. * @param accessToken A Mapbox API access token. @@ -185,6 +196,10 @@ * @param styleName The map style name to use. */ - (void)useBundledStyleNamed:(NSString *)styleName; +/** Sets the map style URL to use. +* @param styleURL The map style URL to use. Can be either an HTTP/HTTPS URL or a Mapbox map ID style URL (`mapbox://`). */ +- (void)setStyleURL:(NSURL *)styleURL; + #pragma mark - Annotating the Map /** @name Annotating the Map */ @@ -234,6 +249,30 @@ * @param animated If `YES`, the callout view is animated offscreen. */ - (void)deselectAnnotation:(id )annotation animated:(BOOL)animated; +#pragma mark - Displaying the User's Location + +/** A Boolean value indicating whether the map may display the user location. + + This property does not indicate whether the user’s position is actually visible on the map, only whether the map view is allowed to display it. To determine whether the user’s position is visible, use the userLocationVisible property. The default value of this property is `NO`. + + Setting this property to `YES` causes the map view to use the Core Location framework to find the current location. As long as this property is `YES`, the map view continues to track the user’s location and update it periodically. + + On iOS 8 and above, your app must specify a value for `NSLocationWhenInUseUsageDescription` in its `Info.plist` to satisfy the requirements of the underlying Core Location framework when enabling this property. + */ +@property (nonatomic, assign) BOOL showsUserLocation; + +/// Returns a Boolean value indicating whether the user currently sees the user location annotation. +@property (nonatomic, assign, readonly, getter=isUserLocationVisible) BOOL userLocationVisible; + +/// Returns the annotation object indicating the user’s current location. +@property (nonatomic, readonly) MGLUserLocation *userLocation; + +/** The mode used to track the user location. */ +@property (nonatomic, assign) MGLUserTrackingMode userTrackingMode; + +/** Whether the map view should display a heading calibration alert when necessary. The default value is `YES`. */ +@property (nonatomic, assign) BOOL displayHeadingCalibration; + #pragma mark - Debugging /** @name Debugging */ @@ -251,11 +290,15 @@ @end +#pragma mark - MGLMapViewDelegate + /** 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 +#pragma mark - Managing the Display of Annotations + /** @name Managing the Display of Annotations */ /** Returns the style's symbol name to use for the marker for the specified point annotation object. @@ -264,14 +307,54 @@ * @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; +/** Returns a Boolean value indicating whether the annotation is able to display extra information in a callout bubble. +* +* If the value returned is `YES`, a standard callout bubble is shown when the user taps a selected annotation. The callout uses the title and subtitle text from the associated annotation object. If there is no title text, though, the annotation will not show a callout. The callout also displays any custom callout views returned by the delegate for the left and right callout accessory views. +* +* If the value returned is `NO`, the value of the title and subtitle strings are ignored. +* +* @param mapView The map view that requested the annotation callout ability. +* @param annotation The object representing the annotation. +* @return A Boolean indicating whether the annotation should show a callout. */ +- (BOOL)mapView:(MGLMapView *)mapView annotationCanShowCallout:(id )annotation; + +/** Return the view to display on the left side of the standard callout bubble. +* +* The default value is treated as if `nil`. The left callout view is typically used to display information about the annotation or to link to custom information provided by your application. +* +* If the view you specify is also a descendant of the `UIControl` class, you can use the map view’s delegate to receive notifications when your control is tapped. If it does not descend from `UIControl`, your view is responsible for handling any touch events within its bounds. +* +* @param mapView The map view presenting the annotation callout. +* @param annotation The object representing the annotation with the callout. +* @return The accessory view to display. */ +- (UIView *)mapView:(MGLMapView *)mapView leftCalloutAccessoryViewForAnnotation:(id )annotation; + +/** Return the view to display on the right side of the standard callout bubble. +* +* The default value is treated is if `nil`. The right callout view is typically used to link to more detailed information about the annotation. A common view to specify for this property is `UIButton` object whose type is set to `UIButtonTypeDetailDisclosure`. +* +* If the view you specify is also a descendant of the `UIControl` class, you can use the map view’s delegate to receive notifications when your control is tapped. If it does not descend from `UIControl`, your view is responsible for handling any touch events within its bounds. +* +* @param mapView The map view presenting the annotation callout. +* @param annotation The object representing the annotation with the callout. +* @return The accessory view to display. */ +- (UIView *)mapView:(MGLMapView *)mapView rightCalloutAccessoryViewForAnnotation:(id )annotation; + +#pragma mark - Responding to Map Position Changes + // Responding to Map Position Changes // TODO - (void)mapView:(MGLMapView *)mapView regionWillChangeAnimated:(BOOL)animated; +// TODO +- (void)mapViewRegionIsChanging:(MGLMapView *)mapView; + // TODO - (void)mapView:(MGLMapView *)mapView regionDidChangeAnimated:(BOOL)animated; +#pragma mark - Loading the Map Data + // Loading the Map Data // TODO @@ -289,4 +372,60 @@ // TODO - (void)mapViewDidFinishRenderingMap:(MGLMapView *)mapView fullyRendered:(BOOL)fullyRendered; +#pragma mark - Tracking the User Location + +/// Tells the delegate that the map view will begin tracking the user’s location. +- (void)mapViewWillStartLocatingUser:(MGLMapView *)mapView; + +/// Tells the delegate that the map view has stopped tracking the user’s location. +- (void)mapViewDidStopLocatingUser:(MGLMapView *)mapView; + +/// Tells the delegate that the map view has updated the user’s location to the given location. +- (void)mapView:(MGLMapView *)mapView didUpdateUserLocation:(MGLUserLocation *)userLocation; + +/// Tells the delegate that the map view has failed to locate the user. +- (void)mapView:(MGLMapView *)mapView didFailToLocateUserWithError:(NSError *)error; + +/** + Tells the delegate that the map view’s user tracking mode has changed. + + This method is called after the map view asynchronously changes to reflect the new user tracking mode, for example by beginning to zoom or rotate. + */ +- (void)mapView:(MGLMapView *)mapView didChangeUserTrackingMode:(MGLUserTrackingMode)mode animated:(BOOL)animated; + +#pragma mark - Managing Annotations + +/** @name Managing Annotations */ + +/* Tells the delegate that the user tapped one of the annotation's accessory buttons. +* +* Accessory views contain custom content and are positioned on either side of the annotation title text. If a view you specify is a descendant of the `UIControl` class, the map view calls this method as a convenience whenever the user taps your view. You can use this method to respond to taps and perform any actions associated with that control. For example, if your control displayed additional information about the annotation, you could use this method to present a modal panel with that information. +* +* If your custom accessory views are not descendants of the `UIControl` class, the map view does not call this method. +* +* @param mapView The map view containing the specified annotation. +* @param annotation The annotation whose button was tapped. +* @param control The control that was tapped. */ +- (void)mapView:(MGLMapView *)mapView annotation:(id )annotation calloutAccessoryControlTapped:(UIControl *)control; + +#pragma mark - Selecting Annotations + +/** @name Selecting Annotations */ + +/* Tells the delegate that one of its annotations was selected. +* +* You can use this method to track changes in the selection state of annotations. +* +* @param mapView The map view containing the annotation. +* @param annotation The annotation that was selected. */ +- (void)mapView:(MGLMapView *)mapView didSelectAnnotation:(id )annotation; + +/* Tells the delegate that one of its annotations was deselected. +* +* You can use this method to track changes in the selection state of annotations. +* +* @param mapView The map view containing the annotation. +* @param annotation The annotation that was deselected. */ +- (void)mapView:(MGLMapView *)mapView didDeselectAnnotation:(id )annotation; + @end diff --git a/include/mbgl/ios/MGLMapboxEvents.h b/include/mbgl/ios/MGLMapboxEvents.h index bb28ec26c..ea37edbb8 100644 --- a/include/mbgl/ios/MGLMapboxEvents.h +++ b/include/mbgl/ios/MGLMapboxEvents.h @@ -1,26 +1,50 @@ -// -// MapboxEvents.h -// MapboxEvents -// -// Created by Brad Leege on 3/5/15. -// Copyright (c) 2015 Mapbox. All rights reserved. -// - #import +extern NSString *const MGLEventTypeMapLoad; +extern NSString *const MGLEventTypeMapTap; +extern NSString *const MGLEventTypeMapDragEnd; +extern NSString *const MGLEventTypeLocation; + +extern NSString *const MGLEventKeyLatitude; +extern NSString *const MGLEventKeyLongitude; +extern NSString *const MGLEventKeyZoomLevel; +extern NSString *const MGLEventKeyPushEnabled; +extern NSString *const MGLEventKeyEmailEnabled; +extern NSString *const MGLEventKeyGestureID; + +extern NSString *const MGLEventGestureSingleTap; +extern NSString *const MGLEventGestureDoubleTap; +extern NSString *const MGLEventGestureTwoFingerSingleTap; +extern NSString *const MGLEventGestureQuickZoom; +extern NSString *const MGLEventGesturePanStart; +extern NSString *const MGLEventGesturePinchStart; +extern NSString *const MGLEventGestureRotateStart; + @interface MGLMapboxEvents : NSObject -@property (atomic) NSInteger flushAt; -@property (atomic) NSInteger flushAfter; -@property (atomic) NSString *api; -@property (atomic) NSString *token; -@property (atomic) NSString *appName; -@property (atomic) NSString *appVersion; +// You must call these methods from the main thread. +// ++ (void) setToken:(NSString *)token; ++ (void) setAppName:(NSString *)appName; ++ (void) setAppVersion:(NSString *)appVersion; -+ (id)sharedManager; +// You can call this method from any thread. Significant work will +// be dispatched to a low-priority background queue and all +// resulting calls are guaranteed threadsafe. +// +// Events or attributes passed could be accessed on non-main threads, +// so you must not reference UI elements from within any arguments. +// Copy any values needed first or create dedicated methods in this +// class for threadsafe access to UIKit classes. +// ++ (void) pushEvent:(NSString *)event withAttributes:(NSDictionary *)attributeDictionary; -- (void) pushEvent:(NSString *)event withAttributes:(NSDictionary *)attributeDictionary; +// You can call these methods from any thread. +// ++ (BOOL) checkPushEnabled; -- (void) flush; +// You can call this method from any thread. +// ++ (void) flush; -@end \ No newline at end of file +@end diff --git a/include/mbgl/ios/MGLMetricsLocationManager.h b/include/mbgl/ios/MGLMetricsLocationManager.h index ce04ae9ef..7281d0501 100644 --- a/include/mbgl/ios/MGLMetricsLocationManager.h +++ b/include/mbgl/ios/MGLMetricsLocationManager.h @@ -1,22 +1,9 @@ -// -// MBLocationManager.h -// Hermes -// -// Created by Brad Leege on 3/8/15. -// Copyright (c) 2015 Mapbox. All rights reserved. -// - #import -#import "CoreLocation/CoreLocation.h" -@interface MGLMetricsLocationManager : NSObject +@interface MGLMetricsLocationManager : NSObject -+ (id)sharedManager; - -- (BOOL) isAuthorizedStatusDetermined; -- (void) requestAlwaysAuthorization; - -- (void) startUpdatingLocation; -- (void) stopUpdatingLocation; +// This method can be called from any thread. +// ++ (instancetype)sharedManager; @end diff --git a/include/mbgl/ios/MGLStyleFunctionValue.h b/include/mbgl/ios/MGLStyleFunctionValue.h deleted file mode 100644 index 27a867548..000000000 --- a/include/mbgl/ios/MGLStyleFunctionValue.h +++ /dev/null @@ -1,23 +0,0 @@ -#import - -@interface MGLStyleFunctionValue : NSObject - -+ (instancetype)linearFunctionWithBaseZoomLevel:(CGFloat)zBase - initialValue:(CGFloat)val - slope:(CGFloat)slope - minimumValue:(CGFloat)min - maximumValue:(CGFloat)max; - -+ (instancetype)exponentialFunctionWithBaseZoomLevel:(CGFloat)zBase - initialValue:(CGFloat)val - slope:(CGFloat)slope - minimumValue:(CGFloat)min - maximumValue:(CGFloat)max; - -+ (instancetype)minimumZoomLevelFunction:(CGFloat)minimumZoom; - -+ (instancetype)maximumZoomLevelFunction:(CGFloat)maximumZoom; - -+ (instancetype)stopsFunctionWithZoomLevelsAndValues:(NSNumber *)firstZoom, ... NS_REQUIRES_NIL_TERMINATION; - -@end diff --git a/include/mbgl/ios/MGLTypes.h b/include/mbgl/ios/MGLTypes.h index 7a1744577..4c2e58b24 100644 --- a/include/mbgl/ios/MGLTypes.h +++ b/include/mbgl/ios/MGLTypes.h @@ -1,17 +1,9 @@ #import -// style property value types -// -extern NSString *const MGLStyleValueTypeBoolean; -extern NSString *const MGLStyleValueTypeNumber; -extern NSString *const MGLStyleValueTypeNumberPair; -extern NSString *const MGLStyleValueTypeColor; -extern NSString *const MGLStyleValueTypeString; - -// style property function types -// -extern NSString *const MGLStyleValueTypeFunctionMinimumZoom; -extern NSString *const MGLStyleValueTypeFunctionMaximumZoom; -extern NSString *const MGLStyleValueTypeFunctionLinear; -extern NSString *const MGLStyleValueTypeFunctionExponential; -extern NSString *const MGLStyleValueTypeFunctionStops; +/// The degree to which the map view tracks the user’s location. +typedef NS_ENUM(NSUInteger, MGLUserTrackingMode) +{ + MGLUserTrackingModeNone = 0, ///< does not track the user’s location or heading + MGLUserTrackingModeFollow = 1, ///< tracks the user’s location + MGLUserTrackingModeFollowWithHeading = 2, ///< tracks the user’s location and heading +}; diff --git a/include/mbgl/ios/MGLUserLocation.h b/include/mbgl/ios/MGLUserLocation.h new file mode 100644 index 000000000..fee336888 --- /dev/null +++ b/include/mbgl/ios/MGLUserLocation.h @@ -0,0 +1,26 @@ +#import "MGLAnnotation.h" + +@interface MGLUserLocation : NSObject + +@property (nonatomic, readonly) CLLocationCoordinate2D coordinate; + +/** @name Determining the User’s Position */ + +/** The current location of the device. (read-only) +* +* This property contains `nil` if the map view is not currently showing the user location or if the user’s location has not yet been determined. */ +@property (nonatomic, readonly) CLLocation *location; + +/** A Boolean value indicating whether the user’s location is currently being updated. (read-only) */ +@property (nonatomic, readonly, getter=isUpdating) BOOL updating; // FIXME + +/** The heading of the user location. (read-only) +* +* This property is `nil` if the user location tracking mode is not `RMUserTrackingModeFollowWithHeading`. */ +@property (nonatomic, readonly) CLHeading *heading; + +@property (nonatomic, copy) NSString *title; + +@property (nonatomic, copy) NSString *subtitle; + +@end diff --git a/include/mbgl/ios/MapboxGL.h b/include/mbgl/ios/MapboxGL.h index 237d493f3..c32915bc7 100644 --- a/include/mbgl/ios/MapboxGL.h +++ b/include/mbgl/ios/MapboxGL.h @@ -1,7 +1,4 @@ #import "MGLAnnotation.h" #import "MGLMapView.h" -#import "MGLStyleFunctionValue.h" #import "MGLTypes.h" -#import "NSArray+MGLAdditions.h" -#import "NSDictionary+MGLAdditions.h" -#import "UIColor+MGLAdditions.h" +#import "MGLUserLocation.h" diff --git a/include/mbgl/ios/NSArray+MGLAdditions.h b/include/mbgl/ios/NSArray+MGLAdditions.h deleted file mode 100644 index 4b8761433..000000000 --- a/include/mbgl/ios/NSArray+MGLAdditions.h +++ /dev/null @@ -1,7 +0,0 @@ -#import - -@interface NSArray (MGLAdditions) - -- (NSMutableArray *)deepMutableCopy; - -@end diff --git a/include/mbgl/ios/NSDictionary+MGLAdditions.h b/include/mbgl/ios/NSDictionary+MGLAdditions.h deleted file mode 100644 index 04c3396d4..000000000 --- a/include/mbgl/ios/NSDictionary+MGLAdditions.h +++ /dev/null @@ -1,7 +0,0 @@ -#import - -@interface NSDictionary (MGLAdditions) - -- (NSMutableDictionary *)deepMutableCopy; - -@end diff --git a/include/mbgl/ios/UIColor+MGLAdditions.h b/include/mbgl/ios/UIColor+MGLAdditions.h deleted file mode 100644 index 3758c04ee..000000000 --- a/include/mbgl/ios/UIColor+MGLAdditions.h +++ /dev/null @@ -1,11 +0,0 @@ -#import - -@interface UIColor (MGLAdditions) - -+ (UIColor *)colorWithRGBAString:(NSString *)rgbaString; -- (NSString *)rgbaStringFromColor; - -+ (UIColor *)colorWithHexString:(NSString *)hexString; -- (NSString *)hexStringFromColor; - -@end diff --git a/include/mbgl/map/map.hpp b/include/mbgl/map/map.hpp index 0fb2065cc..cd280d024 100644 --- a/include/mbgl/map/map.hpp +++ b/include/mbgl/map/map.hpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -28,7 +29,6 @@ class LayerDescription; class Sprite; class Style; class StyleLayer; -class StyleLayerGroup; class StyleSource; class TexturePool; class FileSource; @@ -153,13 +153,14 @@ public: // Annotations void setDefaultPointAnnotationSymbol(const std::string&); + double getTopOffsetPixelsForAnnotationSymbol(const std::string&); uint32_t addPointAnnotation(const LatLng&, const std::string& symbol); std::vector addPointAnnotations(const std::vector&, const std::vector& symbols); void removeAnnotation(uint32_t); void removeAnnotations(const std::vector&); - std::vector getAnnotationsInBounds(const LatLngBounds&) const; - LatLngBounds getBoundsForAnnotations(const std::vector&) const; + std::vector getAnnotationsInBounds(const LatLngBounds&); + LatLngBounds getBoundsForAnnotations(const std::vector&); // Debug void setDebug(bool value); @@ -186,7 +187,6 @@ private: void updateTiles(); void updateSources(); - void updateSources(const util::ptr &group); // Triggered by triggerUpdate(); void update(); @@ -199,6 +199,12 @@ private: // the stylesheet. void prepare(); + // Runs the function in the map thread. + void invokeTask(std::function&&); + template auto invokeSyncTask(const Fn& fn) -> decltype(fn()); + + void processTasks(); + void updateAnnotationTiles(const std::vector&); enum class Mode : uint8_t { @@ -218,6 +224,7 @@ private: std::thread thread; std::unique_ptr asyncTerminate; std::unique_ptr asyncUpdate; + std::unique_ptr asyncInvoke; std::unique_ptr asyncRender; bool terminating = false; @@ -256,6 +263,9 @@ private: std::set> activeSources; std::atomic updated; + + std::mutex mutexTask; + std::queue> tasks; }; } diff --git a/include/mbgl/map/view.hpp b/include/mbgl/map/view.hpp index 1ee9d300c..bcfeb62cf 100644 --- a/include/mbgl/map/view.hpp +++ b/include/mbgl/map/view.hpp @@ -10,14 +10,15 @@ class Map; enum MapChange : uint8_t { MapChangeRegionWillChange = 0, MapChangeRegionWillChangeAnimated = 1, - MapChangeRegionDidChange = 2, - MapChangeRegionDidChangeAnimated = 3, - MapChangeWillStartLoadingMap = 4, - MapChangeDidFinishLoadingMap = 5, - MapChangeDidFailLoadingMap = 6, - MapChangeWillStartRenderingMap = 7, - MapChangeDidFinishRenderingMap = 8, - MapChangeDidFinishRenderingMapFullyRendered = 9 + MapChangeRegionIsChanging = 2, + MapChangeRegionDidChange = 3, + MapChangeRegionDidChangeAnimated = 4, + MapChangeWillStartLoadingMap = 5, + MapChangeDidFinishLoadingMap = 6, + MapChangeDidFailLoadingMap = 7, + MapChangeWillStartRenderingMap = 8, + MapChangeDidFinishRenderingMap = 9, + MapChangeDidFinishRenderingMapFullyRendered = 10 }; class View { diff --git a/include/mbgl/platform/darwin/settings_nsuserdefaults.hpp b/include/mbgl/platform/darwin/settings_nsuserdefaults.hpp index 3533e3da3..6c91fd302 100644 --- a/include/mbgl/platform/darwin/settings_nsuserdefaults.hpp +++ b/include/mbgl/platform/darwin/settings_nsuserdefaults.hpp @@ -1,6 +1,8 @@ #ifndef MBGL_COMMON_SETTINGS_NSUSERDEFAULTS #define MBGL_COMMON_SETTINGS_NSUSERDEFAULTS +#import + namespace mbgl { class Settings_NSUserDefaults { @@ -16,6 +18,9 @@ public: double zoom = 0; double bearing = 0; + MGLUserTrackingMode userTrackingMode = MGLUserTrackingModeNone; + bool showsUserLocation = false; + bool debug = false; }; diff --git a/ios/MapboxGL.podspec b/ios/MapboxGL.podspec index 617966744..b474f7c9e 100644 --- a/ios/MapboxGL.podspec +++ b/ios/MapboxGL.podspec @@ -22,7 +22,7 @@ Pod::Spec.new do |m| m.resource_bundle = { 'MapboxGL' => 'MapboxGL.bundle/*' } - m.frameworks = 'CoreLocation', 'GLKit', 'ImageIO', 'MobileCoreServices', 'SystemConfiguration' + m.frameworks = 'CoreLocation', 'CoreTelephony', 'GLKit', 'ImageIO', 'MobileCoreServices', 'QuartzCore', 'SystemConfiguration' m.libraries = 'c++', 'sqlite3', 'z' diff --git a/ios/app/MBXViewController.mm b/ios/app/MBXViewController.mm index 6d1175e4f..c9973bcb7 100644 --- a/ios/app/MBXViewController.mm +++ b/ios/app/MBXViewController.mm @@ -21,10 +21,9 @@ static NSArray *const kStyleNames = @[ static NSString *const kStyleVersion = @"v7"; -@interface MBXViewController () +@interface MBXViewController () @property (nonatomic) MGLMapView *mapView; -@property (nonatomic) CLLocationManager *locationManager; @end @@ -66,9 +65,10 @@ mbgl::Settings_NSUserDefaults *settings = nullptr; self.mapView = [[MGLMapView alloc] initWithFrame:self.view.bounds accessToken:accessToken]; self.mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; - [self.view addSubview:self.mapView]; - self.mapView.viewControllerForLayoutGuides = self; + self.mapView.showsUserLocation = YES; + self.mapView.delegate = self; + [self.view addSubview:self.mapView]; self.view.tintColor = kTintColor; self.navigationController.navigationBar.tintColor = kTintColor; @@ -107,6 +107,8 @@ mbgl::Settings_NSUserDefaults *settings = nullptr; settings->zoom = self.mapView.zoomLevel; settings->bearing = self.mapView.direction; settings->debug = self.mapView.isDebugActive; + settings->userTrackingMode = self.mapView.userTrackingMode; + settings->showsUserLocation = self.mapView.showsUserLocation; settings->save(); } } @@ -117,6 +119,8 @@ mbgl::Settings_NSUserDefaults *settings = nullptr; settings->load(); [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(settings->latitude, settings->longitude) zoomLevel:settings->zoom animated:NO]; self.mapView.direction = settings->bearing; + self.mapView.userTrackingMode = settings->userTrackingMode; + self.mapView.showsUserLocation = settings->showsUserLocation; [self.mapView setDebugActive:settings->debug]; } } @@ -252,40 +256,17 @@ mbgl::Settings_NSUserDefaults *settings = nullptr; - (void)locateUser { - if ( ! self.locationManager) + if (self.mapView.userTrackingMode == MGLUserTrackingModeNone) { - self.locationManager = [CLLocationManager new]; - self.locationManager.delegate = self; + self.mapView.userTrackingMode = MGLUserTrackingModeFollow; } - - if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) + else if (self.mapView.userTrackingMode == MGLUserTrackingModeFollow) { - [[[UIAlertView alloc] initWithTitle:@"Authorization Denied" - message:@"Please enable location services for this app in Privacy settings." - delegate:nil - cancelButtonTitle:nil otherButtonTitles:@"OK", nil] show]; + self.mapView.userTrackingMode = MGLUserTrackingModeFollowWithHeading; } else { -#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000 - if ([CLLocationManager instancesRespondToSelector:@selector(requestWhenInUseAuthorization)]) - { - if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse) - { - [self.locationManager startUpdatingLocation]; - } - else - { - [_locationManager requestWhenInUseAuthorization]; - } - } - else - { - [self.locationManager startUpdatingLocation]; - } -#else - [self.locationManager startUpdatingLocation]; -#endif + self.mapView.userTrackingMode = MGLUserTrackingModeNone; } } @@ -303,39 +284,14 @@ mbgl::Settings_NSUserDefaults *settings = nullptr; } } -#pragma mark - CLLocationManagerDelegate - -- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status -{ - switch (status) - { - case kCLAuthorizationStatusAuthorizedAlways: -#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000 - case kCLAuthorizationStatusAuthorizedWhenInUse: -#endif - { - [manager startUpdatingLocation]; - break; - } - default: - { - } - } -} - #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-parameter" -- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations +#pragma mark - MGLMapViewDelegate + +- (BOOL)mapView:(MGLMapView *)mapView annotationCanShowCallout:(id )annotation { - CLLocation *latestLocation = locations.lastObject; - - if ([latestLocation distanceFromLocation:[[CLLocation alloc] initWithLatitude:self.mapView.centerCoordinate.latitude longitude:self.mapView.centerCoordinate.longitude]] > 100) - { - [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(latestLocation.coordinate.latitude, latestLocation.coordinate.longitude) zoomLevel:17 animated:YES]; - } - - [self.locationManager stopUpdatingLocation]; + return YES; } #pragma clang diagnostic pop diff --git a/ios/app/mapboxgl-app.gyp b/ios/app/mapboxgl-app.gyp index 793ba6bce..0e093a1d8 100644 --- a/ios/app/mapboxgl-app.gyp +++ b/ios/app/mapboxgl-app.gyp @@ -10,7 +10,8 @@ 'mac_bundle': 1, 'mac_bundle_resources': [ ' MGLUserTrackingModeNone && + uncheckedTrackingMode <= MGLUserTrackingModeFollowWithHeading) + { + userTrackingMode = (MGLUserTrackingMode)uncheckedTrackingMode; + } + showsUserLocation = [settings[@"showsUserLocation"] boolValue]; } void Settings_NSUserDefaults::save() { - [[NSUserDefaults standardUserDefaults] setValuesForKeysWithDictionary:@{ @"longitude" : @(longitude), - @"latitude" : @(latitude), - @"zoom" : @(zoom), - @"bearing" : @(bearing), - @"debug" : @(debug) }]; + [[NSUserDefaults standardUserDefaults] setValuesForKeysWithDictionary:@{ + @"longitude" : @(longitude), + @"latitude" : @(latitude), + @"zoom" : @(zoom), + @"bearing" : @(bearing), + @"userTrackingMode" : @(userTrackingMode), + @"showsUserLocation" : @(showsUserLocation), + @"debug" : @(debug), + }]; [[NSUserDefaults standardUserDefaults] synchronize]; } diff --git a/platform/ios/MGLMapView.mm b/platform/ios/MGLMapView.mm index ce5997e0a..4a55ada17 100644 --- a/platform/ios/MGLMapView.mm +++ b/platform/ios/MGLMapView.mm @@ -15,16 +15,15 @@ #include #import "MGLTypes.h" -#import "MGLStyleFunctionValue.h" #import "MGLAnnotation.h" +#import "MGLUserLocationAnnotationView.h" +#import "MGLUserLocation_Private.h" -#import "UIColor+MGLAdditions.h" -#import "NSArray+MGLAdditions.h" -#import "NSDictionary+MGLAdditions.h" +#import "SMCalloutView.h" + +#import "MGLMapboxEvents.h" #import -#import "MGLMapboxEvents.h" -#import "MGLMetricsLocationManager.h" // Returns the path to the default cache database on this system. const std::string &defaultCacheDatabase() { @@ -47,24 +46,14 @@ 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; -extern NSString *const MGLStyleKeyIcon; -extern NSString *const MGLStyleKeyText; -extern NSString *const MGLStyleKeyRaster; -extern NSString *const MGLStyleKeyComposite; -extern NSString *const MGLStyleKeyBackground; - -extern NSString *const MGLStyleValueFunctionAllowed; - NSTimeInterval const MGLAnimationDuration = 0.3; +const CGSize MGLAnnotationUpdateViewportOutset = {150, 150}; NSString *const MGLAnnotationIDKey = @"MGLAnnotationIDKey"; #pragma mark - Private - -@interface MGLMapView () +@interface MGLMapView () @property (nonatomic) EAGLContext *context; @property (nonatomic) GLKView *glView; @@ -77,10 +66,12 @@ NSString *const MGLAnnotationIDKey = @"MGLAnnotationIDKey"; @property (nonatomic) UIRotationGestureRecognizer *rotate; @property (nonatomic) UILongPressGestureRecognizer *quickZoom; @property (nonatomic) NSMutableArray *bundledStyleNames; -@property (nonatomic) NSMapTable *annotationsStore; +@property (nonatomic) NSMapTable *annotationIDsByAnnotation; @property (nonatomic) std::vector annotationsNearbyLastTap; @property (nonatomic, weak) id selectedAnnotation; -@property (nonatomic, readonly) NSDictionary *allowedStyleTypes; +@property (nonatomic) SMCalloutView *selectedAnnotationCalloutView; +@property (nonatomic) MGLUserLocationAnnotationView *userLocationAnnotationView; +@property (nonatomic) CLLocationManager *locationManager; @property (nonatomic) CGPoint centerPoint; @property (nonatomic) CGFloat scale; @property (nonatomic) CGFloat angle; @@ -90,26 +81,8 @@ NSString *const MGLAnnotationIDKey = @"MGLAnnotationIDKey"; @end -@interface MGLStyleFunctionValue (MGLMapViewFriend) - -@property (nonatomic) NSString *functionType; -@property (nonatomic) NSDictionary *stops; -@property (nonatomic) CGFloat zBase; -@property (nonatomic) CGFloat val; -@property (nonatomic) CGFloat slope; -@property (nonatomic) CGFloat min; -@property (nonatomic) CGFloat max; -@property (nonatomic) CGFloat minimumZoom; -@property (nonatomic) CGFloat maximumZoom; - -- (id)rawStyle; - -@end - @implementation MGLMapView -@synthesize bundledStyleNames=_bundledStyleNames; - #pragma mark - Setup & Teardown - @dynamic debugActive; @@ -159,6 +132,19 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; return self; } +- (instancetype)initWithFrame:(CGRect)frame accessToken:(NSString *)accessToken styleURL:(NSURL *)styleURL +{ + self = [super initWithFrame:frame]; + + if (self && [self commonInit]) + { + if (accessToken) [self setAccessToken:accessToken]; + if (styleURL) [self setStyleURL:styleURL]; + } + + return self; +} + - (instancetype)initWithFrame:(CGRect)frame accessToken:(NSString *)accessToken { return [self initWithFrame:frame accessToken:accessToken styleJSON:nil]; @@ -180,8 +166,8 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; { if (accessToken) { - mbglMap->setAccessToken((std::string)[accessToken cStringUsingEncoding:[NSString defaultCStringEncoding]]); - [[MGLMapboxEvents sharedManager] setToken:accessToken]; + mbglMap->setAccessToken((std::string)[accessToken UTF8String]); + [MGLMapboxEvents setToken:accessToken]; } } @@ -195,13 +181,22 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; } else { - mbglMap->setStyleJSON((std::string)[styleJSON cStringUsingEncoding:[NSString defaultCStringEncoding]]); + mbglMap->setStyleJSON((std::string)[styleJSON UTF8String]); } } -- (void)setStyleURL:(NSString *)filePathURL +- (void)setStyleURL:(NSURL *)styleURL { - mbglMap->setStyleURL(std::string("asset://") + [filePathURL UTF8String]); + std::string styleURLString([[styleURL absoluteString] UTF8String]); + + if ( ! [styleURL scheme]) + { + mbglMap->setStyleURL(std::string("asset://") + styleURLString); + } + else + { + mbglMap->setStyleURL(styleURLString); + } } - (BOOL)commonInit @@ -221,16 +216,11 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; // self.accessibilityLabel = @"Map"; - // setup Metrics - MGLMapboxEvents *events = [MGLMapboxEvents sharedManager]; + // metrics: initial setup NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"]; NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]; - if (appName != nil) { - events.appName = appName; - } - if (appVersion != nil) { - events.appVersion = appVersion; - } + if (appName != nil) [MGLMapboxEvents setAppName:appName]; + if (appVersion != nil) [MGLMapboxEvents setAppVersion:appVersion]; // create GL view // @@ -244,7 +234,7 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; } _glView.delegate = self; [_glView bindDrawable]; - [self addSubview:_glView]; + [self insertSubview:_glView atIndex:0]; _glView.contentMode = UIViewContentModeCenter; [self setBackgroundColor:[UIColor clearColor]]; @@ -291,8 +281,8 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; // setup annotations // - _annotationsStore = [NSMapTable mapTableWithKeyOptions:NSMapTableStrongMemory valueOptions:NSMapTableStrongMemory]; - std::string defaultSymbolName([MGLDefaultStyleMarkerSymbolName cStringUsingEncoding:[NSString defaultCStringEncoding]]); + _annotationIDsByAnnotation = [NSMapTable mapTableWithKeyOptions:NSMapTableStrongMemory valueOptions:NSMapTableStrongMemory]; + std::string defaultSymbolName([MGLDefaultStyleMarkerSymbolName UTF8String]); mbglMap->setDefaultPointAnnotationSymbol(defaultSymbolName); // setup logo bug @@ -371,9 +361,6 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillForeground:) name:UIApplicationWillEnterForegroundNotification object:nil]; - // Setup MBLocationManager for metrics - [MGLMetricsLocationManager sharedManager]; - // set initial position // mbglMap->setLatLngZoom(mbgl::LatLng(0, 0), mbglMap->getMinZoom()); @@ -386,28 +373,17 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; // start the main loop mbglMap->start(); - - // Fire map.load on a background thread - dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - - NSMutableDictionary *evt = [[NSMutableDictionary alloc] init]; - [evt setValue:[[NSNumber alloc] initWithDouble:mbglMap->getLatLng().latitude] forKey:@"lat"]; - [evt setValue:[[NSNumber alloc] initWithDouble:mbglMap->getLatLng().longitude] forKey:@"lng"]; - [evt setValue:[[NSNumber alloc] initWithDouble:mbglMap->getZoom()] forKey:@"zoom"]; - [[MGLMapboxEvents sharedManager] pushEvent:@"map.load" withAttributes:evt]; - - [evt setValue:[[NSNumber alloc] initWithBool:[[UIApplication sharedApplication] isRegisteredForRemoteNotifications]] forKey:@"enabled.push"]; - - NSString *email = @"Unknown"; - Class MFMailComposeViewController = NSClassFromString(@"MFMailComposeViewController"); - if (MFMailComposeViewController) { - SEL canSendMail = NSSelectorFromString(@"canSendMail"); - BOOL sendMail = ((BOOL (*)(id, SEL))[MFMailComposeViewController methodForSelector:canSendMail])(MFMailComposeViewController, canSendMail); - email = [NSString stringWithFormat:@"%i", sendMail]; - } - [evt setValue:email forKey:@"enabled.email"]; - }); - + // metrics: map load event + const mbgl::LatLng latLng = mbglMap->getLatLng(); + const double zoom = mbglMap->getZoom(); + + [MGLMapboxEvents pushEvent:MGLEventTypeMapLoad withAttributes:@{ + MGLEventKeyLatitude: @(latLng.latitude), + MGLEventKeyLongitude: @(latLng.longitude), + MGLEventKeyZoomLevel: @(zoom), + MGLEventKeyPushEnabled: @([MGLMapboxEvents checkPushEnabled]) + }]; + return YES; } @@ -449,6 +425,13 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; } } +- (void)setDelegate:(id)delegate +{ + if (_delegate == delegate) return; + + _delegate = delegate; +} + #pragma mark - Layout - - (void)setFrame:(CGRect)frame @@ -585,8 +568,7 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; - (void)appDidBackground:(NSNotification *)notification { - // Flush Any Events Still In Queue - [[MGLMapboxEvents sharedManager] flush]; + [MGLMapboxEvents flush]; mbglMap->stop(); @@ -602,13 +584,14 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; - (void)tintColorDidChange { - for (UIView *subview in self.subviews) - { - if ([subview respondsToSelector:@selector(setTintColor:)]) - { - subview.tintColor = self.tintColor; - } - } + for (UIView *subview in self.subviews) [self updateTintColorForView:subview]; +} + +- (void)updateTintColorForView:(UIView *)view +{ + if ([view respondsToSelector:@selector(setTintColor:)]) view.tintColor = self.tintColor; + + for (UIView *subview in view.subviews) [self updateTintColorForView:subview]; } #pragma mark - Gestures - @@ -616,21 +599,25 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; - (void)handleCompassTapGesture:(id)sender { [self resetNorthAnimated:YES]; + + if (self.userTrackingMode == MGLUserTrackingModeFollowWithHeading) self.userTrackingMode = MGLUserTrackingModeFollow; } #pragma clang diagnostic pop - (void)handlePanGesture:(UIPanGestureRecognizer *)pan { - [self trackGestureEvent:@"Pan" forRecognizer:pan]; - if ( ! self.isScrollEnabled) return; mbglMap->cancelTransitions(); if (pan.state == UIGestureRecognizerStateBegan) { + [self trackGestureEvent:MGLEventGesturePanStart forRecognizer:pan]; + self.centerPoint = CGPointMake(0, 0); + + self.userTrackingMode = MGLUserTrackingModeNone; } else if (pan.state == UIGestureRecognizerStateChanged) { @@ -640,6 +627,8 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; mbglMap->moveBy(delta.x, delta.y); self.centerPoint = CGPointMake(self.centerPoint.x + delta.x, self.centerPoint.y + delta.y); + + [self notifyMapChange:@(mbgl::MapChangeRegionDidChangeAnimated)]; } else if (pan.state == UIGestureRecognizerStateEnded || pan.state == UIGestureRecognizerStateCancelled) { @@ -675,23 +664,26 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; [weakSelf notifyMapChange:@(mbgl::MapChangeRegionDidChangeAnimated)]; }]; } - - // Send Map Drag End Event - CGPoint ptInView = CGPointMake([pan locationInView:pan.view].x, [pan locationInView:pan.view].y); - CLLocationCoordinate2D coord = [self convertPoint:ptInView toCoordinateFromView:pan.view]; - NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; - [dict setValue:[[NSNumber alloc] initWithDouble:coord.latitude] forKey:@"lat"]; - [dict setValue:[[NSNumber alloc] initWithDouble:coord.longitude] forKey:@"lng"]; - [dict setValue:[[NSNumber alloc] initWithDouble:[self zoomLevel]] forKey:@"zoom"]; - - [[MGLMapboxEvents sharedManager] pushEvent:@"map.dragend" withAttributes:dict]; + else + { + [self notifyMapChange:@(mbgl::MapChangeRegionDidChange)]; + } + + // metrics: pan end + CGPoint pointInView = CGPointMake([pan locationInView:pan.view].x, [pan locationInView:pan.view].y); + CLLocationCoordinate2D panCoordinate = [self convertPoint:pointInView toCoordinateFromView:pan.view]; + double zoom = [self zoomLevel]; + + [MGLMapboxEvents pushEvent:MGLEventTypeMapDragEnd withAttributes:@{ + MGLEventKeyLatitude: @(panCoordinate.latitude), + MGLEventKeyLongitude: @(panCoordinate.longitude), + MGLEventKeyZoomLevel: @(zoom) + }]; } } - (void)handlePinchGesture:(UIPinchGestureRecognizer *)pinch { - [self trackGestureEvent:@"Pinch" forRecognizer:pinch]; - if ( ! self.isZoomEnabled) return; if (mbglMap->getZoom() <= mbglMap->getMinZoom() && pinch.scale < 1) return; @@ -700,9 +692,13 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; if (pinch.state == UIGestureRecognizerStateBegan) { + [self trackGestureEvent:MGLEventGesturePinchStart forRecognizer:pinch]; + mbglMap->startScaling(); self.scale = mbglMap->getScale(); + + self.userTrackingMode = MGLUserTrackingModeNone; } else if (pinch.state == UIGestureRecognizerStateChanged) { @@ -720,23 +716,25 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; [self unrotateIfNeededAnimated:YES]; - [self notifyMapChange:@(mbgl::MapChangeRegionDidChangeAnimated)]; + [self notifyMapChange:@(mbgl::MapChangeRegionDidChange)]; } } - (void)handleRotateGesture:(UIRotationGestureRecognizer *)rotate { - [self trackGestureEvent:@"Rotation" forRecognizer:rotate]; - if ( ! self.isRotateEnabled) return; mbglMap->cancelTransitions(); if (rotate.state == UIGestureRecognizerStateBegan) { + [self trackGestureEvent:MGLEventGestureRotateStart forRecognizer:rotate]; + mbglMap->startRotating(); self.angle = [MGLMapView degreesToRadians:mbglMap->getBearing()] * -1; + + self.userTrackingMode = MGLUserTrackingModeNone; } else if (rotate.state == UIGestureRecognizerStateChanged) { @@ -760,135 +758,169 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; [self unrotateIfNeededAnimated:YES]; - [self notifyMapChange:@(mbgl::MapChangeRegionDidChangeAnimated)]; + [self notifyMapChange:@(mbgl::MapChangeRegionDidChange)]; } } - (void)handleSingleTapGesture:(UITapGestureRecognizer *)singleTap { - [self trackGestureEvent:@"SingleTap" forRecognizer: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()) + if (singleTap.state == UIGestureRecognizerStateEnded) { - // there is at least one nearby annotation; select one - // - // first, sort for comparison and iteration - std::sort(nearbyAnnotations.begin(), nearbyAnnotations.end()); + [self trackGestureEvent:MGLEventGestureSingleTap forRecognizer:singleTap]; - if (nearbyAnnotations == self.annotationsNearbyLastTap) + CGPoint tapPoint = [singleTap locationInView:self]; + + if (self.userLocationVisible && ! [self.selectedAnnotation isEqual:self.userLocation]) { - // the selection candidates haven't changed; cycle through them - if (self.selectedAnnotation && - [[[self.annotationsStore objectForKey:self.selectedAnnotation] - objectForKey:MGLAnnotationIDKey] unsignedIntValue] == self.annotationsNearbyLastTap.back()) + CGRect userLocationRect = CGRectMake(tapPoint.x - 15, tapPoint.y - 15, 30, 30); + + if (CGRectContainsPoint(userLocationRect, [self convertCoordinate:self.userLocation.coordinate toPointToView:self])) { - // 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(); + [self selectAnnotation:self.userLocation animated:YES]; + return; } - else if (self.selectedAnnotation) + } + + // tolerances based on touch size & typical marker aspect ratio + CGFloat toleranceWidth = 40; + CGFloat toleranceHeight = 60; + + // 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(coordinateToLatLng(coordinate)); + + coordinate = [self convertPoint:tapRectUpperLeft toCoordinateFromView:self]; + tapBounds.extend(coordinateToLatLng(coordinate)); + + coordinate = [self convertPoint:tapRectUpperRight toCoordinateFromView:self]; + tapBounds.extend(coordinateToLatLng(coordinate)); + + coordinate = [self convertPoint:tapRectLowerRight toCoordinateFromView:self]; + tapBounds.extend(coordinateToLatLng(coordinate)); + + // 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) { - // 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]; + // the selection candidates haven't changed; cycle through them + if (self.selectedAnnotation && + [[[self.annotationIDsByAnnotation 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.annotationIDsByAnnotation 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 { - // no current selection; select the first one + // start tracking a new set of nearby annotations + self.annotationsNearbyLastTap = nearbyAnnotations; + + // 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(); + // there are no nearby annotations; deselect if necessary + newSelectedAnnotationID = -1; } - } - 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 (newSelectedAnnotationID >= 0) { - 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]; - } + // find & select model object for selection + NSEnumerator *enumerator = self.annotationIDsByAnnotation.keyEnumerator; - // either way, we should stop enumerating - break; + while (id annotation = enumerator.nextObject) + { + if ([[[self.annotationIDsByAnnotation 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]; + } } - else - { - // deselect any selected annotation - if (self.selectedAnnotation) [self deselectAnnotation:self.selectedAnnotation animated:YES]; - } - - NSLog(@"%i (%@)", newSelectedAnnotationID, self.selectedAnnotation.title); } - (void)handleDoubleTapGesture:(UITapGestureRecognizer *)doubleTap { - [self trackGestureEvent:@"DoubleTap" forRecognizer:doubleTap]; - if ( ! self.isZoomEnabled) return; mbglMap->cancelTransitions(); - if (doubleTap.state == UIGestureRecognizerStateEnded) + if (doubleTap.state == UIGestureRecognizerStateBegan) { - mbglMap->scaleBy(2, [doubleTap locationInView:doubleTap.view].x, [doubleTap locationInView:doubleTap.view].y, secondsAsDuration(MGLAnimationDuration)); + [self trackGestureEvent:MGLEventGestureDoubleTap forRecognizer:doubleTap]; + } + else if (doubleTap.state == UIGestureRecognizerStateEnded) + { + CGPoint doubleTapPoint = [doubleTap locationInView:doubleTap.view]; + + CGPoint zoomInPoint; + + if (self.userTrackingMode != MGLUserTrackingModeNone) + { + CGPoint userPoint = [self convertCoordinate:self.userLocation.coordinate toPointToView:self]; + CGRect userLocationRect = CGRectMake(userPoint.x - 40, userPoint.y - 40, 80, 80); + if (CGRectContainsPoint(userLocationRect, doubleTapPoint)) + { + zoomInPoint = userPoint; + } + } + else + { + self.userTrackingMode = MGLUserTrackingModeNone; + + zoomInPoint = doubleTapPoint; + } + + mbglMap->scaleBy(2, zoomInPoint.x, zoomInPoint.y, secondsAsDuration(MGLAnimationDuration)); self.animatingGesture = YES; @@ -907,17 +939,32 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; - (void)handleTwoFingerTapGesture:(UITapGestureRecognizer *)twoFingerTap { - [self trackGestureEvent:@"TwoFingerTap" forRecognizer:twoFingerTap]; - if ( ! self.isZoomEnabled) return; if (mbglMap->getZoom() == mbglMap->getMinZoom()) return; mbglMap->cancelTransitions(); - if (twoFingerTap.state == UIGestureRecognizerStateEnded) + if (twoFingerTap.state == UIGestureRecognizerStateBegan) { - mbglMap->scaleBy(0.5, [twoFingerTap locationInView:twoFingerTap.view].x, [twoFingerTap locationInView:twoFingerTap.view].y, secondsAsDuration(MGLAnimationDuration)); + [self trackGestureEvent:MGLEventGestureTwoFingerSingleTap forRecognizer:twoFingerTap]; + } + else if (twoFingerTap.state == UIGestureRecognizerStateEnded) + { + CGPoint zoomOutPoint; + + if (self.userTrackingMode != MGLUserTrackingModeNone) + { + zoomOutPoint = self.center; + } + else + { + self.userTrackingMode = MGLUserTrackingModeNone; + + zoomOutPoint = CGPointMake([twoFingerTap locationInView:twoFingerTap.view].x, [twoFingerTap locationInView:twoFingerTap.view].y); + } + + mbglMap->scaleBy(0.5, zoomOutPoint.x, zoomOutPoint.y, secondsAsDuration(MGLAnimationDuration)); self.animatingGesture = YES; @@ -936,17 +983,19 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; - (void)handleQuickZoomGesture:(UILongPressGestureRecognizer *)quickZoom { - [self trackGestureEvent:@"QuickZoom" forRecognizer:quickZoom]; - if ( ! self.isZoomEnabled) return; mbglMap->cancelTransitions(); if (quickZoom.state == UIGestureRecognizerStateBegan) { + [self trackGestureEvent:MGLEventGestureQuickZoom forRecognizer:quickZoom]; + self.scale = mbglMap->getScale(); self.quickZoomStart = [quickZoom locationInView:quickZoom.view].y; + + self.userTrackingMode = MGLUserTrackingModeNone; } else if (quickZoom.state == UIGestureRecognizerStateChanged) { @@ -962,7 +1011,16 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; { [self unrotateIfNeededAnimated:YES]; - [self notifyMapChange:@(mbgl::MapChangeRegionDidChangeAnimated)]; + [self notifyMapChange:@(mbgl::MapChangeRegionDidChange)]; + } +} + +- (void)handleCalloutAccessoryTapGesture:(UITapGestureRecognizer *)tap +{ + if ([self.delegate respondsToSelector:@selector(mapView:annotation:calloutAccessoryControlTapped:)]) + { + [self.delegate mapView:self annotation:self.selectedAnnotation + calloutAccessoryControlTapped:(UIControl *)tap.view]; } } @@ -973,18 +1031,18 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; return ([validSimultaneousGestures containsObject:gestureRecognizer] && [validSimultaneousGestures containsObject:otherGestureRecognizer]); } -- (void) trackGestureEvent:(NSString *) gesture forRecognizer:(UIGestureRecognizer *) recognizer +- (void)trackGestureEvent:(NSString *)gestureID forRecognizer:(UIGestureRecognizer *)recognizer { - // Send Map Zoom Event - CGPoint ptInView = CGPointMake([recognizer locationInView:recognizer.view].x, [recognizer locationInView:recognizer.view].y); - CLLocationCoordinate2D coord = [self convertPoint:ptInView toCoordinateFromView:recognizer.view]; - NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; - [dict setValue:[[NSNumber alloc] initWithDouble:coord.latitude] forKey:@"lat"]; - [dict setValue:[[NSNumber alloc] initWithDouble:coord.longitude] forKey:@"lng"]; - [dict setValue:[[NSNumber alloc] initWithDouble:[self zoomLevel]] forKey:@"zoom"]; - [dict setValue:gesture forKey:@"gesture"]; - - [[MGLMapboxEvents sharedManager] pushEvent:@"map.click" withAttributes:dict]; + CGPoint pointInView = CGPointMake([recognizer locationInView:recognizer.view].x, [recognizer locationInView:recognizer.view].y); + CLLocationCoordinate2D gestureCoordinate = [self convertPoint:pointInView toCoordinateFromView:recognizer.view]; + double zoom = [self zoomLevel]; + + [MGLMapboxEvents pushEvent:MGLEventTypeMapTap withAttributes:@{ + MGLEventKeyLatitude: @(gestureCoordinate.latitude), + MGLEventKeyLongitude: @(gestureCoordinate.longitude), + MGLEventKeyZoomLevel: @(zoom), + MGLEventKeyGestureID: gestureID + }]; } #pragma mark - Properties - @@ -1016,6 +1074,8 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; - (void)resetNorthAnimated:(BOOL)animated { + self.userTrackingMode = MGLUserTrackingModeNone; + CGFloat duration = (animated ? MGLAnimationDuration : 0); mbglMap->setBearing(0, secondsAsDuration(duration)); @@ -1029,6 +1089,8 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; { if (finished) { + [self notifyMapChange:@(animated ? mbgl::MapChangeRegionDidChangeAnimated : mbgl::MapChangeRegionDidChange)]; + [UIView animateWithDuration:MGLAnimationDuration animations:^ { @@ -1041,6 +1103,8 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; - (void)resetPosition { mbglMap->resetPosition(); + + [self notifyMapChange:@(mbgl::MapChangeRegionDidChange)]; } - (void)toggleDebug @@ -1050,11 +1114,20 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; #pragma mark - Geography - +- (void)setCenterCoordinate:(CLLocationCoordinate2D)coordinate animated:(BOOL)animated preservingTracking:(BOOL)tracking +{ + self.userTrackingMode = (tracking ? self.userTrackingMode : MGLUserTrackingModeNone); + + [self setCenterCoordinate:coordinate animated:animated]; +} + - (void)setCenterCoordinate:(CLLocationCoordinate2D)coordinate animated:(BOOL)animated { CGFloat duration = (animated ? MGLAnimationDuration : 0); mbglMap->setLatLng(coordinateToLatLng(coordinate), secondsAsDuration(duration)); + + [self notifyMapChange:@(animated ? mbgl::MapChangeRegionDidChangeAnimated : mbgl::MapChangeRegionDidChange)]; } - (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate @@ -1069,11 +1142,15 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; - (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate zoomLevel:(double)zoomLevel animated:(BOOL)animated { + self.userTrackingMode = MGLUserTrackingModeNone; + CGFloat duration = (animated ? MGLAnimationDuration : 0); mbglMap->setLatLngZoom(coordinateToLatLng(centerCoordinate), zoomLevel, secondsAsDuration(duration)); [self unrotateIfNeededAnimated:animated]; + + [self notifyMapChange:@(animated ? mbgl::MapChangeRegionDidChangeAnimated : mbgl::MapChangeRegionDidChange)]; } - (double)zoomLevel @@ -1083,11 +1160,15 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; - (void)setZoomLevel:(double)zoomLevel animated:(BOOL)animated { + self.userTrackingMode = MGLUserTrackingModeNone; + CGFloat duration = (animated ? MGLAnimationDuration : 0); mbglMap->setZoom(zoomLevel, secondsAsDuration(duration)); [self unrotateIfNeededAnimated:animated]; + + [self notifyMapChange:@(animated ? mbgl::MapChangeRegionDidChangeAnimated : mbgl::MapChangeRegionDidChange)]; } - (void)setZoomLevel:(double)zoomLevel @@ -1095,6 +1176,22 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; [self setZoomLevel:zoomLevel animated:NO]; } +- (void)zoomToSouthWestCoordinate:(CLLocationCoordinate2D)southWestCoordinate northEastCoordinate:(CLLocationCoordinate2D)northEastCoordinate animated:(BOOL)animated +{ + // NOTE: does not disrupt tracking mode + + CLLocationCoordinate2D center = CLLocationCoordinate2DMake((northEastCoordinate.latitude + southWestCoordinate.latitude) / 2, (northEastCoordinate.longitude + southWestCoordinate.longitude) / 2); + + CGFloat scale = mbglMap->getScale(); + CGFloat scaleX = mbglMap->getState().getWidth() / (northEastCoordinate.longitude - southWestCoordinate.longitude); + CGFloat scaleY = mbglMap->getState().getHeight() / (northEastCoordinate.latitude - southWestCoordinate.latitude); + CGFloat minZoom = mbglMap->getMinZoom(); + CGFloat maxZoom = mbglMap->getMaxZoom(); + CGFloat zoomLevel = MAX(MIN(log(scale * MIN(scaleX, scaleY)) / log(2), maxZoom), minZoom); + + [self setCenterCoordinate:center zoomLevel:zoomLevel animated:animated]; +} + - (CLLocationDirection)direction { double direction = mbglMap->getBearing() * -1; @@ -1109,9 +1206,13 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; { if ( ! animated && ! self.rotationAllowed) return; + self.userTrackingMode = MGLUserTrackingModeNone; + CGFloat duration = (animated ? MGLAnimationDuration : 0); mbglMap->setBearing(direction * -1, secondsAsDuration(duration)); + + [self notifyMapChange:@(animated ? mbgl::MapChangeRegionDidChangeAnimated : mbgl::MapChangeRegionDidChange)]; } - (void)setDirection:(CLLocationDirection)direction @@ -1132,7 +1233,7 @@ mbgl::DefaultFileSource *mbglFileSource = nullptr; - (CGPoint)convertCoordinate:(CLLocationCoordinate2D)coordinate toPointToView:(UIView *)view { - mbgl::vec2 pixel = mbglMap->pixelForLatLng(mbgl::LatLng(coordinate.latitude, coordinate.longitude)); + mbgl::vec2 pixel = mbglMap->pixelForLatLng(coordinateToLatLng(coordinate)); // flip y coordinate for iOS view origin in top left // @@ -1178,14 +1279,14 @@ CLLocationCoordinate2D latLngToCoordinate(mbgl::LatLng latLng) { const std::string styleJSON = mbglMap->getStyleJSON(); - return [NSJSONSerialization JSONObjectWithData:[@(styleJSON.c_str()) dataUsingEncoding:[NSString defaultCStringEncoding]] options:0 error:nil]; + return [NSJSONSerialization JSONObjectWithData:[@(styleJSON.c_str()) dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]; } - (void)setRawStyle:(NSDictionary *)style { NSData *data = [NSJSONSerialization dataWithJSONObject:style options:0 error:nil]; - [self setStyleJSON:[[NSString alloc] initWithData:data encoding:[NSString defaultCStringEncoding]]]; + [self setStyleJSON:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]]; } - (NSArray *)bundledStyleNames @@ -1219,53 +1320,12 @@ CLLocationCoordinate2D latLngToCoordinate(mbgl::LatLng latLng) if (isHybrid) { styleName = [@"satellite-" stringByAppendingString:[styleName substringFromIndex:[hybridStylePrefix length]]]; } - [self setStyleURL:[NSString stringWithFormat:@"styles/%@.json", styleName]]; + [self setStyleURL:[NSURL URLWithString:[NSString stringWithFormat:@"styles/%@.json", styleName]]]; if (isHybrid) { [self setStyleClasses:@[@"contours", @"labels"]]; } } -- (NSArray *)getStyleOrderedLayerNames -{ - return [[self getRawStyle] valueForKeyPath:@"layers.id"]; -} - -- (void)setStyleOrderedLayerNames:(NSArray *)orderedLayerNames -{ - NSMutableDictionary *style = [[self getRawStyle] deepMutableCopy]; - NSArray *oldLayers = style[@"layers"]; - NSMutableArray *newLayers = [NSMutableArray array]; - - if ([orderedLayerNames count] != [[oldLayers valueForKeyPath:@"id"] count]) - { - [NSException raise:@"invalid layer count" - format:@"new layer count (%lu) should equal existing layer count (%lu)", - (unsigned long)[orderedLayerNames count], - (unsigned long)[[oldLayers valueForKeyPath:@"id"] count]]; - } - else - { - for (NSString *newLayerName in orderedLayerNames) - { - if ( ! [[oldLayers valueForKeyPath:@"id"] containsObject:newLayerName]) - { - [NSException raise:@"invalid layer name" - format:@"layer name %@ unknown", - newLayerName]; - } - else - { - NSDictionary *newLayer = [oldLayers objectAtIndex:[[oldLayers valueForKeyPath:@"id"] indexOfObject:newLayerName]]; - [newLayers addObject:newLayer]; - } - } - } - - [style setValue:newLayers forKey:@"layers"]; - - [self setRawStyle:style]; -} - - (NSArray *)getAppliedStyleClasses { NSMutableArray *returnArray = [NSMutableArray array]; @@ -1291,355 +1351,22 @@ CLLocationCoordinate2D latLngToCoordinate(mbgl::LatLng latLng) for (NSString *appliedClass in appliedClasses) { - newAppliedClasses.insert(newAppliedClasses.end(), [appliedClass cStringUsingEncoding:[NSString defaultCStringEncoding]]); + newAppliedClasses.insert(newAppliedClasses.end(), [appliedClass UTF8String]); } mbglMap->setDefaultTransitionDuration(secondsAsDuration(transitionDuration)); mbglMap->setClasses(newAppliedClasses); } -- (NSString *)getKeyTypeForLayer:(NSString *)layerName -{ - NSDictionary *style = [self getRawStyle]; - - NSString *bucketType; - - if ([layerName isEqualToString:@"background"]) - { - bucketType = @"background"; - } - else - { - for (NSDictionary *layer in style[@"structure"]) - { - if ([layer[@"name"] isEqualToString:layerName]) - { - bucketType = style[@"buckets"][layer[@"bucket"]][@"type"]; - break; - } - } - } - - NSString *keyType; - - if ([bucketType isEqualToString:@"fill"]) - { - keyType = MGLStyleKeyFill; - } - else if ([bucketType isEqualToString:@"line"]) - { - keyType = MGLStyleKeyLine; - } - else if ([bucketType isEqualToString:@"point"]) - { - keyType = MGLStyleKeyIcon; - } - else if ([bucketType isEqualToString:@"text"]) - { - keyType = MGLStyleKeyText; - } - else if ([bucketType isEqualToString:@"raster"]) - { - keyType = MGLStyleKeyRaster; - } - else if ([bucketType isEqualToString:@"composite"]) - { - keyType = MGLStyleKeyComposite; - } - else if ([bucketType isEqualToString:@"background"]) - { - keyType = MGLStyleKeyBackground; - } - else - { - [NSException raise:@"invalid bucket type" - format:@"bucket type %@ unknown", - bucketType]; - } - - return keyType; -} - -- (NSDictionary *)getStyleDescriptionForLayer:(NSString *)layerName inClass:(NSString *)className -{ - NSDictionary *style = [self getRawStyle]; - - if ( ! [[style valueForKeyPath:@"classes.name"] containsObject:className]) - { - [NSException raise:@"invalid class name" - format:@"class name %@ unknown", - className]; - } - - NSUInteger classNumber = [[style valueForKeyPath:@"classes.name"] indexOfObject:className]; - - if ( ! [[style[@"classes"][classNumber][@"layers"] allKeys] containsObject:layerName]) - { - // layer specified in structure, but not styled - // - return nil; - } - - NSDictionary *layerStyle = style[@"classes"][classNumber][@"layers"][layerName]; - - NSMutableDictionary *styleDescription = [NSMutableDictionary dictionary]; - - for (NSString *keyName in [layerStyle allKeys]) - { - id value = layerStyle[keyName]; - - while ([[style[@"constants"] allKeys] containsObject:value]) - { - value = style[@"constants"][value]; - } - - if ([[self.allowedStyleTypes[MGLStyleKeyGeneric] allKeys] containsObject:keyName]) - { - [styleDescription setValue:[self typedPropertyForKeyName:keyName - ofType:MGLStyleKeyGeneric - withValue:value] - forKey:keyName]; - } - - NSString *keyType = [self getKeyTypeForLayer:layerName]; - - if ([[self.allowedStyleTypes[keyType] allKeys] containsObject:keyName]) - { - [styleDescription setValue:[self typedPropertyForKeyName:keyName - ofType:keyType - withValue:value] - forKey:keyName]; - } - } - - return styleDescription; -} - -- (NSDictionary *)typedPropertyForKeyName:(NSString *)keyName ofType:(NSString *)keyType withValue:(id)value -{ - if ( ! [[self.allowedStyleTypes[keyType] allKeys] containsObject:keyName]) - { - [NSException raise:@"invalid property name" - format:@"property name %@ unknown", - keyName]; - } - - NSArray *typeInfo = self.allowedStyleTypes[keyType][keyName]; - - if ([value isKindOfClass:[NSArray class]] && ! [typeInfo containsObject:MGLStyleValueTypeColor]) - { - if ([typeInfo containsObject:MGLStyleValueFunctionAllowed]) - { - if ([[(NSArray *)value firstObject] isKindOfClass:[NSString class]]) - { - NSString *functionType; - - if ([[(NSArray *)value firstObject] isEqualToString:@"linear"]) - { - functionType = MGLStyleValueTypeFunctionLinear; - } - else if ([[(NSArray *)value firstObject] isEqualToString:@"stops"]) - { - functionType = MGLStyleValueTypeFunctionStops; - } - else if ([[(NSArray *)value firstObject] isEqualToString:@"exponential"]) - { - functionType = MGLStyleValueTypeFunctionExponential; - } - else if ([[(NSArray *)value firstObject] isEqualToString:@"min"]) - { - functionType = MGLStyleValueTypeFunctionMinimumZoom; - } - else if ([[(NSArray *)value firstObject] isEqualToString:@"max"]) - { - functionType = MGLStyleValueTypeFunctionMaximumZoom; - } - - if (functionType) - { - return @{ @"type" : functionType, - @"value" : value }; - } - } - } - else if ([typeInfo containsObject:MGLStyleValueTypeNumberPair]) - { - return @{ @"type" : MGLStyleValueTypeNumberPair, - @"value" : value }; - } - } - else if ([typeInfo containsObject:MGLStyleValueTypeNumber]) - { - return @{ @"type" : MGLStyleValueTypeNumber, - @"value" : value }; - } - else if ([typeInfo containsObject:MGLStyleValueTypeBoolean]) - { - return @{ @"type" : MGLStyleValueTypeBoolean, - @"value" : @([(NSString *)value boolValue]) }; - } - else if ([typeInfo containsObject:MGLStyleValueTypeString]) - { - return @{ @"type" : MGLStyleValueTypeString, - @"value" : value }; - } - else if ([typeInfo containsObject:MGLStyleValueTypeColor]) - { - UIColor *color; - - if ([(NSString *)value hasPrefix:@"#"]) - { - color = [UIColor colorWithHexString:value]; - } - else if ([(NSString *)value hasPrefix:@"rgb"]) - { - color = [UIColor colorWithRGBAString:value]; - } - else if ([(NSString *)value hasPrefix:@"hsl"]) - { - [NSException raise:@"invalid color format" - format:@"HSL color format not yet supported natively"]; - } - else if ([value isKindOfClass:[NSArray class]] && [(NSArray *)value count] == 4) - { - color = [UIColor colorWithRed:[value[0] floatValue] - green:[value[1] floatValue] - blue:[value[2] floatValue] - alpha:[value[3] floatValue]]; - } - else if ([[UIColor class] respondsToSelector:NSSelectorFromString([NSString stringWithFormat:@"%@Color", [(NSString *)value lowercaseString]])]) - { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Warc-performSelector-leaks" - - color = [[UIColor class] performSelector:NSSelectorFromString([NSString stringWithFormat:@"%@Color", [(NSString *)value lowercaseString]])]; - -#pragma clang diagnostic pop - } - - return @{ @"type" : MGLStyleValueTypeColor, - @"value" : color }; - } - - return nil; -} - -- (void)setStyleDescription:(NSDictionary *)styleDescription forLayer:(NSString *)layerName inClass:(NSString *)className -{ -#pragma unused(className) - - NSMutableDictionary *convertedStyle = [NSMutableDictionary dictionary]; - - for (NSString *key in [styleDescription allKeys]) - { - NSArray *styleParameters = nil; - - if ([[self.allowedStyleTypes[MGLStyleKeyGeneric] allKeys] containsObject:key]) - { - styleParameters = self.allowedStyleTypes[MGLStyleKeyGeneric][key]; - } - else - { - NSString *keyType = [self getKeyTypeForLayer:layerName]; - - if ([[self.allowedStyleTypes[keyType] allKeys] containsObject:key]) - { - styleParameters = self.allowedStyleTypes[keyType][key]; - } - } - - if (styleParameters) - { - if ([styleDescription[key][@"value"] isKindOfClass:[MGLStyleFunctionValue class]]) - { - convertedStyle[key] = [(MGLStyleFunctionValue *)styleDescription[key][@"value"] rawStyle]; - } - else if ([styleParameters containsObject:styleDescription[key][@"type"]]) - { - NSString *valueType = styleDescription[key][@"type"]; - - if ([valueType isEqualToString:MGLStyleValueTypeColor]) - { - convertedStyle[key] = [@"#" stringByAppendingString:[(UIColor *)styleDescription[key][@"value"] hexStringFromColor]]; - } - else - { - // the rest (bool/number/pair/string) are already JSON-convertible types - // - convertedStyle[key] = styleDescription[key][@"value"]; - } - } - } - else - { - [NSException raise:@"invalid style description format" - format:@"unable to parse key '%@'", - key]; - } - } - -// NSMutableDictionary *style = [[self getRawStyle] deepMutableCopy]; -// -// NSUInteger classIndex = [[[self getAllStyleClasses] valueForKey:@"name"] indexOfObject:className]; -// -// style[@"classes"][classIndex][@"layers"][layerName] = convertedStyle; -// -// [self setRawStyle:style]; -} - -- (NSDictionary *)allowedStyleTypes -{ - static NSDictionary *MGLStyleAllowedTypes = @{ - MGLStyleKeyGeneric : @{ - @"enabled" : @[ MGLStyleValueTypeBoolean, MGLStyleValueFunctionAllowed ], - @"translate" : @[ MGLStyleValueTypeNumberPair, MGLStyleValueFunctionAllowed ], - @"translate-anchor" : @[ MGLStyleValueTypeString, MGLStyleValueFunctionAllowed ], - @"opacity" : @[ MGLStyleValueTypeNumber, MGLStyleValueFunctionAllowed ], - @"prerender" : @[ MGLStyleValueTypeBoolean ], - @"prerender-buffer" : MGLStyleValueTypeNumber, - @"prerender-size" : @[ MGLStyleValueTypeNumber ], - @"prerender-blur" : @[ MGLStyleValueTypeNumber ] }, - MGLStyleKeyFill : @{ - @"color" : @[ MGLStyleValueTypeColor ], - @"stroke" : @[ MGLStyleValueTypeColor ], - @"antialias" : @[ MGLStyleValueTypeBoolean ], - @"image" : @[ MGLStyleValueTypeString ] }, - MGLStyleKeyLine : @{ - @"color" : @[ MGLStyleValueTypeColor ], - @"width" : @[ MGLStyleValueTypeNumber, MGLStyleValueFunctionAllowed ], - @"dasharray" : @[ MGLStyleValueTypeNumberPair, MGLStyleValueFunctionAllowed ] }, - MGLStyleKeyIcon : @{ - @"color" : @[ MGLStyleValueTypeColor ], - @"image" : @[ MGLStyleValueTypeString ], - @"size" : @[ MGLStyleValueTypeNumber, MGLStyleValueFunctionAllowed ], - @"radius" : @[ MGLStyleValueTypeNumber, MGLStyleValueFunctionAllowed], - @"blur" : @[ MGLStyleValueTypeNumber, MGLStyleValueFunctionAllowed ] }, - MGLStyleKeyText : @{ - @"color" : @[ MGLStyleValueTypeColor ], - @"stroke" : @[ MGLStyleValueTypeColor ], - @"strokeWidth" : @[ MGLStyleValueTypeNumber, MGLStyleValueFunctionAllowed ], - @"strokeBlur" : @[ MGLStyleValueTypeNumber, MGLStyleValueFunctionAllowed ], - @"size" : @[ MGLStyleValueTypeNumber, MGLStyleValueFunctionAllowed ], - @"rotate" : @[ MGLStyleValueTypeNumber, MGLStyleValueFunctionAllowed ], - @"alwaysVisible" : @[ MGLStyleValueTypeBoolean ] }, - MGLStyleKeyRaster : @{}, - MGLStyleKeyComposite : @{}, - MGLStyleKeyBackground : @{ - @"color" : @[ MGLStyleValueTypeColor ] } - }; - - return MGLStyleAllowedTypes; -} - #pragma mark - Annotations - - (NSArray *)annotations { - if ([_annotationsStore count]) + if ([_annotationIDsByAnnotation count]) { NSMutableArray *result = [NSMutableArray array]; - NSEnumerator *keyEnumerator = [_annotationsStore keyEnumerator]; + NSEnumerator *keyEnumerator = [_annotationIDsByAnnotation keyEnumerator]; id annotation; while (annotation = [keyEnumerator nextObject]) @@ -1688,15 +1415,15 @@ CLLocationCoordinate2D latLngToCoordinate(mbgl::LatLng latLng) symbolName = [self.delegate mapView:self symbolNameForAnnotation:annotation]; } - symbols.push_back((symbolName ? [symbolName cStringUsingEncoding:[NSString defaultCStringEncoding]] : "")); + symbols.push_back((symbolName ? [symbolName UTF8String] : "")); } 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]]; + [self.annotationIDsByAnnotation setObject:@{ MGLAnnotationIDKey : @(annotationIDs[i]) } + forKey:annotations[i]]; } } @@ -1722,8 +1449,14 @@ CLLocationCoordinate2D latLngToCoordinate(mbgl::LatLng latLng) { assert([annotation conformsToProtocol:@protocol(MGLAnnotation)]); - annotationIDsToRemove.push_back([[[self.annotationsStore objectForKey:annotation] objectForKey:MGLAnnotationIDKey] unsignedIntValue]); - [self.annotationsStore removeObjectForKey:annotation]; + annotationIDsToRemove.push_back([[[self.annotationIDsByAnnotation objectForKey:annotation] + objectForKey:MGLAnnotationIDKey] unsignedIntValue]); + [self.annotationIDsByAnnotation removeObjectForKey:annotation]; + + if (annotation == self.selectedAnnotation) + { + [self deselectAnnotation:annotation animated:NO]; + } } mbglMap->removeAnnotations(annotationIDsToRemove); @@ -1744,27 +1477,453 @@ CLLocationCoordinate2D latLngToCoordinate(mbgl::LatLng latLng) if ( ! [self viewportBounds].contains(coordinateToLatLng(firstAnnotation.coordinate))) return; - self.selectedAnnotation = firstAnnotation; + [self selectAnnotation:firstAnnotation animated:NO]; } - (void)selectAnnotation:(id )annotation animated:(BOOL)animated { - (void)animated; - if ( ! annotation) return; if ( ! [self viewportBounds].contains(coordinateToLatLng(annotation.coordinate))) return; + + if (annotation == self.selectedAnnotation) return; + + self.userTrackingMode = MGLUserTrackingModeNone; + + [self deselectAnnotation:self.selectedAnnotation animated:NO]; self.selectedAnnotation = annotation; + + if (annotation.title && [self.delegate respondsToSelector:@selector(mapView:annotationCanShowCallout:)] && + [self.delegate mapView:self annotationCanShowCallout:annotation]) + { + // build the callout + self.selectedAnnotationCalloutView = [self calloutViewForAnnotation:annotation]; + + CGRect calloutBounds; + + if ([annotation isEqual:self.userLocation]) + { + CGPoint calloutAnchorPoint = [self convertCoordinate:annotation.coordinate toPointToView:self]; + calloutBounds = CGRectMake(calloutAnchorPoint.x - 1, calloutAnchorPoint.y - 13, 0, 0); + } + else + { + // determine symbol in use for point + NSString *symbol = MGLDefaultStyleMarkerSymbolName; + if ([self.delegate respondsToSelector:@selector(mapView:symbolNameForAnnotation:)]) + { + symbol = [self.delegate mapView:self symbolNameForAnnotation:annotation]; + } + std::string symbolName([symbol UTF8String]); + + // determine anchor point based on symbol + CGPoint calloutAnchorPoint = [self convertCoordinate:annotation.coordinate toPointToView:self]; + double y = mbglMap->getTopOffsetPixelsForAnnotationSymbol(symbolName); + calloutBounds = CGRectMake(calloutAnchorPoint.x - 1, calloutAnchorPoint.y + y, 0, 0); + } + + // consult delegate for left and/or right accessory views + if ([self.delegate respondsToSelector:@selector(mapView:leftCalloutAccessoryViewForAnnotation:)]) + { + self.selectedAnnotationCalloutView.leftAccessoryView = + [self.delegate mapView:self leftCalloutAccessoryViewForAnnotation:annotation]; + + if ([self.selectedAnnotationCalloutView.leftAccessoryView isKindOfClass:[UIControl class]]) + { + UITapGestureRecognizer *calloutAccessoryTap = [[UITapGestureRecognizer alloc] initWithTarget:self + action:@selector(handleCalloutAccessoryTapGesture:)]; + + [self.selectedAnnotationCalloutView.leftAccessoryView addGestureRecognizer:calloutAccessoryTap]; + } + } + + if ([self.delegate respondsToSelector:@selector(mapView:rightCalloutAccessoryViewForAnnotation:)]) + { + self.selectedAnnotationCalloutView.rightAccessoryView = + [self.delegate mapView:self rightCalloutAccessoryViewForAnnotation:annotation]; + + if ([self.selectedAnnotationCalloutView.rightAccessoryView isKindOfClass:[UIControl class]]) + { + UITapGestureRecognizer *calloutAccessoryTap = [[UITapGestureRecognizer alloc] initWithTarget:self + action:@selector(handleCalloutAccessoryTapGesture:)]; + + [self.selectedAnnotationCalloutView.rightAccessoryView addGestureRecognizer:calloutAccessoryTap]; + } + } + + // present popup + [self.selectedAnnotationCalloutView presentCalloutFromRect:calloutBounds + inView:self.glView + constrainedToView:self.glView + animated:animated]; + } + + // notify delegate + if ([self.delegate respondsToSelector:@selector(mapView:didSelectAnnotation:)]) + { + [self.delegate mapView:self didSelectAnnotation:annotation]; + } +} + +- (SMCalloutView *)calloutViewForAnnotation:(id )annotation +{ + SMCalloutView *calloutView = [SMCalloutView platformCalloutView]; + + if ([annotation respondsToSelector:@selector(title)]) calloutView.title = annotation.title; + if ([annotation respondsToSelector:@selector(subtitle)]) calloutView.subtitle = annotation.subtitle; + + calloutView.tintColor = self.tintColor; + + return calloutView; } - (void)deselectAnnotation:(id )annotation animated:(BOOL)animated { - (void)animated; - if ( ! annotation) return; - if ([self.selectedAnnotation isEqual:annotation]) self.selectedAnnotation = nil; + if ([self.selectedAnnotation isEqual:annotation]) + { + // dismiss popup + [self.selectedAnnotationCalloutView dismissCalloutAnimated:animated]; + + // clean up + self.selectedAnnotationCalloutView = nil; + self.selectedAnnotation = nil; + } + + // notify delegate + if ([self.delegate respondsToSelector:@selector(mapView:didDeselectAnnotation:)]) + { + [self.delegate mapView:self didDeselectAnnotation:annotation]; + } +} + +#pragma mark - User Location - + +- (void)setShowsUserLocation:(BOOL)showsUserLocation +{ + if (showsUserLocation == _showsUserLocation) return; + + _showsUserLocation = showsUserLocation; + + if (showsUserLocation) + { + if ([self.delegate respondsToSelector:@selector(mapViewWillStartLocatingUser:)]) + { + [self.delegate mapViewWillStartLocatingUser:self]; + } + + self.userLocationAnnotationView = [[MGLUserLocationAnnotationView alloc] initInMapView:self]; + + self.locationManager = [CLLocationManager new]; + +#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000 + // enable iOS 8+ location authorization API + // + if ([CLLocationManager instancesRespondToSelector:@selector(requestWhenInUseAuthorization)]) + { + BOOL hasLocationDescription = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"] || + [[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysUsageDescription"]; + NSAssert(hasLocationDescription, + @"For iOS 8 and above, your app must have a value for NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription in its Info.plist"); + [self.locationManager requestWhenInUseAuthorization]; + } +#endif + + self.locationManager.headingFilter = 5.0; + self.locationManager.delegate = self; + [self.locationManager startUpdatingLocation]; + } + else + { + [self.locationManager stopUpdatingLocation]; + [self.locationManager stopUpdatingHeading]; + self.locationManager.delegate = nil; + self.locationManager = nil; + + if ([self.delegate respondsToSelector:@selector(mapViewDidStopLocatingUser:)]) + { + [self.delegate mapViewDidStopLocatingUser:self]; + } + + [self setUserTrackingMode:MGLUserTrackingModeNone animated:YES]; + + [self.userLocationAnnotationView removeFromSuperview]; + self.userLocationAnnotationView = nil; + } +} + +- (void)setUserLocationAnnotationView:(MGLUserLocationAnnotationView *)newAnnotationView +{ + if ( ! [newAnnotationView isEqual:_userLocationAnnotationView]) + { + _userLocationAnnotationView = newAnnotationView; + } +} + ++ (NSSet *)keyPathsForValuesAffectingUserLocation +{ + return [NSSet setWithObject:@"userLocationAnnotationView"]; +} + +- (MGLUserLocation *)userLocation +{ + return self.userLocationAnnotationView.annotation; +} + +- (BOOL)isUserLocationVisible +{ + if (self.userLocationAnnotationView) + { + CGPoint locationPoint = [self convertCoordinate:self.userLocation.coordinate toPointToView:self]; + + CGRect locationRect = CGRectMake(locationPoint.x - self.userLocation.location.horizontalAccuracy, + locationPoint.y - self.userLocation.location.horizontalAccuracy, + self.userLocation.location.horizontalAccuracy * 2, + self.userLocation.location.horizontalAccuracy * 2); + + return CGRectIntersectsRect([self bounds], locationRect); + } + + return NO; +} + +- (void)setUserTrackingMode:(MGLUserTrackingMode)mode +{ + [self setUserTrackingMode:mode animated:YES]; +} + +- (void)setUserTrackingMode:(MGLUserTrackingMode)mode animated:(BOOL)animated +{ + if (mode == _userTrackingMode) return; + + if (mode == MGLUserTrackingModeFollowWithHeading && ! CLLocationCoordinate2DIsValid(self.userLocation.coordinate)) + { + mode = MGLUserTrackingModeNone; + } + + _userTrackingMode = mode; + + switch (_userTrackingMode) + { + case MGLUserTrackingModeNone: + default: + { + [self.locationManager stopUpdatingHeading]; + + break; + } + case MGLUserTrackingModeFollow: + { + self.showsUserLocation = YES; + + [self.locationManager stopUpdatingHeading]; + + if (self.userLocationAnnotationView) + { + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wdeprecated-declarations" + [self locationManager:self.locationManager didUpdateToLocation:self.userLocation.location fromLocation:self.userLocation.location]; + #pragma clang diagnostic pop + } + + break; + } + case MGLUserTrackingModeFollowWithHeading: + { + self.showsUserLocation = YES; + + if (self.zoomLevel < 3) [self setZoomLevel:3 animated:YES]; + + if (self.userLocationAnnotationView) + { + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wdeprecated-declarations" + [self locationManager:self.locationManager didUpdateToLocation:self.userLocation.location fromLocation:self.userLocation.location]; + #pragma clang diagnostic pop + } + + [self updateHeadingForDeviceOrientation]; + + [self.locationManager startUpdatingHeading]; + + break; + } + } + + if ([self.delegate respondsToSelector:@selector(mapView:didChangeUserTrackingMode:animated:)]) + { + [self.delegate mapView:self didChangeUserTrackingMode:_userTrackingMode animated:animated]; + } +} + +- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation +{ + (void)manager; + + if ( ! _showsUserLocation || ! newLocation || ! CLLocationCoordinate2DIsValid(newLocation.coordinate)) return; + + if ([newLocation distanceFromLocation:oldLocation] || ! oldLocation) + { + self.userLocation.location = newLocation; + + // deselect user if applicable since we don't do callout tracking yet + if ([self.selectedAnnotation isEqual:self.userLocation]) [self deselectAnnotation:self.userLocation animated:NO]; + + if ([self.delegate respondsToSelector:@selector(mapView:didUpdateUserLocation:)]) + { + [self.delegate mapView:self didUpdateUserLocation:self.userLocation]; + } + } + + if (self.userTrackingMode != MGLUserTrackingModeNone) + { + // center on user location unless we're already centered there (or very close) + // + CGPoint mapCenterPoint = [self convertPoint:self.center fromView:self.superview]; + CGPoint userLocationPoint = [self convertCoordinate:self.userLocation.coordinate toPointToView:self]; + + if (std::abs(userLocationPoint.x - mapCenterPoint.x) > 1.0 || std::abs(userLocationPoint.y - mapCenterPoint.y) > 1.0) + { + if (round(self.zoomLevel) >= 10) + { + // at sufficient detail, just re-center the map; don't zoom + // + [self setCenterCoordinate:self.userLocation.location.coordinate animated:YES preservingTracking:YES]; + } + else + { + // otherwise re-center and zoom in to near accuracy confidence + // + float delta = (newLocation.horizontalAccuracy / 110000) * 1.2; // approx. meter per degree latitude, plus some margin + + CLLocationCoordinate2D desiredSouthWest = CLLocationCoordinate2DMake(newLocation.coordinate.latitude - delta, + newLocation.coordinate.longitude - delta); + + CLLocationCoordinate2D desiredNorthEast = CLLocationCoordinate2DMake(newLocation.coordinate.latitude + delta, + newLocation.coordinate.longitude + delta); + + CGFloat pixelRadius = fminf(self.bounds.size.width, self.bounds.size.height) / 2; + + CLLocationCoordinate2D actualSouthWest = [self convertPoint:CGPointMake(userLocationPoint.x - pixelRadius, + userLocationPoint.y - pixelRadius) + toCoordinateFromView:self]; + + CLLocationCoordinate2D actualNorthEast = [self convertPoint:CGPointMake(userLocationPoint.x + pixelRadius, + userLocationPoint.y + pixelRadius) + toCoordinateFromView:self]; + + if (desiredNorthEast.latitude != actualNorthEast.latitude || + desiredNorthEast.longitude != actualNorthEast.longitude || + desiredSouthWest.latitude != actualSouthWest.latitude || + desiredSouthWest.longitude != actualSouthWest.longitude) + { + // assumes we won't disrupt tracking mode + [self zoomToSouthWestCoordinate:desiredSouthWest northEastCoordinate:desiredNorthEast animated:YES]; + } + } + } + } + + self.userLocationAnnotationView.haloLayer.hidden = ! CLLocationCoordinate2DIsValid(self.userLocation.coordinate) || + newLocation.horizontalAccuracy > 10; + + [self updateUserLocationAnnotationView]; +} + +- (BOOL)locationManagerShouldDisplayHeadingCalibration:(CLLocationManager *)manager +{ + (void)manager; + + if (self.displayHeadingCalibration) [self.locationManager performSelector:@selector(dismissHeadingCalibrationDisplay) + withObject:nil + afterDelay:10.0]; + + return self.displayHeadingCalibration; +} + +- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading +{ + (void)manager; + + if ( ! _showsUserLocation || self.pan.state == UIGestureRecognizerStateBegan || newHeading.headingAccuracy < 0) return; + + self.userLocation.heading = newHeading; + + if ([self.delegate respondsToSelector:@selector(mapView:didUpdateUserLocation:)]) + { + [self.delegate mapView:self didUpdateUserLocation:self.userLocation]; + + if ( ! _showsUserLocation) return; + } + + CLLocationDirection headingDirection = (newHeading.trueHeading > 0 ? newHeading.trueHeading : newHeading.magneticHeading); + + if (headingDirection > 0 && self.userTrackingMode == MGLUserTrackingModeFollowWithHeading) + { + mbglMap->setBearing(headingDirection, secondsAsDuration(MGLAnimationDuration)); + } +} + +- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status +{ + (void)manager; + + if (status == kCLAuthorizationStatusDenied || status == kCLAuthorizationStatusRestricted) + { + self.userTrackingMode = MGLUserTrackingModeNone; + self.showsUserLocation = NO; + } +} + +- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error +{ + (void)manager; + + if ([error code] == kCLErrorDenied) + { + self.userTrackingMode = MGLUserTrackingModeNone; + self.showsUserLocation = NO; + + if ([self.delegate respondsToSelector:@selector(mapView:didFailToLocateUserWithError:)]) + { + [self.delegate mapView:self didFailToLocateUserWithError:error]; + } + } +} + +- (void)updateHeadingForDeviceOrientation +{ + if (self.locationManager) + { + // note that right/left device and interface orientations are opposites (see UIApplication.h) + // + switch ([[UIApplication sharedApplication] statusBarOrientation]) + { + case (UIInterfaceOrientationLandscapeLeft): + { + self.locationManager.headingOrientation = CLDeviceOrientationLandscapeRight; + break; + } + case (UIInterfaceOrientationLandscapeRight): + { + self.locationManager.headingOrientation = CLDeviceOrientationLandscapeLeft; + break; + } + case (UIInterfaceOrientationPortraitUpsideDown): + { + self.locationManager.headingOrientation = CLDeviceOrientationPortraitUpsideDown; + break; + } + case (UIInterfaceOrientationPortrait): + default: + { + self.locationManager.headingOrientation = CLDeviceOrientationPortrait; + break; + } + } + } } #pragma mark - Utility - @@ -1844,6 +2003,11 @@ CLLocationCoordinate2D latLngToCoordinate(mbgl::LatLng latLng) case mbgl::MapChangeRegionWillChange: case mbgl::MapChangeRegionWillChangeAnimated: { + [self updateUserLocationAnnotationView]; + [self updateCompass]; + + [self deselectAnnotation:self.selectedAnnotation animated:NO]; + BOOL animated = ([change unsignedIntegerValue] == mbgl::MapChangeRegionWillChangeAnimated); @synchronized (self.regionChangeDelegateQueue) @@ -1874,9 +2038,20 @@ CLLocationCoordinate2D latLngToCoordinate(mbgl::LatLng latLng) } break; } + case mbgl::MapChangeRegionIsChanging: + { + [self updateUserLocationAnnotationView]; + [self updateCompass]; + + if ([self.delegate respondsToSelector:@selector(mapViewRegionIsChanging:)]) + { + [self.delegate mapViewRegionIsChanging:self]; + } + } case mbgl::MapChangeRegionDidChange: case mbgl::MapChangeRegionDidChangeAnimated: { + [self updateUserLocationAnnotationView]; [self updateCompass]; if (self.pan.state == UIGestureRecognizerStateChanged || @@ -1942,6 +2117,32 @@ CLLocationCoordinate2D latLngToCoordinate(mbgl::LatLng latLng) } } +- (void)updateUserLocationAnnotationView +{ + if ( ! CLLocationCoordinate2DIsValid(self.userLocation.coordinate)) { + self.userLocationAnnotationView.layer.hidden = YES; + return; + } + + if ( ! self.userLocationAnnotationView.superview) [self.glView addSubview:self.userLocationAnnotationView]; + + CGPoint userPoint = [self convertCoordinate:self.userLocation.coordinate toPointToView:self]; + + if (CGRectContainsPoint(CGRectInset(self.bounds, -MGLAnnotationUpdateViewportOutset.width, + -MGLAnnotationUpdateViewportOutset.height), userPoint)) + { + self.userLocationAnnotationView.center = userPoint; + + self.userLocationAnnotationView.layer.hidden = NO; + + [self.userLocationAnnotationView setupLayers]; + } + else + { + self.userLocationAnnotationView.layer.hidden = YES; + } +} + - (void)updateCompass { double degrees = mbglMap->getBearing() * -1; @@ -1993,8 +2194,11 @@ CLLocationCoordinate2D latLngToCoordinate(mbgl::LatLng latLng) - (void)invalidate { - // This is run in the main/UI thread. + assert([[NSThread currentThread] isMainThread]); + [self.glView setNeedsDisplay]; + + [self notifyMapChange:@(mbgl::MapChangeRegionIsChanging)]; } class MBGLView : public mbgl::View @@ -2022,12 +2226,9 @@ class MBGLView : public mbgl::View } else { - dispatch_async(dispatch_get_main_queue(), ^ - { - [nativeView performSelector:@selector(notifyMapChange:) - withObject:@(change) - afterDelay:0]; - }); + assert([[NSThread currentThread] isMainThread]); + + [nativeView notifyMapChange:@(change)]; } } diff --git a/platform/ios/MGLMapboxEvents.m b/platform/ios/MGLMapboxEvents.m index a231b5115..7b810d5cd 100644 --- a/platform/ios/MGLMapboxEvents.m +++ b/platform/ios/MGLMapboxEvents.m @@ -1,42 +1,99 @@ -// -// MapboxEvents.m -// MapboxEvents -// -// Dynamic detection of ASIdentifierManager from Mixpanel -// https://github.com/mixpanel/mixpanel-iphone/blob/master/LICENSE -// -// Created by Brad Leege on 3/5/15. -// Copyright (c) 2015 Mapbox. All rights reserved. -// - #import "MGLMapboxEvents.h" + #import +#import #import #import + +#import "MGLMetricsLocationManager.h" + #include -#import + +static NSString *const MGLMapboxEventsUserAgent = @"MapboxEventsiOS/1.0"; +static NSString *const MGLMapboxEventsAPIBase = @"https://api.tiles.mapbox.com"; + +NSString *const MGLEventTypeMapLoad = @"map.load"; +NSString *const MGLEventTypeMapTap = @"map.click"; +NSString *const MGLEventTypeMapDragEnd = @"map.dragend"; +NSString *const MGLEventTypeLocation = @"Location"; + +NSString *const MGLEventKeyLatitude = @"lat"; +NSString *const MGLEventKeyLongitude = @"lng"; +NSString *const MGLEventKeyZoomLevel = @"zoom"; +NSString *const MGLEventKeyPushEnabled = @"enabled.push"; +NSString *const MGLEventKeyEmailEnabled = @"enabled.email"; +NSString *const MGLEventKeyGestureID = @"gesture"; + +NSString *const MGLEventGestureSingleTap = @"SingleTap"; +NSString *const MGLEventGestureDoubleTap = @"DoubleTap"; +NSString *const MGLEventGestureTwoFingerSingleTap = @"TwoFingerTap"; +NSString *const MGLEventGestureQuickZoom = @"QuickZoom"; +NSString *const MGLEventGesturePanStart = @"Pan"; +NSString *const MGLEventGesturePinchStart = @"Pinch"; +NSString *const MGLEventGestureRotateStart = @"Rotation"; + +// +// Threadsafety conventions: +// +// All variables accessed from more than one thread are +// designated `atomic` and accessed through dot syntax. The +// main thread uses underscore syntax during the +// initialization of the variable. +// +// All variables accessed outside of initialization and +// from within a single thread use underscore syntax. +// +// All captures of `self` from within asynchronous +// dispatches will use a `weakSelf` to avoid cyclical +// strong references. +// @interface MGLMapboxEvents() -@property (atomic) NSMutableArray *queue; -@property (atomic) NSString *instance; -@property (atomic) NSString *anonid; -@property (atomic) NSTimer *timer; +// All of the following properties are written to only from +// the main thread, but can be read on any thread. +// +@property (atomic) NSString *token; +@property (atomic) NSString *appName; +@property (atomic) NSString *appVersion; +@property (atomic) NSString *instanceID; +@property (atomic) NSString *advertiserId; +@property (atomic) NSString *vendorId; +@property (atomic) NSString *appBundleId; @property (atomic) NSString *userAgent; +@property (atomic) NSString *model; +@property (atomic) NSString *iOSVersion; +@property (atomic) NSString *carrier; +@property (atomic) NSUInteger flushAt; +@property (atomic) NSDateFormatter *rfc3339DateFormatter; +@property (atomic) CGFloat scale; + +// The timer is only ever accessed from the main thread. +// +@property (nonatomic) NSTimer *timer; + +// The flush expiration time is only ever accessed from the main thread. +// +@property (nonatomic) NSTimeInterval flushAfter; + +// This is an array of events to push. All access to it will be +// from our own serial queue. +// +@property (nonatomic) NSMutableArray *eventQueue; + +// This is a custom serial queue for accessing the event queue. +// +@property (nonatomic) dispatch_queue_t serialQueue; @end @implementation MGLMapboxEvents -static MGLMapboxEvents *sharedManager = nil; +// Must be called from the main thread. Only called internally. +// +- (instancetype) init { + assert([[NSThread currentThread] isMainThread]); -NSDateFormatter *rfc3339DateFormatter = nil; -NSString *model; -NSString *iOSVersion; -NSString *carrier; -NSNumber *scale; - -- (id) init { self = [super init]; if (self) { @@ -45,6 +102,8 @@ NSNumber *scale; if(!settingsBundle) { NSLog(@"Could not find Settings.bundle"); } else { + // Dynamic Settings.bundle loading based on: + // http://stackoverflow.com/questions/510216/can-you-make-the-settings-in-settings-bundle-default-even-if-you-dont-open-the NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:@"Root.plist"]]; NSArray *preferences = [settings objectForKey:@"PreferenceSpecifiers"]; NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]]; @@ -57,14 +116,19 @@ NSNumber *scale; [[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister]; } - + _appBundleId = [[NSBundle mainBundle] bundleIdentifier]; + NSString *uniqueID = [[NSProcessInfo processInfo] globallyUniqueString]; + _serialQueue = dispatch_queue_create([[NSString stringWithFormat:@"%@.%@.events.serial", _appBundleId, uniqueID] UTF8String], DISPATCH_QUEUE_SERIAL); + // Configure Events Infrastructure - _queue = [[NSMutableArray alloc] init]; + _eventQueue = [[NSMutableArray alloc] init]; _flushAt = 20; - _flushAfter = 10000; - _api = @"https://api.tiles.mapbox.com"; + _flushAfter = 60; _token = nil; - _instance = [[NSUUID UUID] UUIDString]; + _instanceID = [[NSUUID UUID] UUIDString]; + // Dynamic detection of ASIdentifierManager from Mixpanel + // https://github.com/mixpanel/mixpanel-iphone/blob/master/LICENSE + _advertiserId = @""; Class ASIdentifierManagerClass = NSClassFromString(@"ASIdentifierManager"); if (ASIdentifierManagerClass) { SEL sharedManagerSelector = NSSelectorFromString(@"sharedManager"); @@ -75,232 +139,348 @@ NSNumber *scale; if (trackingEnabled) { SEL advertisingIdentifierSelector = NSSelectorFromString(@"advertisingIdentifier"); NSUUID *uuid = ((NSUUID* (*)(id, SEL))[sharedManager methodForSelector:advertisingIdentifierSelector])(sharedManager, advertisingIdentifierSelector); - _anonid = [uuid UUIDString]; - } else { - _anonid = [[[UIDevice currentDevice] identifierForVendor] UUIDString]; + _advertiserId = [uuid UUIDString]; } - } else { - _anonid = [[[UIDevice currentDevice] identifierForVendor] UUIDString]; } + _vendorId = [[[UIDevice currentDevice] identifierForVendor] UUIDString]; - model = [self getSysInfoByName:"hw.machine"]; - iOSVersion = [NSString stringWithFormat:@"%@ %@", [UIDevice currentDevice].systemName, [UIDevice currentDevice].systemVersion]; + _model = [self getSysInfoByName:"hw.machine"]; + _iOSVersion = [NSString stringWithFormat:@"%@ %@", [UIDevice currentDevice].systemName, [UIDevice currentDevice].systemVersion]; if ([UIScreen instancesRespondToSelector:@selector(nativeScale)]) { - scale = [[NSNumber alloc] initWithFloat:[UIScreen mainScreen].nativeScale]; + _scale = [UIScreen mainScreen].nativeScale; } else { - scale = [[NSNumber alloc] initWithFloat:[UIScreen mainScreen].scale]; + _scale = [UIScreen mainScreen].scale; } CTCarrier *carrierVendor = [[[CTTelephonyNetworkInfo alloc] init] subscriberCellularProvider]; - carrier = [carrierVendor carrierName]; + _carrier = [carrierVendor carrierName]; - _userAgent = @"MapboxEventsiOS/1.0"; + _userAgent = MGLMapboxEventsUserAgent; // Setup Date Format - rfc3339DateFormatter = [[NSDateFormatter alloc] init]; + _rfc3339DateFormatter = [[NSDateFormatter alloc] init]; NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; - [rfc3339DateFormatter setLocale:enUSPOSIXLocale]; - [rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"]; - [rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; + [_rfc3339DateFormatter setLocale:enUSPOSIXLocale]; + [_rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"]; + [_rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; } return self; } -+ (id)sharedManager { +// Can be called from any thread. Called implicitly from any +// public class convenience methods. +// ++ (instancetype)sharedManager { static dispatch_once_t onceToken; + static MGLMapboxEvents *_sharedManager; dispatch_once(&onceToken, ^{ - sharedManager = [[self alloc] init]; + void (^setupBlock)() = ^{ + _sharedManager = [[self alloc] init]; + // setup dedicated location manager on first use + [MGLMetricsLocationManager sharedManager]; + }; + if ( ! [[NSThread currentThread] isMainThread]) { + dispatch_sync(dispatch_get_main_queue(), ^{ + setupBlock(); + }); + } else { + setupBlock(); + } }); - return sharedManager; + return _sharedManager; } +// Must be called from the main thread. +// ++ (void) setToken:(NSString *)token { + assert([[NSThread currentThread] isMainThread]); + [MGLMapboxEvents sharedManager].token = token; +} + +// Must be called from the main thread. +// ++ (void) setAppName:(NSString *)appName { + assert([[NSThread currentThread] isMainThread]); + [MGLMapboxEvents sharedManager].appName = appName; +} + +// Must be called from the main thread. +// ++ (void) setAppVersion:(NSString *)appVersion { + assert([[NSThread currentThread] isMainThread]); + [MGLMapboxEvents sharedManager].appVersion = appVersion; +} + +// Can be called from any thread. Can be called rapidly from +// the UI thread, so performance is paramount. +// ++ (void) pushEvent:(NSString *)event withAttributes:(NSDictionary *)attributeDictionary { + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ + [[MGLMapboxEvents sharedManager] pushEvent:event withAttributes:attributeDictionary]; + }); +} + +// Can be called from any thread. Called implicitly from public +// use of +pushEvent:withAttributes:. +// - (void) pushEvent:(NSString *)event withAttributes:(NSDictionary *)attributeDictionary { - - // Opt Out Checking When Built - if (![[NSUserDefaults standardUserDefaults] boolForKey:@"mapbox_metrics_enabled_preference"]) { - NSLog(@"Mapbox Metrics are not enabled, so clear any currently stored events, and return without sending in data."); - [_queue removeAllObjects]; - return; - } + __weak MGLMapboxEvents *weakSelf = self; - // Add Metrics Disabled App Wide Check - if ([[NSUserDefaults standardUserDefaults] objectForKey:@"mapbox_metrics_disabled"] != nil) { - NSLog(@"Mapbox Metrics have been disabled for this app."); - [_queue removeAllObjects]; - return; - } - - if (!event) { - return; - } - - NSMutableDictionary *evt = [[NSMutableDictionary alloc] init]; - // mapbox-events stock attributes - [evt setObject:event forKey:@"event"]; - [evt setObject:[NSNumber numberWithInt:1] forKey:@"version"]; - [evt setObject:[self formatDate:[NSDate date]] forKey:@"created"]; - [evt setObject:self.instance forKey:@"instance"]; - [evt setObject:self.anonid forKey:@"anonid"]; - - // mapbox-events-ios stock attributes - [evt setValue:[rfc3339DateFormatter stringFromDate:[NSDate date]] forKey:@"deviceTimestamp"]; - [evt setValue:model forKey:@"model"]; - [evt setValue:iOSVersion forKey:@"operatingSystem"]; - [evt setValue:[self getDeviceOrientation] forKey:@"orientation"]; - [evt setValue:[[NSNumber alloc] initWithFloat:(100 * [UIDevice currentDevice].batteryLevel)] forKey:@"batteryLevel"]; - [evt setValue:scale forKey:@"resolution"]; - [evt setValue:carrier forKey:@"carrier"]; - [evt setValue:[self getWifiNetworkName] forKey:@"wifi"]; - [evt setValue:[NSNumber numberWithInt:[self getContentSizeScale]] forKey:@"accessibilityFontScale"]; - - for (NSString *key in [attributeDictionary allKeys]) { - [evt setObject:[attributeDictionary valueForKey:key] forKey:key]; - } - - // Make Immutable Version - NSDictionary *finalEvent = [NSDictionary dictionaryWithDictionary:evt]; - - // Put On The Queue - [self.queue addObject:finalEvent]; - - // Has Flush Limit Been Reached? - if ((int)_queue.count >= (int)_flushAt) { - [self flush]; - } - - // Reset Timer (Initial Starting of Timer after first event is pushed) - [self startTimer]; -} - -- (void) flush { - if (_token == nil) { - NSLog(@"token hasn't been set yet, so no events can be sent. return"); - return; - } - - int upper = (int)_flushAt; - if (_flushAt > [_queue count]) { - if ([_queue count] == 0) { + dispatch_async(_serialQueue, ^{ + // Opt Out Checking When Built + if (![[NSUserDefaults standardUserDefaults] boolForKey:@"mapbox_metrics_enabled_preference"]) { + [_eventQueue removeAllObjects]; return; } - upper = (int)[_queue count]; - } - - // Create Array of Events to push to the Server - NSRange theRange = NSMakeRange(0, upper); - NSArray *events = [_queue subarrayWithRange:theRange]; - - // Update Queue to remove events sent to server - [_queue removeObjectsInRange:theRange]; - - // Send Array of Events to Server - [self postEvents:events]; - -} -- (void) postEvents:(NSArray *)events { - // Setup URL Request - NSString *url = [NSString stringWithFormat:@"%@/events/v1?access_token=%@", _api, _token]; - NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]]; - [request setValue:[self getUserAgent] forHTTPHeaderField:@"User-Agent"]; - [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; - [request setHTTPMethod:@"POST"]; - - // Convert Array of Dictionaries to JSON - if ([NSJSONSerialization isValidJSONObject:events]) { - NSData *jsonData = [NSJSONSerialization dataWithJSONObject:events options:NSJSONWritingPrettyPrinted error:nil]; - [request setHTTPBody:jsonData]; + // Add Metrics Disabled App Wide Check + if ([[NSUserDefaults standardUserDefaults] objectForKey:@"mapbox_metrics_disabled"] != nil) { + [_eventQueue removeAllObjects]; + return; + } - // Send non blocking HTTP Request to server - [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:nil]; - } + if (!event) return; + + NSMutableDictionary *evt = [[NSMutableDictionary alloc] initWithDictionary:attributeDictionary]; + // mapbox-events stock attributes + [evt setObject:event forKey:@"event"]; + [evt setObject:@(1) forKey:@"version"]; + [evt setObject:[weakSelf formatDate:[NSDate date]] forKey:@"created"]; + [evt setObject:weakSelf.instanceID forKey:@"instance"]; + [evt setObject:weakSelf.advertiserId forKey:@"advertiserId"]; + [evt setObject:weakSelf.vendorId forKey:@"vendorId"]; + [evt setObject:weakSelf.appBundleId forKeyedSubscript:@"appBundleId"]; + + // mapbox-events-ios stock attributes + [evt setValue:[weakSelf.rfc3339DateFormatter stringFromDate:[NSDate date]] forKey:@"created"]; + [evt setValue:weakSelf.model forKey:@"model"]; + [evt setValue:weakSelf.iOSVersion forKey:@"operatingSystem"]; + [evt setValue:[weakSelf getDeviceOrientation] forKey:@"orientation"]; + [evt setValue:@(100 * [UIDevice currentDevice].batteryLevel) forKey:@"batteryLevel"]; + [evt setValue:@(weakSelf.scale) forKey:@"resolution"]; + [evt setValue:weakSelf.carrier forKey:@"carrier"]; + [evt setValue:[weakSelf getCurrentCellularNetworkConnectionType] forKey:@"cellularNetworkType"]; + [evt setValue:[weakSelf getWifiNetworkName] forKey:@"wifi"]; + [evt setValue:@([weakSelf getContentSizeScale]) forKey:@"accessibilityFontScale"]; + + // Make Immutable Version + NSDictionary *finalEvent = [NSDictionary dictionaryWithDictionary:evt]; + + // Put On The Queue + [_eventQueue addObject:finalEvent]; + + // Has Flush Limit Been Reached? + if (_eventQueue.count >= weakSelf.flushAt) { + [weakSelf flush]; + } + + // Reset Timer (Initial Starting of Timer after first event is pushed) + [weakSelf startTimer]; + }); } +// Can be called from any thread. +// ++ (void) flush { + [[MGLMapboxEvents sharedManager] flush]; +} + +// Can be called from any thread. +// +- (void) flush { + if (self.token == nil) return; + + __weak MGLMapboxEvents *weakSelf = self; + + dispatch_async(_serialQueue, ^{ + __block NSArray *events; + + NSUInteger upper = weakSelf.flushAt; + if (weakSelf.flushAt > [_eventQueue count]) { + if ([_eventQueue count] == 0) { + return; + } + upper = [_eventQueue count]; + } + + // Create Array of Events to push to the Server + NSRange theRange = NSMakeRange(0, upper); + events = [_eventQueue subarrayWithRange:theRange]; + + // Update Queue to remove events sent to server + [_eventQueue removeObjectsInRange:theRange]; + + // Send Array of Events to Server + [weakSelf postEvents:events]; + }); +} + +// Can be called from any thread. Called implicitly from public +// use of +flush. Posts an async network request to upload metrics. +// +- (void) postEvents:(NSArray *)events { + __weak MGLMapboxEvents *weakSelf = self; + + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ + // Setup URL Request + NSString *url = [NSString stringWithFormat:@"%@/events/v1?access_token=%@", MGLMapboxEventsAPIBase, weakSelf.token]; + NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]]; + [request setValue:[weakSelf getUserAgent] forHTTPHeaderField:@"User-Agent"]; + [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; + [request setHTTPMethod:@"POST"]; + + // Convert Array of Dictionaries to JSON + if ([NSJSONSerialization isValidJSONObject:events]) { + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:events options:NSJSONWritingPrettyPrinted error:nil]; + [request setHTTPBody:jsonData]; + + // Send non blocking HTTP Request to server + [NSURLConnection sendAsynchronousRequest:request + queue:nil + completionHandler:nil]; + } + }); +} + +// Can be called from any thread. +// - (void) startTimer { - // Stop Timer if it already exists - if (_timer) { - [_timer invalidate]; - _timer = nil; + void (^timerBlock)() = ^{ + // Stop Timer if it already exists + if (_timer) { + [_timer invalidate]; + _timer = nil; + } + + // Start New Timer + _timer = [NSTimer scheduledTimerWithTimeInterval:_flushAfter + target:[self class] + selector:@selector(flush) + userInfo:nil + repeats:YES]; + }; + + if ( ! [[NSThread currentThread] isMainThread]) { + dispatch_sync(dispatch_get_main_queue(), ^{ + timerBlock(); + }); + } else { + timerBlock(); } - - // Start New Timer - NSTimeInterval interval = (double)((NSInteger)_flushAfter); - _timer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(flush) userInfo:nil repeats:YES]; } +// Can be called from any thread. +// - (NSString *) getUserAgent { - - if (_appName != nil && _appVersion != nil && ([_userAgent rangeOfString:_appName].location == NSNotFound)) { - _userAgent = [NSString stringWithFormat:@"%@/%@ %@", _appName, _appVersion, _userAgent]; + if (self.appName != nil && self.appVersion != nil && ([self.userAgent rangeOfString:self.appName].location == NSNotFound)) { + self.userAgent = [NSString stringWithFormat:@"%@/%@ %@", self.appName, self.appVersion, self.userAgent]; } - return _userAgent; + return self.userAgent; } +// Can be called from any thread. +// - (NSString *) formatDate:(NSDate *)date { - return [rfc3339DateFormatter stringFromDate:date]; + return [self.rfc3339DateFormatter stringFromDate:date]; } +// Can be called from any thread. +// - (NSString *) getDeviceOrientation { - switch ([UIDevice currentDevice].orientation) { - case UIDeviceOrientationUnknown: - return @"Unknown"; - break; - case UIDeviceOrientationPortrait: - return @"Portrait"; - break; - case UIDeviceOrientationPortraitUpsideDown: - return @"PortraitUpsideDown"; - break; - case UIDeviceOrientationLandscapeLeft: - return @"LandscapeLeft"; - break; - case UIDeviceOrientationLandscapeRight: - return @"LandscapeRight"; - break; - case UIDeviceOrientationFaceUp: - return @"FaceUp"; - break; - case UIDeviceOrientationFaceDown: - return @"FaceDown"; - break; - default: - return @"Default - Unknown"; - break; + __block NSString *result; + + NSString *(^deviceOrientationBlock)(void) = ^{ + switch ([UIDevice currentDevice].orientation) { + case UIDeviceOrientationUnknown: + result = @"Unknown"; + break; + case UIDeviceOrientationPortrait: + result = @"Portrait"; + break; + case UIDeviceOrientationPortraitUpsideDown: + result = @"PortraitUpsideDown"; + break; + case UIDeviceOrientationLandscapeLeft: + result = @"LandscapeLeft"; + break; + case UIDeviceOrientationLandscapeRight: + result = @"LandscapeRight"; + break; + case UIDeviceOrientationFaceUp: + result = @"FaceUp"; + break; + case UIDeviceOrientationFaceDown: + result = @"FaceDown"; + break; + default: + result = @"Default - Unknown"; + break; + } + + return result; + }; + + if ( ! [[NSThread currentThread] isMainThread]) { + dispatch_sync(dispatch_get_main_queue(), ^{ + result = deviceOrientationBlock(); + }); + } else { + result = deviceOrientationBlock(); } + + return result; } -- (int) getContentSizeScale { - NSString *sc = [UIApplication sharedApplication].preferredContentSizeCategory; - - if ([sc isEqualToString:UIContentSizeCategoryExtraSmall]) { - return -3; - } else if ([sc isEqualToString:UIContentSizeCategorySmall]) { - return -2; - } else if ([sc isEqualToString:UIContentSizeCategoryMedium]) { - return -1; - } else if ([sc isEqualToString:UIContentSizeCategoryLarge]) { - return 0; - } else if ([sc isEqualToString:UIContentSizeCategoryExtraLarge]) { - return 1; - } else if ([sc isEqualToString:UIContentSizeCategoryExtraExtraLarge]) { - return 2; - } else if ([sc isEqualToString:UIContentSizeCategoryExtraExtraExtraLarge]) { - return 3; - } else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityMedium]) { - return -11; - } else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityLarge]) { - return 10; - } else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityExtraLarge]) { - return 11; - } else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraLarge]) { - return 12; - } else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraExtraLarge]) { - return 13; +// Can be called from any thread. +// +- (NSInteger) getContentSizeScale { + __block NSInteger result = -9999; + + NSInteger (^contentSizeScaleBlock)(void) = ^{ + NSString *sc = [UIApplication sharedApplication].preferredContentSizeCategory; + + if ([sc isEqualToString:UIContentSizeCategoryExtraSmall]) { + result = -3; + } else if ([sc isEqualToString:UIContentSizeCategorySmall]) { + result = -2; + } else if ([sc isEqualToString:UIContentSizeCategoryMedium]) { + result = -1; + } else if ([sc isEqualToString:UIContentSizeCategoryLarge]) { + result = 0; + } else if ([sc isEqualToString:UIContentSizeCategoryExtraLarge]) { + result = 1; + } else if ([sc isEqualToString:UIContentSizeCategoryExtraExtraLarge]) { + result = 2; + } else if ([sc isEqualToString:UIContentSizeCategoryExtraExtraExtraLarge]) { + result = 3; + } else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityMedium]) { + result = -11; + } else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityLarge]) { + result = 10; + } else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityExtraLarge]) { + result = 11; + } else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraLarge]) { + result = 12; + } else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraExtraLarge]) { + result = 13; + } + + return result; + }; + + if ( ! [[NSThread currentThread] isMainThread]) { + dispatch_sync(dispatch_get_main_queue(), ^{ + result = contentSizeScaleBlock(); + }); + } else { + result = contentSizeScaleBlock(); } - return -9999; + + return result; } - +// Can be called from any thread. +// - (NSString *)getSysInfoByName:(char *)typeSpecifier { size_t size; @@ -315,6 +495,8 @@ NSNumber *scale; return results; } +// Can be called from any thread. +// - (NSString *) getWifiNetworkName { NSString *ssid = @""; @@ -324,14 +506,80 @@ NSNumber *scale; if (info) { ssid = info[@"SSID"]; } else { - ssid = @"<>"; + ssid = @"NONE"; } } else { - ssid = @"<>"; + ssid = @"NONE"; } return ssid; } +// Can be called from any thread. +// +- (NSString *) getCurrentCellularNetworkConnectionType { + CTTelephonyNetworkInfo *telephonyInfo = [CTTelephonyNetworkInfo new]; + NSString *radioTech = telephonyInfo.currentRadioAccessTechnology; + + if (radioTech == nil) { + return @"NONE"; + } else if ([radioTech isEqualToString:CTRadioAccessTechnologyGPRS]) { + return @"GPRS"; + } else if ([radioTech isEqualToString:CTRadioAccessTechnologyEdge]) { + return @"EDGE"; + } else if ([radioTech isEqualToString:CTRadioAccessTechnologyWCDMA]) { + return @"WCDMA"; + } else if ([radioTech isEqualToString:CTRadioAccessTechnologyHSDPA]) { + return @"HSDPA"; + } else if ([radioTech isEqualToString:CTRadioAccessTechnologyHSUPA]) { + return @"HSUPA"; + } else if ([radioTech isEqualToString:CTRadioAccessTechnologyCDMA1x]) { + return @"CDMA1x"; + } else if ([radioTech isEqualToString:CTRadioAccessTechnologyCDMAEVDORev0]) { + return @"CDMAEVDORev0"; + } else if ([radioTech isEqualToString:CTRadioAccessTechnologyCDMAEVDORevA]) { + return @"CDMAEVDORevA"; + } else if ([radioTech isEqualToString:CTRadioAccessTechnologyCDMAEVDORevB]) { + return @"CDMAEVDORevB"; + } else if ([radioTech isEqualToString:CTRadioAccessTechnologyeHRPD]) { + return @"HRPD"; + } else if ([radioTech isEqualToString:CTRadioAccessTechnologyLTE]) { + return @"LTE"; + } else { + return @"Unknown"; + } +} -@end \ No newline at end of file +// Can be called from any thread. +// ++ (BOOL) checkPushEnabled { + BOOL (^pushCheckBlock)(void) = ^{ + BOOL blockResult; + if ([[UIApplication sharedApplication] respondsToSelector:@selector(isRegisteredForRemoteNotifications)]) { + // iOS 8+ + blockResult = [[UIApplication sharedApplication] isRegisteredForRemoteNotifications]; + } else { + // iOS 7 +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes]; + blockResult = (types == UIRemoteNotificationTypeNone) ? NO : YES; +#pragma clang diagnostic pop + } + return blockResult; + }; + + __block BOOL result; + + if ( ! [[NSThread currentThread] isMainThread]) { + dispatch_sync(dispatch_get_main_queue(), ^{ + result = pushCheckBlock(); + }); + } else { + result = pushCheckBlock(); + } + + return result; +} + +@end diff --git a/platform/ios/MGLMetricsLocationManager.m b/platform/ios/MGLMetricsLocationManager.m index 5eac0370d..c0ff740b3 100644 --- a/platform/ios/MGLMetricsLocationManager.m +++ b/platform/ios/MGLMetricsLocationManager.m @@ -1,48 +1,18 @@ -// -// MBLocationManager.m -// Hermes -// -// Dynamic Settings.bundle loading based on: -// http://stackoverflow.com/questions/510216/can-you-make-the-settings-in-settings-bundle-default-even-if-you-dont-open-the -// -// Created by Brad Leege on 3/8/15. -// Copyright (c) 2015 Mapbox. All rights reserved. -// - -#import "MGLMetricsLocationManager.h" -#import "CoreLocation/CoreLocation.h" #import "MGLMapboxEvents.h" +#import "MGLMetricsLocationManager.h" -@interface MGLMetricsLocationManager() +#import -@property (atomic) CLLocationManager *locationManager; +@interface MGLMetricsLocationManager() + +@property (nonatomic) CLLocationManager *locationManager; @end @implementation MGLMetricsLocationManager -static MGLMetricsLocationManager *sharedManager = nil; - -- (id) init { +- (instancetype) init { if (self = [super init]) { - - NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"]; - if(!settingsBundle) { - NSLog(@"Could not find Settings.bundle"); - } else { - NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:@"Root.plist"]]; - NSArray *preferences = [settings objectForKey:@"PreferenceSpecifiers"]; - NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]]; - for(NSDictionary *prefSpecification in preferences) { - NSString *key = [prefSpecification objectForKey:@"Key"]; - if(key && [[prefSpecification allKeys] containsObject:@"DefaultValue"]) { - [defaultsToRegister setObject:[prefSpecification objectForKey:@"DefaultValue"] forKey:key]; - } - } - - [[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister]; - } - _locationManager = [[CLLocationManager alloc] init]; _locationManager.distanceFilter = 2; _locationManager.desiredAccuracy = kCLLocationAccuracyBest; @@ -52,46 +22,31 @@ static MGLMetricsLocationManager *sharedManager = nil; return self; } -+ (id)sharedManager { ++ (instancetype)sharedManager { static dispatch_once_t onceToken; + static MGLMetricsLocationManager *sharedManager; dispatch_once(&onceToken, ^{ sharedManager = [[self alloc] init]; }); return sharedManager; } -- (BOOL) isAuthorizedStatusDetermined { - return ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined); ++ (void) startUpdatingLocation { + [[MGLMetricsLocationManager sharedManager].locationManager startUpdatingLocation]; } -- (void) requestAlwaysAuthorization { - if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) { - [self.locationManager requestAlwaysAuthorization]; - } else { - // This is iOS 7 or below so Starting Location Updates will trigger authorization request - [self startUpdatingLocation]; - } -} - -- (void) startUpdatingLocation { - [self.locationManager startUpdatingLocation]; -} - -- (void) stopUpdatingLocation { - [self.locationManager stopUpdatingLocation]; ++ (void) stopUpdatingLocation { + [[MGLMetricsLocationManager sharedManager].locationManager stopUpdatingLocation]; } #pragma mark CLLocationManagerDelegate - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { - CLLocation *loc = (CLLocation *)[locations objectAtIndex:0]; - NSLog(@"didUpdateLocations() called with %lu location in array. First Location = %f, %f", (unsigned long)locations.count, loc.coordinate.latitude, loc.coordinate.longitude); - // Iterate through locations to pass all data for (CLLocation *loc in locations) { - NSMutableDictionary *evt = [[NSMutableDictionary alloc] init]; - [evt setValue:[[NSNumber alloc] initWithDouble:loc.coordinate.latitude] forKey:@"lat"]; - [evt setValue:[[NSNumber alloc] initWithDouble:loc.coordinate.longitude] forKey:@"lng"]; - [[MGLMapboxEvents sharedManager] pushEvent:@"location" withAttributes:evt]; + [MGLMapboxEvents pushEvent:MGLEventTypeLocation withAttributes:@{ + MGLEventKeyLatitude: @(loc.coordinate.latitude), + MGLEventKeyLongitude: @(loc.coordinate.longitude) + }]; } } @@ -106,24 +61,23 @@ static MGLMetricsLocationManager *sharedManager = nil; break; case kCLAuthorizationStatusDenied: newStatus = @"User Explcitly Denied"; - [[MGLMetricsLocationManager sharedManager] stopUpdatingLocation]; + [MGLMetricsLocationManager stopUpdatingLocation]; break; case kCLAuthorizationStatusAuthorized: newStatus = @"User Has Authorized / Authorized Always"; - [[MGLMetricsLocationManager sharedManager] startUpdatingLocation]; + [MGLMetricsLocationManager startUpdatingLocation]; break; // case kCLAuthorizationStatusAuthorizedAlways: // newStatus = @"Not Determined"; // break; case kCLAuthorizationStatusAuthorizedWhenInUse: newStatus = @"User Has Authorized When In Use Only"; - [[MGLMetricsLocationManager sharedManager] startUpdatingLocation]; + [MGLMetricsLocationManager startUpdatingLocation]; break; default: newStatus = @"Unknown"; break; } - NSLog(@"MGLMetricsLocationManager didChangeAuthorizationStatus() called. New Status = %@", newStatus); } @end diff --git a/platform/ios/MGLStyleFunctionValue.m b/platform/ios/MGLStyleFunctionValue.m deleted file mode 100644 index a319114ee..000000000 --- a/platform/ios/MGLStyleFunctionValue.m +++ /dev/null @@ -1,190 +0,0 @@ -#import "MGLStyleFunctionValue.h" - -#import "MGLTypes.h" - -@interface MGLStyleFunctionValue () - -@property (nonatomic) NSString *functionType; -@property (nonatomic) NSDictionary *stops; -@property (nonatomic) CGFloat zBase; -@property (nonatomic) CGFloat val; -@property (nonatomic) CGFloat slope; -@property (nonatomic) CGFloat min; -@property (nonatomic) CGFloat max; -@property (nonatomic) CGFloat minimumZoom; -@property (nonatomic) CGFloat maximumZoom; - -- (NSDictionary *)rawStyle; - -@end - -@implementation MGLStyleFunctionValue - -- (id)initWithFunctionType:(NSString *)functionType - stops:(NSDictionary *)stops - zBase:(CGFloat)zBase - val:(CGFloat)val - slope:(CGFloat)slope - min:(CGFloat)min - max:(CGFloat)max - minimumZoom:(CGFloat)minimumZoom - maximumZoom:(CGFloat)maximumZoom -{ - self = [super init]; - - if (self) - { - _functionType = functionType; - _stops = stops; - _zBase = zBase; - _val = val; - _slope = slope; - _min = min; - _max = max; - _minimumZoom = minimumZoom; - _maximumZoom = maximumZoom; - } - - return self; -} - -- (id)rawStyle -{ - if ([self.functionType isEqualToString:MGLStyleValueTypeFunctionMinimumZoom]) - { - return @[ @"min", @(self.minimumZoom) ]; - } - else if ([self.functionType isEqualToString:MGLStyleValueTypeFunctionMaximumZoom]) - { - return @[ @"max", @(self.maximumZoom) ]; - } - else if ([self.functionType isEqualToString:MGLStyleValueTypeFunctionLinear]) - { - return @[ @"linear", @(self.zBase), @(self.val), @(self.slope), @(self.min), @(self.max) ]; - } - else if ([self.functionType isEqualToString:MGLStyleValueTypeFunctionExponential]) - { - return @[ @"exponential", @(self.zBase), @(self.val), @(self.slope), @(self.min), @(self.max) ]; - } - else if ([self.functionType isEqualToString:MGLStyleValueTypeFunctionStops]) - { - NSMutableArray *returnArray = [NSMutableArray array]; - - for (NSNumber *z in [self.stops allKeys]) - { - [returnArray addObject:@{ @"z" : z, @"val" : self.stops[z] }]; - } - - [returnArray insertObject:@"stops" atIndex:0]; - - return returnArray; - } - - return nil; -} - -+ (instancetype)stopsFunctionWithZoomLevelsAndValues:(NSNumber *)firstZoom, ... -{ - NSMutableArray *numbersArray = [NSMutableArray array]; - - va_list args; - va_start(args, firstZoom); - - for (NSNumber *arg = firstZoom; arg != nil; arg = va_arg(args, NSNumber *)) - { - [numbersArray addObject:arg]; - } - - va_end(args); - - NSAssert([numbersArray count] % 2 == 0, @"invalid number of arguments"); - - NSMutableDictionary *stops = [NSMutableDictionary dictionary]; - - for (NSUInteger i = 0; i < [numbersArray count]; i = i + 2) - { - stops[numbersArray[i]] = stops[numbersArray[i + 1]]; - } - - return [[self alloc] initWithFunctionType:MGLStyleValueTypeFunctionStops - stops:stops - zBase:0 - val:0 - slope:0 - min:0 - max:0 - minimumZoom:0 - maximumZoom:0]; -} - -+ (instancetype)linearFunctionWithBaseZoomLevel:(CGFloat)zBase - initialValue:(CGFloat)val - slope:(CGFloat)slope - minimumValue:(CGFloat)min - maximumValue:(CGFloat)max -{ - NSAssert(zBase >= 0 && zBase <= 18, @"invalid base zoom level"); - NSAssert(min < max, @"minimum value must be less than maximum value"); - - return [[self alloc] initWithFunctionType:MGLStyleValueTypeFunctionLinear - stops:nil - zBase:zBase - val:val - slope:slope - min:min - max:max - minimumZoom:0 - maximumZoom:0]; -} - -+ (instancetype)exponentialFunctionWithBaseZoomLevel:(CGFloat)zBase - initialValue:(CGFloat)val - slope:(CGFloat)slope - minimumValue:(CGFloat)min - maximumValue:(CGFloat)max -{ - NSAssert(zBase >= 0 && zBase <= 18, @"invalid base zoom level"); - NSAssert(min < max, @"minimum value must be less than maximum value"); - - return [[self alloc] initWithFunctionType:MGLStyleValueTypeFunctionExponential - stops:nil - zBase:zBase - val:val - slope:slope - min:min - max:max - minimumZoom:0 - maximumZoom:0]; -} - -+ (instancetype)minimumZoomLevelFunction:(CGFloat)minimumZoom -{ - NSAssert(minimumZoom >= 0 && minimumZoom <= 18, @"invalid minimum zoom value"); - - return [[self alloc] initWithFunctionType:MGLStyleValueTypeFunctionMinimumZoom - stops:nil - zBase:0 - val:0 - slope:0 - min:0 - max:0 - minimumZoom:minimumZoom - maximumZoom:0]; -} - -+ (instancetype)maximumZoomLevelFunction:(CGFloat)maximumZoom -{ - NSAssert(maximumZoom >= 0 && maximumZoom <= 18, @"invalid maximum zoom value"); - - return [[self alloc] initWithFunctionType:MGLStyleValueTypeFunctionMaximumZoom - stops:nil - zBase:0 - val:0 - slope:0 - min:0 - max:0 - minimumZoom:0 - maximumZoom:maximumZoom]; -} - -@end diff --git a/platform/ios/MGLTypes.m b/platform/ios/MGLTypes.m deleted file mode 100644 index 2928bc2f4..000000000 --- a/platform/ios/MGLTypes.m +++ /dev/null @@ -1,24 +0,0 @@ -#import "MGLTypes.h" - -NSString *const MGLStyleKeyGeneric = @"MGLStyleKeyGeneric"; -NSString *const MGLStyleKeyFill = @"MGLStyleKeyFill"; -NSString *const MGLStyleKeyLine = @"MGLStyleKeyLine"; -NSString *const MGLStyleKeyIcon = @"MGLStyleKeyIcon"; -NSString *const MGLStyleKeyText = @"MGLStyleKeyText"; -NSString *const MGLStyleKeyRaster = @"MGLStyleKeyRaster"; -NSString *const MGLStyleKeyComposite = @"MGLStyleKeyComposite"; -NSString *const MGLStyleKeyBackground = @"MGLStyleKeyBackground"; - -NSString *const MGLStyleValueTypeBoolean = @"MGLStyleValueTypeBoolean"; -NSString *const MGLStyleValueTypeNumber = @"MGLStyleValueTypeNumber"; -NSString *const MGLStyleValueTypeNumberPair = @"MGLStyleValueTypeNumberPair"; -NSString *const MGLStyleValueTypeColor = @"MGLStyleValueTypeColor"; -NSString *const MGLStyleValueTypeString = @"MGLStyleValueTypeString"; - -NSString *const MGLStyleValueFunctionAllowed = @"MGLStyleValueFunctionAllowed"; - -NSString *const MGLStyleValueTypeFunctionMinimumZoom = @"MGLStyleValueTypeFunctionMinimumZoom"; -NSString *const MGLStyleValueTypeFunctionMaximumZoom = @"MGLStyleValueTypeFunctionMaximumZoom"; -NSString *const MGLStyleValueTypeFunctionLinear = @"MGLStyleValueTypeFunctionLinear"; -NSString *const MGLStyleValueTypeFunctionExponential = @"MGLStyleValueTypeFunctionExponential"; -NSString *const MGLStyleValueTypeFunctionStops = @"MGLStyleValueTypeFunctionStops"; diff --git a/platform/ios/MGLUserLocation.m b/platform/ios/MGLUserLocation.m new file mode 100644 index 000000000..054dfa686 --- /dev/null +++ b/platform/ios/MGLUserLocation.m @@ -0,0 +1,57 @@ +#import "MGLUserLocation_Private.h" + +@implementation MGLUserLocation +{ + CLLocationCoordinate2D _coordinate; +} + +@synthesize coordinate = _coordinate; + +- (instancetype)init +{ + if (self = [super init]) + { + _coordinate = CLLocationCoordinate2DMake(MAXFLOAT, MAXFLOAT); + } + + return self; +} + ++ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key +{ + return ! [key isEqualToString:@"location"] && ! [key isEqualToString:@"heading"]; +} + ++ (NSSet *)keyPathsForValuesAffectingCoordinate +{ + return [NSSet setWithObject:@"location"]; +} + +- (void)setLocation:(CLLocation *)newLocation +{ + if ([newLocation distanceFromLocation:_location] && newLocation.coordinate.latitude != 0 && + newLocation.coordinate.longitude != 0) + { + [self willChangeValueForKey:@"location"]; + _location = newLocation; + _coordinate = _location.coordinate; + [self didChangeValueForKey:@"location"]; + } +} + +- (void)setHeading:(CLHeading *)newHeading +{ + if (newHeading.trueHeading != _heading.trueHeading) + { + [self willChangeValueForKey:@"heading"]; + _heading = newHeading; + [self didChangeValueForKey:@"heading"]; + } +} + +- (NSString *)title +{ + if ( ! _title) return @"Current Location"; +} + +@end diff --git a/platform/ios/MGLUserLocationAnnotationView.h b/platform/ios/MGLUserLocationAnnotationView.h new file mode 100644 index 000000000..c72d64ed8 --- /dev/null +++ b/platform/ios/MGLUserLocationAnnotationView.h @@ -0,0 +1,18 @@ +#import +#import + +#import "MGLUserLocation.h" + +@class MGLMapView; + +/** The MGLUserLocationAnnotationView class defines a specific type of annotation that identifies the user’s current location. You do not create instances of this class directly. Instead, you retrieve an existing MGLUserLocationAnnotationView object from the userLocation property of the map view displayed in your application. */ +@interface MGLUserLocationAnnotationView : UIView + +@property (nonatomic, weak) MGLMapView *mapView; +@property (nonatomic) MGLUserLocation *annotation; +@property (nonatomic, readonly) CALayer *haloLayer; + +- (instancetype)initInMapView:(MGLMapView *)mapView; +- (void)setupLayers; + +@end diff --git a/platform/ios/MGLUserLocationAnnotationView.m b/platform/ios/MGLUserLocationAnnotationView.m new file mode 100644 index 000000000..18c98bf1d --- /dev/null +++ b/platform/ios/MGLUserLocationAnnotationView.m @@ -0,0 +1,197 @@ +#import "MGLUserLocationAnnotationView.h" + +#import "MGLUserLocation_Private.h" +#import "MGLAnnotation.h" +#import "MGLMapView.h" + +const CGFloat MGLTrackingDotRingWidth = 24.0; + +@interface MGLUserLocationAnnotationView () + +@property (nonatomic, readwrite) CALayer *haloLayer; + +@end + +#pragma mark - + +@implementation MGLUserLocationAnnotationView +{ + CALayer *_accuracyRingLayer; + CALayer *_dotBorderLayer; + CALayer *_dotLayer; +} + +- (instancetype)initInMapView:(MGLMapView *)mapView +{ + if (self = [super init]) + { + self.annotation = [[MGLUserLocation alloc] init]; + _mapView = mapView; + [self setupLayers]; + } + return self; +} + +- (void)setTintColor:(UIColor *)tintColor +{ + UIImage *trackingDotHaloImage = [self trackingDotHaloImage]; + _haloLayer.bounds = CGRectMake(0, 0, trackingDotHaloImage.size.width, trackingDotHaloImage.size.height); + _haloLayer.contents = (__bridge id)[trackingDotHaloImage CGImage]; + + UIImage *dotImage = [self dotImage]; + _dotLayer.bounds = CGRectMake(0, 0, dotImage.size.width, dotImage.size.height); + _dotLayer.contents = (__bridge id)[dotImage CGImage]; +} + +- (void)setupLayers +{ + if (CLLocationCoordinate2DIsValid(self.annotation.coordinate)) + { + if ( ! _accuracyRingLayer && self.annotation.location.horizontalAccuracy) + { + UIImage *accuracyRingImage = [self accuracyRingImage]; + _accuracyRingLayer = [CALayer layer]; + _haloLayer.bounds = CGRectMake(0, 0, accuracyRingImage.size.width, accuracyRingImage.size.height); + _haloLayer.contents = (__bridge id)[accuracyRingImage CGImage]; + _haloLayer.position = CGPointMake(super.layer.bounds.size.width / 2.0, super.layer.bounds.size.height / 2.0); + + [self.layer addSublayer:_accuracyRingLayer]; + } + + if ( ! _haloLayer) + { + UIImage *haloImage = [self trackingDotHaloImage]; + _haloLayer = [CALayer layer]; + _haloLayer.bounds = CGRectMake(0, 0, haloImage.size.width, haloImage.size.height); + _haloLayer.contents = (__bridge id)[haloImage CGImage]; + _haloLayer.position = CGPointMake(super.layer.bounds.size.width / 2.0, super.layer.bounds.size.height / 2.0); + + [CATransaction begin]; + + [CATransaction setAnimationDuration:3.5]; + [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]]; + + // scale out radially + // + CABasicAnimation *boundsAnimation = [CABasicAnimation animationWithKeyPath:@"transform"]; + boundsAnimation.repeatCount = MAXFLOAT; + boundsAnimation.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]; + boundsAnimation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(2.0, 2.0, 1.0)]; + boundsAnimation.removedOnCompletion = NO; + + [_haloLayer addAnimation:boundsAnimation forKey:@"animateScale"]; + + // go transparent as scaled out + // + CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"]; + opacityAnimation.repeatCount = MAXFLOAT; + opacityAnimation.fromValue = [NSNumber numberWithFloat:1.0]; + opacityAnimation.toValue = [NSNumber numberWithFloat:-1.0]; + opacityAnimation.removedOnCompletion = NO; + + [_haloLayer addAnimation:opacityAnimation forKey:@"animateOpacity"]; + + [CATransaction commit]; + + [self.layer addSublayer:_haloLayer]; + } + + // white dot background with shadow + // + if ( ! _dotBorderLayer) + { + CGRect rect = CGRectMake(0, 0, MGLTrackingDotRingWidth * 1.25, MGLTrackingDotRingWidth * 1.25); + + UIGraphicsBeginImageContextWithOptions(rect.size, NO, [[UIScreen mainScreen] scale]); + CGContextRef context = UIGraphicsGetCurrentContext(); + + CGContextSetShadow(context, CGSizeMake(0, 0), MGLTrackingDotRingWidth / 4.0); + + CGContextSetFillColorWithColor(context, [[UIColor whiteColor] CGColor]); + CGContextFillEllipseInRect(context, CGRectMake((rect.size.width - MGLTrackingDotRingWidth) / 2.0, (rect.size.height - MGLTrackingDotRingWidth) / 2.0, MGLTrackingDotRingWidth, MGLTrackingDotRingWidth)); + + UIImage *whiteBackground = UIGraphicsGetImageFromCurrentImageContext(); + + UIGraphicsEndImageContext(); + + _dotBorderLayer = [CALayer layer]; + _dotBorderLayer.bounds = CGRectMake(0, 0, whiteBackground.size.width, whiteBackground.size.height); + _dotBorderLayer.contents = (__bridge id)[whiteBackground CGImage]; + _dotBorderLayer.position = CGPointMake(super.layer.bounds.size.width / 2.0, super.layer.bounds.size.height / 2.0); + [self.layer addSublayer:_dotBorderLayer]; + } + + // pulsing, tinted dot sublayer + // + if ( ! _dotLayer) + { + UIImage *dotImage = [self dotImage]; + _dotLayer = [CALayer layer]; + _dotLayer.bounds = CGRectMake(0, 0, dotImage.size.width, dotImage.size.height); + _dotLayer.contents = (__bridge id)[dotImage CGImage]; + _dotLayer.position = CGPointMake(super.layer.bounds.size.width / 2.0, super.layer.bounds.size.height / 2.0); + + CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"]; + animation.repeatCount = MAXFLOAT; + animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]; + animation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.8, 0.8, 1.0)]; + animation.removedOnCompletion = NO; + animation.autoreverses = YES; + animation.duration = 1.5; + animation.beginTime = CACurrentMediaTime() + 1.0; + animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]; + + [_dotLayer addAnimation:animation forKey:@"animateTransform"]; + + [self.layer addSublayer:_dotLayer]; + } + } +} + +- (UIImage *)accuracyRingImage +{ + CGFloat latRadians = self.annotation.coordinate.latitude * M_PI / 180.0f; + CGFloat pixelRadius = self.annotation.location.horizontalAccuracy / cos(latRadians) / [self.mapView metersPerPixelAtLatitude:self.annotation.coordinate.latitude]; + UIGraphicsBeginImageContextWithOptions(CGSizeMake(pixelRadius * 2, pixelRadius * 2), NO, [[UIScreen mainScreen] scale]); + + CGContextSetStrokeColorWithColor(UIGraphicsGetCurrentContext(), [[UIColor colorWithRed:0.378 green:0.552 blue:0.827 alpha:0.7] CGColor]); + CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), [[UIColor colorWithRed:0.378 green:0.552 blue:0.827 alpha:0.15] CGColor]); + CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 2.0); + CGContextStrokeEllipseInRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, pixelRadius * 2, pixelRadius * 2)); + + UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext(); + UIGraphicsEndImageContext(); + return finalImage; +} + +- (UIImage *)trackingDotHaloImage +{ + UIGraphicsBeginImageContextWithOptions(CGSizeMake(100, 100), NO, [[UIScreen mainScreen] scale]); + CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), [[_mapView.tintColor colorWithAlphaComponent:0.75] CGColor]); + CGContextFillEllipseInRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, 100, 100)); + UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext(); + UIGraphicsEndImageContext(); + + return finalImage; +} + +- (UIImage *)dotImage +{ + CGFloat tintedWidth = MGLTrackingDotRingWidth * 0.7; + + CGRect rect = CGRectMake(0, 0, tintedWidth, tintedWidth); + + UIGraphicsBeginImageContextWithOptions(rect.size, NO, [[UIScreen mainScreen] scale]); + CGContextRef context = UIGraphicsGetCurrentContext(); + + CGContextSetFillColorWithColor(context, [_mapView.tintColor CGColor]); + CGContextFillEllipseInRect(context, CGRectMake((rect.size.width - tintedWidth) / 2.0, (rect.size.height - tintedWidth) / 2.0, tintedWidth, tintedWidth)); + + UIImage *tintedForeground = UIGraphicsGetImageFromCurrentImageContext(); + + UIGraphicsEndImageContext(); + + return tintedForeground; +} + +@end diff --git a/platform/ios/MGLUserLocation_Private.h b/platform/ios/MGLUserLocation_Private.h new file mode 100644 index 000000000..d4f358bcb --- /dev/null +++ b/platform/ios/MGLUserLocation_Private.h @@ -0,0 +1,9 @@ +#import "MGLUserLocation.h" + +@interface MGLUserLocation (Private) + +@property (nonatomic, readwrite) CLLocationCoordinate2D coordinate; +@property (nonatomic, readwrite) CLLocation *location; +@property (nonatomic, readwrite) CLHeading *heading; + +@end diff --git a/platform/ios/NSArray+MGLAdditions.m b/platform/ios/NSArray+MGLAdditions.m deleted file mode 100644 index 2bac42ce0..000000000 --- a/platform/ios/NSArray+MGLAdditions.m +++ /dev/null @@ -1,10 +0,0 @@ -#import "NSArray+MGLAdditions.h" - -@implementation NSArray (MGLAdditions) - -- (NSMutableArray *)deepMutableCopy -{ - return (NSMutableArray *)CFBridgingRelease(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFArrayRef)self, kCFPropertyListMutableContainersAndLeaves)); -} - -@end diff --git a/platform/ios/NSDictionary+MGLAdditions.m b/platform/ios/NSDictionary+MGLAdditions.m deleted file mode 100644 index 3228d5653..000000000 --- a/platform/ios/NSDictionary+MGLAdditions.m +++ /dev/null @@ -1,10 +0,0 @@ -#import "NSDictionary+MGLAdditions.h" - -@implementation NSDictionary (MGLAdditions) - -- (NSMutableDictionary *)deepMutableCopy -{ - return (NSMutableDictionary *)CFBridgingRelease(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFDictionaryRef)self, kCFPropertyListMutableContainersAndLeaves)); -} - -@end diff --git a/platform/ios/UIColor+MGLAdditions.m b/platform/ios/UIColor+MGLAdditions.m deleted file mode 100644 index ae40735d1..000000000 --- a/platform/ios/UIColor+MGLAdditions.m +++ /dev/null @@ -1,167 +0,0 @@ -#import "UIColor+MGLAdditions.h" - -/* Portions based on Erica Sadun's uicolor-utilities - https://github.com/erica/uicolor-utilities */ - -@interface UIColor (MGLAdditionsPrivate) - -+ (UIColor *)colorWithRGBHex:(UInt32)hex; -- (CGColorSpaceModel)colorSpaceModel; -- (BOOL)canProvideRGBComponents; -- (BOOL)red:(CGFloat *)red green:(CGFloat *)green blue:(CGFloat *)blue alpha:(CGFloat *)alpha; -- (UInt32)rgbHex; - -@end - -@implementation UIColor (MGLAdditions) - -+ (UIColor *)colorWithRGBAString:(NSString *)rgbaString -{ - UIColor *color; - - NSString *numberString = [rgbaString stringByReplacingOccurrencesOfString:@"rgba(" - withString:@""]; - numberString = [numberString stringByReplacingOccurrencesOfString:@"rgb(" - withString:@""]; - numberString = [numberString stringByReplacingOccurrencesOfString:@")" - withString:@""]; - - NSArray *numbers = [numberString componentsSeparatedByString:@","]; - - if ([rgbaString hasPrefix:@"rgb("] && [numbers count] == 3) - { - color = [UIColor colorWithRed:[numbers[0] floatValue] / 255 - green:[numbers[1] floatValue] / 255 - blue:[numbers[2] floatValue] / 255 - alpha:1.0]; - } - else if ([rgbaString hasPrefix:@"rgba("] && [numbers count] == 4) - { - color = [UIColor colorWithRed:[numbers[0] floatValue] / 255 - green:[numbers[1] floatValue] / 255 - blue:[numbers[2] floatValue] / 255 - alpha:[numbers[3] floatValue]]; - } - - return color; -} - -- (NSString *)rgbaStringFromColor -{ - CGFloat r,g,b,a; - - [self getRed:&r green:&g blue:&b alpha:&a]; - - r *= 255; - g *= 255; - b *= 255; - a *= 255; - - return [NSString stringWithFormat:@"rgba(%lu,%lu,%lu,%lu)", (unsigned long)r, (unsigned long)g, (unsigned long)b, (unsigned long)a]; -} - -+ (UIColor *)colorWithRGBHex:(UInt32)hex -{ - int r = (hex >> 16) & 0xFF; - int g = (hex >> 8) & 0xFF; - int b = (hex) & 0xFF; - - return [UIColor colorWithRed:r / 255.0f - green:g / 255.0f - blue:b / 255.0f - alpha:1.0f]; -} - -- (CGColorSpaceModel)colorSpaceModel -{ - return CGColorSpaceGetModel(CGColorGetColorSpace(self.CGColor)); -} - -- (BOOL)canProvideRGBComponents -{ - switch (self.colorSpaceModel) - { - case kCGColorSpaceModelRGB: - case kCGColorSpaceModelMonochrome: - { - return YES; - } - default: - { - return NO; - } - } -} - -- (BOOL)red:(CGFloat *)red green:(CGFloat *)green blue:(CGFloat *)blue alpha:(CGFloat *)alpha -{ - const CGFloat *components = CGColorGetComponents(self.CGColor); - - CGFloat r,g,b,a; - - switch (self.colorSpaceModel) - { - case kCGColorSpaceModelMonochrome: - { - r = g = b = components[0]; - a = components[1]; - - break; - } - case kCGColorSpaceModelRGB: - { - r = components[0]; - g = components[1]; - b = components[2]; - a = components[3]; - - break; - } - default: - { - return NO; - } - } - - if (red) *red = r; - if (green) *green = g; - if (blue) *blue = b; - if (alpha) *alpha = a; - - return YES; -} - -- (UInt32)rgbHex -{ - NSAssert(self.canProvideRGBComponents, @"Must be a RGB color to use rgbHex"); - - CGFloat r, g, b, a; - - if ( ! [self red:&r green:&g blue:&b alpha:&a]) - return 0; - - r = fminf(fmaxf(r, 0.0f), 1.0f); - g = fminf(fmaxf(g, 0.0f), 1.0f); - b = fminf(fmaxf(b, 0.0f), 1.0f); - - return (((int)roundf(r * 255)) << 16) | (((int)roundf(g * 255)) << 8) | (((int)roundf(b * 255))); -} - -- (NSString *)hexStringFromColor -{ - return [NSString stringWithFormat:@"%0.6X", (unsigned int)(self.rgbHex)]; -} - -+ (UIColor *)colorWithHexString:(NSString *)hexString -{ - NSScanner *scanner = [NSScanner scannerWithString:[hexString stringByReplacingOccurrencesOfString:@"#" withString:@""]]; - - unsigned hexNum; - - if ( ! [scanner scanHexInt:&hexNum]) - return nil; - - return [UIColor colorWithRGBHex:hexNum]; -} - -@end diff --git a/platform/ios/resources/mapbox.png b/platform/ios/resources/mapbox.png index 01b5596b6..5a9da3fe3 100644 Binary files a/platform/ios/resources/mapbox.png and b/platform/ios/resources/mapbox.png differ diff --git a/platform/ios/resources/mapbox@2x.png b/platform/ios/resources/mapbox@2x.png index ff4ef2558..194aa64da 100644 Binary files a/platform/ios/resources/mapbox@2x.png and b/platform/ios/resources/mapbox@2x.png differ diff --git a/platform/ios/resources/mapbox@3x.png b/platform/ios/resources/mapbox@3x.png index 5a2afcb17..d1260a16f 100644 Binary files a/platform/ios/resources/mapbox@3x.png and b/platform/ios/resources/mapbox@3x.png differ diff --git a/platform/ios/vendor/SMCalloutView b/platform/ios/vendor/SMCalloutView new file mode 160000 index 000000000..717078fb6 --- /dev/null +++ b/platform/ios/vendor/SMCalloutView @@ -0,0 +1 @@ +Subproject commit 717078fb6b0d02b944a12f4d40fc15567489d23b diff --git a/src/mbgl/geometry/line_atlas.cpp b/src/mbgl/geometry/line_atlas.cpp index 507cc7b08..f64989d66 100644 --- a/src/mbgl/geometry/line_atlas.cpp +++ b/src/mbgl/geometry/line_atlas.cpp @@ -4,6 +4,8 @@ #include #include +#include + #include #include @@ -26,21 +28,22 @@ LineAtlas::~LineAtlas() { } LinePatternPos LineAtlas::getDashPosition(const std::vector &dasharray, bool round) { + size_t key = round ? std::numeric_limits::min() : std::numeric_limits::max(); + for (const float part : dasharray) { + boost::hash_combine(key, part); + } + + // Note: We're not handling hash collisions here. + std::lock_guard lock(mtx); - - std::ostringstream sskey; - - for (const float &part : dasharray) { - sskey << part << "-"; + const auto it = positions.find(key); + if (it == positions.end()) { + auto inserted = positions.emplace(key, addDash(dasharray, round)); + assert(inserted.second); + return inserted.first->second; + } else { + return it->second; } - sskey << round; - std::string key = sskey.str(); - - if (positions.find(key) == positions.end()) { - positions[key] = addDash(dasharray, round); - } - - return positions[key]; } LinePatternPos LineAtlas::addDash(const std::vector &dasharray, bool round) { @@ -55,7 +58,7 @@ LinePatternPos LineAtlas::addDash(const std::vector &dasharray, bool roun } float length = 0; - for (const float &part : dasharray) { + for (const float part : dasharray) { length += part; } diff --git a/src/mbgl/geometry/line_atlas.hpp b/src/mbgl/geometry/line_atlas.hpp index 191dc0c4d..df60a2dec 100644 --- a/src/mbgl/geometry/line_atlas.hpp +++ b/src/mbgl/geometry/line_atlas.hpp @@ -33,7 +33,7 @@ private: std::atomic dirty; uint32_t texture = 0; int nextRow = 0; - std::map positions; + std::map positions; }; }; diff --git a/src/mbgl/geometry/sprite_atlas.cpp b/src/mbgl/geometry/sprite_atlas.cpp index bf31c6e38..c2686e2f3 100644 --- a/src/mbgl/geometry/sprite_atlas.cpp +++ b/src/mbgl/geometry/sprite_atlas.cpp @@ -73,7 +73,7 @@ Rect SpriteAtlas::allocateImage(const size_t pixel_width // This is so we can scale down the texture coordinates and pack them // into 2 bytes rather than 4 bytes. const uint16_t pack_width = (pixel_width + 1) + (4 - (pixel_width + 1) % 4); - const uint16_t pack_height = (pixel_height + 1) + (4 - (pixel_width + 1) % 4); + const uint16_t pack_height = (pixel_height + 1) + (4 - (pixel_height + 1) % 4); // We have to allocate a new area in the bin, and store an empty image in it. // Add a 1px border around every image. @@ -165,37 +165,37 @@ void SpriteAtlas::copy(const Rect& dst, const SpritePosition& src, co static_cast(dst.originalW * pixelRatio), static_cast(dst.originalH * pixelRatio) }; - util::bilinearScale(srcData, srcSize, srcPos, dstData, dstSize, dstPos); + util::bilinearScale(srcData, srcSize, srcPos, dstData, dstSize, dstPos, wrap); // Add borders around the copied image if required. if (wrap) { // We're copying from the same image so we don't have to scale again. const uint32_t border = 1; + const uint32_t borderX = dstPos.x != 0 ? border : 0; + const uint32_t borderY = dstPos.y != 0 ? border : 0; + // Left border - if (dstPos.x >= border) { - util::nearestNeighborScale( - dstData, dstSize, { dstPos.x + dstPos.w - border - 1, dstPos.y, border, dstPos.h }, - dstData, dstSize, { dstPos.x - border, dstPos.y, border, dstPos.h }); - } + util::nearestNeighborScale( + dstData, dstSize, { dstPos.x + dstPos.w - borderX, dstPos.y, borderX, dstPos.h }, + dstData, dstSize, { dstPos.x - borderX, dstPos.y, borderX, dstPos.h }); + // Right border util::nearestNeighborScale(dstData, dstSize, { dstPos.x, dstPos.y, border, dstPos.h }, dstData, dstSize, { dstPos.x + dstPos.w, dstPos.y, border, dstPos.h }); // Top border - if (dstPos.y >= border) { - util::nearestNeighborScale( - dstData, dstSize, { dstPos.x - border, dstPos.y + dstPos.h - border - 1, - dstPos.w + 2 * border, border }, - dstData, dstSize, - { dstPos.x - border, dstPos.y - border, dstPos.w + 2 * border, border }); - } + util::nearestNeighborScale( + dstData, dstSize, { dstPos.x - borderX, dstPos.y + dstPos.h - borderY, + dstPos.w + border + borderX, borderY }, + dstData, dstSize, + { dstPos.x - borderX, dstPos.y - borderY, dstPos.w + 2 * borderX, borderY }); // Bottom border util::nearestNeighborScale( - dstData, dstSize, { dstPos.x - border, dstPos.y, dstPos.w + 2 * border, border }, + dstData, dstSize, { dstPos.x - borderX, dstPos.y, dstPos.w + 2 * borderX, border }, dstData, dstSize, - { dstPos.x - border, dstPos.y + dstPos.h, dstPos.w + 2 * border, border }); + { dstPos.x - borderX, dstPos.y + dstPos.h, dstPos.w + border + borderX, border }); } dirty = true; diff --git a/src/mbgl/geometry/static_vertex_buffer.cpp b/src/mbgl/geometry/static_vertex_buffer.cpp index c86211c50..c1e8caab9 100644 --- a/src/mbgl/geometry/static_vertex_buffer.cpp +++ b/src/mbgl/geometry/static_vertex_buffer.cpp @@ -4,7 +4,7 @@ namespace mbgl { StaticVertexBuffer::StaticVertexBuffer(std::initializer_list> init) { - for (const std::pair &vertex : init) { + for (const auto& vertex : init) { vertex_type *vertices = static_cast(addElement()); vertices[0] = vertex.first; vertices[1] = vertex.second; diff --git a/src/mbgl/map/map.cpp b/src/mbgl/map/map.cpp index 24f72e8dc..c4ad6efc5 100644 --- a/src/mbgl/map/map.cpp +++ b/src/mbgl/map/map.cpp @@ -18,7 +18,6 @@ #include #include #include -#include #include #include #include @@ -129,14 +128,22 @@ void Map::start(bool startPaused) { // Remove all of these to make sure they are destructed in the correct thread. style.reset(); + + // Since we don't have a stylesheet anymore, this will disable all Sources and cancel + // their associated requests. + updateSources(); + assert(activeSources.empty()); + + // It's now safe to destroy/join the workers since there won't be any more callbacks that + // could dispatch to the worker pool. workers.reset(); - activeSources.clear(); terminating = true; // Closes all open handles on the loop. This means that the loop will automatically terminate. asyncRender.reset(); asyncUpdate.reset(); + asyncInvoke.reset(); asyncTerminate.reset(); }); @@ -144,6 +151,10 @@ void Map::start(bool startPaused) { update(); }); + asyncInvoke = util::make_unique(env->loop, [this] { + processTasks(); + }); + asyncRender = util::make_unique(env->loop, [this] { // Must be called in Map thread. assert(Environment::currentlyOn(ThreadType::Map)); @@ -315,6 +326,42 @@ void Map::triggerRender() { asyncRender->send(); } +// Runs the function in the map thread. +void Map::invokeTask(std::function&& fn) { + { + std::lock_guard lock(mutexTask); + tasks.emplace(::std::forward>(fn)); + } + + // TODO: Once we have aligned static and continuous rendering, this should always dispatch + // to the async queue. + if (asyncInvoke) { + asyncInvoke->send(); + } else { + processTasks(); + } +} + +template auto Map::invokeSyncTask(const Fn& fn) -> decltype(fn()) { + std::promise promise; + invokeTask([&fn, &promise] { promise.set_value(fn()); }); + return promise.get_future().get(); +} + +// Processes the functions that should be run in the map thread. +void Map::processTasks() { + std::queue> queue; + { + std::lock_guard lock(mutexTask); + queue.swap(tasks); + } + + while (!queue.empty()) { + queue.front()(); + queue.pop(); + } +} + void Map::checkForPause() { std::unique_lock lockRun (mutexRun); while (pausing) { @@ -352,13 +399,15 @@ void Map::setup() { void Map::setStyleURL(const std::string &url) { assert(Environment::currentlyOn(ThreadType::Main)); - const size_t pos = url.rfind('/'); + const std::string styleURL = mbgl::util::mapbox::normalizeStyleURL(url, getAccessToken()); + + const size_t pos = styleURL.rfind('/'); std::string base = ""; if (pos != std::string::npos) { - base = url.substr(0, pos + 1); + base = styleURL.substr(0, pos + 1); } - data->setStyleInfo({ url, base, "" }); + data->setStyleInfo({ styleURL, base, "" }); triggerUpdate(Update::StyleInfo); } @@ -542,21 +591,31 @@ std::string Map::getAccessToken() const { void Map::setDefaultPointAnnotationSymbol(const std::string& symbol) { assert(Environment::currentlyOn(ThreadType::Main)); - annotationManager->setDefaultPointAnnotationSymbol(symbol); + invokeTask([=] { + annotationManager->setDefaultPointAnnotationSymbol(symbol); + }); +} + +double Map::getTopOffsetPixelsForAnnotationSymbol(const std::string& symbol) { + assert(Environment::currentlyOn(ThreadType::Main)); + return invokeSyncTask([&] { + assert(sprite); + const SpritePosition pos = sprite->getSpritePosition(symbol); + return -pos.height / pos.pixelRatio / 2; + }); } uint32_t Map::addPointAnnotation(const LatLng& point, const std::string& symbol) { - assert(Environment::currentlyOn(ThreadType::Main)); - std::vector points({ point }); - std::vector symbols({ symbol }); - return addPointAnnotations(points, symbols)[0]; + return addPointAnnotations({ point }, { symbol }).front(); } std::vector Map::addPointAnnotations(const std::vector& points, const std::vector& symbols) { assert(Environment::currentlyOn(ThreadType::Main)); - auto result = annotationManager->addPointAnnotations(points, symbols, *this); - updateAnnotationTiles(result.first); - return result.second; + return invokeSyncTask([&] { + auto result = annotationManager->addPointAnnotations(points, symbols, *this); + updateAnnotationTiles(result.first); + return result.second; + }); } void Map::removeAnnotation(uint32_t annotation) { @@ -566,22 +625,28 @@ void Map::removeAnnotation(uint32_t annotation) { void Map::removeAnnotations(const std::vector& annotations) { assert(Environment::currentlyOn(ThreadType::Main)); - auto result = annotationManager->removeAnnotations(annotations, *this); - updateAnnotationTiles(result); + invokeTask([=] { + auto result = annotationManager->removeAnnotations(annotations, *this); + updateAnnotationTiles(result); + }); } -std::vector Map::getAnnotationsInBounds(const LatLngBounds& bounds) const { +std::vector Map::getAnnotationsInBounds(const LatLngBounds& bounds) { assert(Environment::currentlyOn(ThreadType::Main)); - return annotationManager->getAnnotationsInBounds(bounds, *this); + return invokeSyncTask([&] { + return annotationManager->getAnnotationsInBounds(bounds, *this); + }); } -LatLngBounds Map::getBoundsForAnnotations(const std::vector& annotations) const { +LatLngBounds Map::getBoundsForAnnotations(const std::vector& annotations) { assert(Environment::currentlyOn(ThreadType::Main)); - return annotationManager->getBoundsForAnnotations(annotations); + return invokeSyncTask([&] { + return annotationManager->getBoundsForAnnotations(annotations); + }); } void Map::updateAnnotationTiles(const std::vector& ids) { - assert(Environment::currentlyOn(ThreadType::Main)); + assert(Environment::currentlyOn(ThreadType::Map)); for (const auto &source : activeSources) { if (source->info.type == SourceType::Annotations) { source->source->invalidateTiles(*this, ids); @@ -657,7 +722,11 @@ void Map::updateSources() { // Then, reenable all of those that we actually use when drawing this layer. if (style) { - updateSources(style->layers); + for (const auto& layer : style->layers) { + if (layer->bucket && layer->bucket->style_source) { + (*activeSources.emplace(layer->bucket->style_source).first)->enabled = true; + } + } } // Then, construct or destroy the actual source object, depending on enabled state. @@ -678,23 +747,9 @@ void Map::updateSources() { }); } -void Map::updateSources(const util::ptr &group) { - assert(Environment::currentlyOn(ThreadType::Map)); - if (!group) { - return; - } - for (const util::ptr &layer : group->layers) { - if (!layer) continue; - if (layer->bucket && layer->bucket->style_source) { - (*activeSources.emplace(layer->bucket->style_source).first)->enabled = true; - } - - } -} - void Map::updateTiles() { assert(Environment::currentlyOn(ThreadType::Map)); - for (const auto &source : activeSources) { + for (const auto& source : activeSources) { source->source->update(*this, getWorker(), style, *glyphAtlas, *glyphStore, *spriteAtlas, getSprite(), *texturePool, [this]() { assert(Environment::currentlyOn(ThreadType::Map)); @@ -741,7 +796,7 @@ void Map::loadStyleJSON(const std::string& json, const std::string& base) { style = std::make_shared