Files prefix changed from MGL to MLN (#919)

This commit is contained in:
Alex Cristici
2023-03-21 14:18:26 +02:00
committed by GitHub
parent 35a8752083
commit d72cd766c8
467 changed files with 13884 additions and 13872 deletions

View File

@@ -89,7 +89,7 @@ With buck build support, Android Studio can complain about duplicate source file
_The test application (used for development purposes) uses MapTiler vector tiles, which require a MapTiler account and API key._
With the first gradle invocation, gradle will take the value of the `MGL_API_KEY` environment variable and save it to `MapboxGLAndroidSDKTestApp/src/main/res/values/developer-config.xml`. If the environment variable wasn't set, you can edit `developer-config.xml` manually and add your api key to the `api_key` resource.
With the first gradle invocation, gradle will take the value of the `MLN_API_KEY` environment variable and save it to `MapboxGLAndroidSDKTestApp/src/main/res/values/developer-config.xml`. If the environment variable wasn't set, you can edit `developer-config.xml` manually and add your api key to the `api_key` resource.
## Running project

View File

@@ -71,7 +71,7 @@ open class MapLibreApplication : MultiDexApplication() {
private const val API_KEY_NOT_SET_MESSAGE =
(
"In order to run the Test App you need to set a valid " +
"API key. During development, you can set the MGL_API_KEY environment variable for the SDK to " +
"API key. During development, you can set the MLN_API_KEY environment variable for the SDK to " +
"automatically include it in the Test App. Otherwise, you can manually include it in the " +
"res/values/developer-config.xml file in the MapboxGLAndroidSDKTestApp folder."
)

View File

@@ -5,9 +5,9 @@
task apiKey {
def tokenFile = new File("${projectDir}/src/main/res/values/developer-config.xml")
if (!tokenFile.exists()) {
String apiKey = "$System.env.MGL_API_KEY"
String apiKey = "$System.env.MLN_API_KEY"
if (apiKey == "null") {
System.out.println("You should set the MGL_API_KEY environment variable.")
System.out.println("You should set the MLN_API_KEY environment variable.")
apiKey = "YOUR_API_KEY_GOES_HERE"
}
String tokenFileContents = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +

View File

@@ -9,7 +9,7 @@ objc_library(
hdrs = [
"include/mbgl/interface/native_apple_interface.h",
"include/mbgl/storage/reachability.h",
"include/mbgl/util/image+MGLAdditions.hpp",
"include/mbgl/util/image+MLNAdditions.hpp",
],
copts = WARNING_FLAGS + MAPLIBRE_FLAGS + [
"-fmodules",
@@ -42,7 +42,7 @@ objc_library(
hdrs = [
"include/mbgl/interface/native_apple_interface.h",
"include/mbgl/storage/reachability.h",
"include/mbgl/util/image+MGLAdditions.hpp",
"include/mbgl/util/image+MLNAdditions.hpp",
],
copts = CPP_FLAGS + MAPLIBRE_FLAGS + [
"-fcxx-modules",

View File

@@ -2,13 +2,13 @@
NS_ASSUME_NONNULL_BEGIN
@class MGLNativeNetworkManager;
@class MLNNativeNetworkManager;
@protocol MGLNativeNetworkDelegate <NSObject>
@protocol MLNNativeNetworkDelegate <NSObject>
@optional
- (NSURLSession *)sessionForNetworkManager:(MGLNativeNetworkManager *)networkManager;
- (NSURLSession *)sessionForNetworkManager:(MLNNativeNetworkManager *)networkManager;
@required
@@ -26,13 +26,13 @@ NS_ASSUME_NONNULL_BEGIN
@end
#define MGL_APPLE_EXPORT __attribute__((visibility ("default")))
#define MLN_APPLE_EXPORT __attribute__((visibility ("default")))
@interface MGLNativeNetworkManager: NSObject
@interface MLNNativeNetworkManager: NSObject
+ (MGLNativeNetworkManager *)sharedManager;
+ (MLNNativeNetworkManager *)sharedManager;
@property (nonatomic, weak) id<MGLNativeNetworkDelegate> delegate;
@property (nonatomic, weak) id<MLNNativeNetworkDelegate> delegate;
@property (nonatomic, readonly) NSURLSessionConfiguration *sessionConfiguration;

View File

@@ -38,7 +38,7 @@
#define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type
#endif
extern NSString *const kMGLReachabilityChangedNotification;
extern NSString *const kMLNReachabilityChangedNotification;
typedef NS_ENUM(NSInteger, NetworkStatus) {
// Apple NetworkStatus Compatible Names.
@@ -47,13 +47,13 @@ typedef NS_ENUM(NSInteger, NetworkStatus) {
ReachableViaWWAN = 1
};
@class MGLReachability;
@class MLNReachability;
typedef void (^NetworkReachable)(MGLReachability * reachability);
typedef void (^NetworkUnreachable)(MGLReachability * reachability);
typedef void (^NetworkReachable)(MLNReachability * reachability);
typedef void (^NetworkUnreachable)(MLNReachability * reachability);
@interface MGLReachability : NSObject
@interface MLNReachability : NSObject
@property (nonatomic, copy) NetworkReachable reachableBlock;
@property (nonatomic, copy) NetworkUnreachable unreachableBlock;

View File

@@ -5,8 +5,8 @@
#include <CoreGraphics/CGImage.h>
// Creates a CGImage from a PremultipliedImage, taking over the memory ownership.
CGImageRef CGImageCreateWithMGLPremultipliedImage(mbgl::PremultipliedImage&&);
CGImageRef CGImageCreateWithMLNPremultipliedImage(mbgl::PremultipliedImage&&);
// Creates a PremultipliedImage by copying the pixels of the CGImage.
// Does not alter the retain count of the supplied CGImage.
mbgl::PremultipliedImage MGLPremultipliedImageFromCGImage(CGImageRef);
mbgl::PremultipliedImage MLNPremultipliedImageFromCGImage(CGImageRef);

View File

@@ -87,7 +87,7 @@ public:
Impl(const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_)
: resourceOptions(resourceOptions_.clone()), clientOptions(clientOptions_.clone()) {
@autoreleasepool {
NSURLSessionConfiguration *sessionConfig = MGLNativeNetworkManager.sharedManager.sessionConfiguration;
NSURLSessionConfiguration *sessionConfig = MLNNativeNetworkManager.sharedManager.sessionConfiguration;
session = [NSURLSession sessionWithConfiguration:sessionConfig];
userAgent = getUserAgent();
@@ -141,7 +141,7 @@ NSString *HTTPFileSource::Impl::getUserAgent() const {
NSBundle *sdkBundle = HTTPFileSource::Impl::getSDKBundle();
if (sdkBundle) {
NSString *versionString = sdkBundle.infoDictionary[@"MGLSemanticVersionString"];
NSString *versionString = sdkBundle.infoDictionary[@"MLNSemanticVersionString"];
if (!versionString) {
versionString = sdkBundle.infoDictionary[@"CFBundleShortVersionString"];
}
@@ -213,7 +213,7 @@ HTTPFileSource::HTTPFileSource(const ResourceOptions& resourceOptions, const Cli
HTTPFileSource::~HTTPFileSource() = default;
MGL_APPLE_EXPORT
MLN_APPLE_EXPORT
BOOL isValidMapboxEndpoint(NSURL *url) {
return ([url.host isEqualToString:@"mapbox.com"] ||
[url.host hasSuffix:@".mapbox.com"] ||
@@ -221,7 +221,7 @@ BOOL isValidMapboxEndpoint(NSURL *url) {
[url.host hasSuffix:@".mapbox.cn"]);
}
MGL_APPLE_EXPORT
MLN_APPLE_EXPORT
NSURL *resourceURL(const Resource& resource) {
NSURL *url = [NSURL URLWithString:@(resource.url.c_str())];
@@ -252,7 +252,7 @@ std::unique_ptr<AsyncRequest> HTTPFileSource::request(const Resource& resource,
@autoreleasepool {
NSURL *url = resourceURL(resource);
[MGLNativeNetworkManager.sharedManager debugLog:@"Requesting URI: %@", url.relativePath];
[MLNNativeNetworkManager.sharedManager debugLog:@"Requesting URI: %@", url.relativePath];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
if (resource.priorEtag) {
@@ -268,14 +268,14 @@ std::unique_ptr<AsyncRequest> HTTPFileSource::request(const Resource& resource,
const bool isTile = resource.kind == mbgl::Resource::Kind::Tile;
if (isTile) {
[MGLNativeNetworkManager.sharedManager startDownloadEvent:url.relativePath type:@"tile"];
[MLNNativeNetworkManager.sharedManager startDownloadEvent:url.relativePath type:@"tile"];
}
__block NSURLSession *session;
// Use the delegate's session if there is one, otherwise use the one that
// was created when this class was constructed.
MGLNativeNetworkManager *networkManager = MGLNativeNetworkManager.sharedManager;
MLNNativeNetworkManager *networkManager = MLNNativeNetworkManager.sharedManager;
if ([networkManager.delegate respondsToSelector:@selector(sessionForNetworkManager:)]) {
session = [networkManager.delegate sessionForNetworkManager:networkManager];
}
@@ -292,15 +292,15 @@ std::unique_ptr<AsyncRequest> HTTPFileSource::request(const Resource& resource,
session = nil;
if (error && [error code] == NSURLErrorCancelled) {
[MGLNativeNetworkManager.sharedManager cancelDownloadEventForResponse:res];
[MLNNativeNetworkManager.sharedManager cancelDownloadEventForResponse:res];
return;
}
[MGLNativeNetworkManager.sharedManager stopDownloadEventForResponse:res];
[MLNNativeNetworkManager.sharedManager stopDownloadEventForResponse:res];
Response response;
using Error = Response::Error;
if (error) {
[MGLNativeNetworkManager.sharedManager errorLog:@"Requesting: %@ failed with error: %@", req.URL, error.debugDescription];
[MLNNativeNetworkManager.sharedManager errorLog:@"Requesting: %@ failed with error: %@", req.URL, error.debugDescription];
if (data) {
response.data =
@@ -333,7 +333,7 @@ std::unique_ptr<AsyncRequest> HTTPFileSource::request(const Resource& resource,
}
} else if ([res isKindOfClass:[NSHTTPURLResponse class]]) {
const long responseCode = [(NSHTTPURLResponse *)res statusCode];
[MGLNativeNetworkManager.sharedManager debugLog:@"Requesting %@ returned responseCode: %lu", res.URL.relativePath, responseCode];
[MLNNativeNetworkManager.sharedManager debugLog:@"Requesting %@ returned responseCode: %lu", res.URL.relativePath, responseCode];
NSDictionary *headers = [(NSHTTPURLResponse *)res allHeaderFields];
NSString *cache_control = [headers objectForKey:@"Cache-Control"];

View File

@@ -1,4 +1,4 @@
#include <mbgl/util/image+MGLAdditions.hpp>
#include <mbgl/util/image+MLNAdditions.hpp>
#import <ImageIO/ImageIO.h>
@@ -11,7 +11,7 @@ using CGDataProviderHandle = CFHandle<CGDataProviderRef, CGDataProviderRef, CGDa
using CGColorSpaceHandle = CFHandle<CGColorSpaceRef, CGColorSpaceRef, CGColorSpaceRelease>;
using CGContextHandle = CFHandle<CGContextRef, CGContextRef, CGContextRelease>;
CGImageRef CGImageCreateWithMGLPremultipliedImage(mbgl::PremultipliedImage&& src) {
CGImageRef CGImageCreateWithMLNPremultipliedImage(mbgl::PremultipliedImage&& src) {
// We're converting the PremultipliedImage's backing store to a CGDataProvider, and are taking
// over ownership of the memory.
CGDataProviderHandle provider(CGDataProviderCreateWithData(
@@ -41,7 +41,7 @@ CGImageRef CGImageCreateWithMGLPremultipliedImage(mbgl::PremultipliedImage&& src
NULL, false, kCGRenderingIntentDefault);
}
mbgl::PremultipliedImage MGLPremultipliedImageFromCGImage(CGImageRef src) {
mbgl::PremultipliedImage MLNPremultipliedImageFromCGImage(CGImageRef src) {
const size_t width = CGImageGetWidth(src);
const size_t height = CGImageGetHeight(src);
@@ -89,7 +89,7 @@ PremultipliedImage decodeImage(const std::string& source) {
throw std::runtime_error("CGImageSourceCreateImageAtIndex failed");
}
return MGLPremultipliedImageFromCGImage(*image);
return MLNPremultipliedImageFromCGImage(*image);
}
} // namespace mbgl

View File

@@ -64,9 +64,9 @@ public:
Creates a new rasterizer with the given font names as a fallback.
The fallback font names can also be specified in the style as a font stack
or in the `MGLIdeographicFontFamilyName` key of
or in the `MLNIdeographicFontFamilyName` key of
`NSUserDefaults.standardUserDefaults`. The font stack takes precedence,
followed by the `MGLIdeographicFontFamilyName` user default, then finally
followed by the `MLNIdeographicFontFamilyName` user default, then finally
the `fallbackFontNames_` parameter as a last resort.
@param fallbackFontNames_ A list of font names, one per line. Each font
@@ -77,7 +77,7 @@ public:
*/
Impl(const std::optional<std::string> fallbackFontNames_)
{
fallbackFontNames = [[NSUserDefaults standardUserDefaults] stringArrayForKey:@"MGLIdeographicFontFamilyName"];
fallbackFontNames = [[NSUserDefaults standardUserDefaults] stringArrayForKey:@"MLNIdeographicFontFamilyName"];
if (fallbackFontNames_) {
fallbackFontNames = [fallbackFontNames ?: @[] arrayByAddingObjectsFromArray:[@(fallbackFontNames_->c_str()) componentsSeparatedByString:@"\n"]];
}

View File

@@ -1,14 +1,14 @@
#import <Foundation/Foundation.h>
#import <mbgl/interface/native_apple_interface.h>
@implementation MGLNativeNetworkManager
@implementation MLNNativeNetworkManager
static MGLNativeNetworkManager *instance = nil;
static MLNNativeNetworkManager *instance = nil;
+ (MGLNativeNetworkManager *)sharedManager {
+ (MLNNativeNetworkManager *)sharedManager {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[MGLNativeNetworkManager alloc] init];
instance = [[MLNNativeNetworkManager alloc] init];
});
return instance;
}
@@ -32,9 +32,9 @@ static MGLNativeNetworkManager *instance = nil;
if (!configuration) {
// For testing. Since we get a `nil` return when SDK is modular, we use
// this for testing requests.
// Same as `[MGLNetworkConfiguration defaultSessionConfiguration]` in
// `MGLNetworkConfiguration.mm`.
configuration = [MGLNativeNetworkManager testSessionConfiguration];
// Same as `[MLNNetworkConfiguration defaultSessionConfiguration]` in
// `MLNNetworkConfiguration.mm`.
configuration = [MLNNativeNetworkManager testSessionConfiguration];
}
return configuration;

View File

@@ -35,10 +35,10 @@
#import <netdb.h>
NSString *const kMGLReachabilityChangedNotification = @"kMGLReachabilityChangedNotification";
NSString *const kMLNReachabilityChangedNotification = @"kMLNReachabilityChangedNotification";
@interface MGLReachability ()
@interface MLNReachability ()
@property (nonatomic, assign) SCNetworkReachabilityRef reachabilityRef;
@property (nonatomic, strong) dispatch_queue_t reachabilitySerialQueue;
@@ -73,7 +73,7 @@ static void TMReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkRea
{
#pragma unused (target)
MGLReachability *reachability = ((__bridge MGLReachability*)info);
MLNReachability *reachability = ((__bridge MLNReachability*)info);
// We probably don't need an autoreleasepool here, as GCD docs state each queue has its own autorelease pool,
// but what the heck eh?
@@ -84,13 +84,13 @@ static void TMReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkRea
}
@implementation MGLReachability
@implementation MLNReachability
// MARK: - Class Constructor Methods
+(instancetype)reachabilityWithHostName:(NSString*)hostname
{
return [MGLReachability reachabilityWithHostname:hostname];
return [MLNReachability reachabilityWithHostname:hostname];
}
+(instancetype)reachabilityWithHostname:(NSString*)hostname
@@ -456,7 +456,7 @@ static void TMReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkRea
// this makes sure the change notification happens on the MAIN THREAD
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:kMGLReachabilityChangedNotification
[[NSNotificationCenter defaultCenter] postNotificationName:kMLNReachabilityChangedNotification
object:self];
});
}

View File

@@ -35,7 +35,7 @@ HeadlessFrontend::HeadlessFrontend(Size size_,
gfx::BackendScope guard {*getBackend()};
// onStyleImageMissing might be called during a render. The user implemented method
// could trigger a call to MGLRenderFrontend#update which overwrites `updateParameters`.
// could trigger a call to MLNRenderFrontend#update which overwrites `updateParameters`.
// Copy the shared pointer here so that the parameters aren't destroyed while `render(...)` is
// still using them.
auto updateParameters_ = updateParameters;

View File

@@ -34,7 +34,7 @@ void GLFWRendererFrontend::render() {
mbgl::gfx::BackendScope guard { glfwView.getRendererBackend(), mbgl::gfx::BackendScope::ScopeType::Implicit };
// onStyleImageMissing might be called during a render. The user implemented method
// could trigger a call to MGLRenderFrontend#update which overwrites `updateParameters`.
// could trigger a call to MLNRenderFrontend#update which overwrites `updateParameters`.
// Copy the shared pointer here so that the parameters aren't destroyed while `render(...)` is
// still using them.
auto updateParameters_ = updateParameters;

View File

@@ -100,7 +100,7 @@ int main(int argc, char *argv[]) {
}
// Set access token if present
const char* apikeyEnv = getenv("MGL_API_KEY");
const char* apikeyEnv = getenv("MLN_API_KEY");
const std::string apikey = apikeyValue ? args::get(apikeyValue) : (apikeyEnv ? apikeyEnv : std::string());
auto mapTilerConfiguration = mbgl::TileServerOptions::MapTilerConfiguration();

View File

@@ -53,45 +53,45 @@ mapbox-gl-native.code-workspace
# generated file list will be in:
# platform/ios/platform/darwin/scripts/generate-style-code.list
platform/darwin/src/MGLLight.h
platform/darwin/src/MGLLight.mm
platform/darwin/test/MGLLightTest.mm
platform/darwin/src/MGLBackgroundStyleLayer.h
platform/darwin/src/MGLBackgroundStyleLayer_Private.h
platform/darwin/src/MGLBackgroundStyleLayer.mm
platform/darwin/test/MGLBackgroundStyleLayerTests.mm
platform/darwin/src/MGLCircleStyleLayer.h
platform/darwin/src/MGLCircleStyleLayer_Private.h
platform/darwin/src/MGLCircleStyleLayer.mm
platform/darwin/test/MGLCircleStyleLayerTests.mm
platform/darwin/src/MGLFillStyleLayer.h
platform/darwin/src/MGLFillStyleLayer_Private.h
platform/darwin/src/MGLFillStyleLayer.mm
platform/darwin/test/MGLFillStyleLayerTests.mm
platform/darwin/src/MGLFillExtrusionStyleLayer.h
platform/darwin/src/MGLFillExtrusionStyleLayer_Private.h
platform/darwin/src/MGLFillExtrusionStyleLayer.mm
platform/darwin/test/MGLFillExtrusionStyleLayerTests.mm
platform/darwin/src/MGLHeatmapStyleLayer.h
platform/darwin/src/MGLHeatmapStyleLayer_Private.h
platform/darwin/src/MGLHeatmapStyleLayer.mm
platform/darwin/test/MGLHeatmapStyleLayerTests.mm
platform/darwin/src/MGLHillshadeStyleLayer.h
platform/darwin/src/MGLHillshadeStyleLayer_Private.h
platform/darwin/src/MGLHillshadeStyleLayer.mm
platform/darwin/test/MGLHillshadeStyleLayerTests.mm
platform/darwin/src/MGLLineStyleLayer.h
platform/darwin/src/MGLLineStyleLayer_Private.h
platform/darwin/src/MGLLineStyleLayer.mm
platform/darwin/test/MGLLineStyleLayerTests.mm
platform/darwin/src/MGLRasterStyleLayer.h
platform/darwin/src/MGLRasterStyleLayer_Private.h
platform/darwin/src/MGLRasterStyleLayer.mm
platform/darwin/test/MGLRasterStyleLayerTests.mm
platform/darwin/src/MGLSymbolStyleLayer.h
platform/darwin/src/MGLSymbolStyleLayer_Private.h
platform/darwin/src/MGLSymbolStyleLayer.mm
platform/darwin/test/MGLSymbolStyleLayerTests.mm
platform/darwin/src/MLNLight.h
platform/darwin/src/MLNLight.mm
platform/darwin/test/MLNLightTest.mm
platform/darwin/src/MLNBackgroundStyleLayer.h
platform/darwin/src/MLNBackgroundStyleLayer_Private.h
platform/darwin/src/MLNBackgroundStyleLayer.mm
platform/darwin/test/MLNBackgroundStyleLayerTests.mm
platform/darwin/src/MLNCircleStyleLayer.h
platform/darwin/src/MLNCircleStyleLayer_Private.h
platform/darwin/src/MLNCircleStyleLayer.mm
platform/darwin/test/MLNCircleStyleLayerTests.mm
platform/darwin/src/MLNFillStyleLayer.h
platform/darwin/src/MLNFillStyleLayer_Private.h
platform/darwin/src/MLNFillStyleLayer.mm
platform/darwin/test/MLNFillStyleLayerTests.mm
platform/darwin/src/MLNFillExtrusionStyleLayer.h
platform/darwin/src/MLNFillExtrusionStyleLayer_Private.h
platform/darwin/src/MLNFillExtrusionStyleLayer.mm
platform/darwin/test/MLNFillExtrusionStyleLayerTests.mm
platform/darwin/src/MLNHeatmapStyleLayer.h
platform/darwin/src/MLNHeatmapStyleLayer_Private.h
platform/darwin/src/MLNHeatmapStyleLayer.mm
platform/darwin/test/MLNHeatmapStyleLayerTests.mm
platform/darwin/src/MLNHillshadeStyleLayer.h
platform/darwin/src/MLNHillshadeStyleLayer_Private.h
platform/darwin/src/MLNHillshadeStyleLayer.mm
platform/darwin/test/MLNHillshadeStyleLayerTests.mm
platform/darwin/src/MLNLineStyleLayer.h
platform/darwin/src/MLNLineStyleLayer_Private.h
platform/darwin/src/MLNLineStyleLayer.mm
platform/darwin/test/MLNLineStyleLayerTests.mm
platform/darwin/src/MLNRasterStyleLayer.h
platform/darwin/src/MLNRasterStyleLayer_Private.h
platform/darwin/src/MLNRasterStyleLayer.mm
platform/darwin/test/MLNRasterStyleLayerTests.mm
platform/darwin/src/MLNSymbolStyleLayer.h
platform/darwin/src/MLNSymbolStyleLayer_Private.h
platform/darwin/src/MLNSymbolStyleLayer.mm
platform/darwin/test/MLNSymbolStyleLayerTests.mm
platform/ios/docs/guides/For Style Authors.md
platform/macos/docs/guides/For Style Authors.md
platform/ios/docs/guides/Migrating to Expressions.md

View File

@@ -9,78 +9,78 @@ load("//bazel:flags.bzl", "CPP_FLAGS", "MAPLIBRE_FLAGS", "WARNING_FLAGS")
# this wrong
# A combination of Mapbox.h and all its headers' imports as recursively
_PUBLIC_HEADERS = [
"platform/darwin/src/MGLAnnotation.h",
"platform/darwin/src/MGLAttributedExpression.h",
"platform/darwin/src/MGLAttributionInfo.h",
"platform/darwin/src/MGLBackgroundStyleLayer.h",
"platform/darwin/src/MGLCircleStyleLayer.h",
"platform/darwin/src/MGLClockDirectionFormatter.h",
"platform/darwin/src/MGLCluster.h",
"platform/darwin/src/MGLCompassDirectionFormatter.h",
"platform/darwin/src/MGLComputedShapeSource.h",
"platform/darwin/src/MGLCoordinateFormatter.h",
"platform/darwin/src/MGLDefaultStyle.h",
"platform/darwin/src/MGLDistanceFormatter.h",
"platform/darwin/src/MGLFeature.h",
"platform/darwin/src/MGLFillExtrusionStyleLayer.h",
"platform/darwin/src/MGLFillStyleLayer.h",
"platform/darwin/src/MGLForegroundStyleLayer.h",
"platform/darwin/src/MGLFoundation.h",
"platform/darwin/src/MGLGeometry.h",
"platform/darwin/src/MGLHeatmapStyleLayer.h",
"platform/darwin/src/MGLHillshadeStyleLayer.h",
"platform/darwin/src/MGLImageSource.h",
"platform/darwin/src/MGLLight.h",
"platform/darwin/src/MGLLineStyleLayer.h",
"platform/darwin/src/MGLLocationManager.h",
"platform/darwin/src/MGLLoggingConfiguration.h",
"platform/darwin/src/MGLMapCamera.h",
"platform/darwin/src/MGLMapSnapshotter.h",
"platform/darwin/src/MGLMultiPoint.h",
"platform/darwin/src/MGLNetworkConfiguration.h",
"platform/darwin/src/MGLOfflinePack.h",
"platform/darwin/src/MGLOfflineRegion.h",
"platform/darwin/src/MGLOfflineStorage.h",
"platform/darwin/src/MGLOpenGLStyleLayer.h",
"platform/darwin/src/MGLOverlay.h",
"platform/darwin/src/MGLPointAnnotation.h",
"platform/darwin/src/MGLPointCollection.h",
"platform/darwin/src/MGLPolygon.h",
"platform/darwin/src/MGLPolyline.h",
"platform/darwin/src/MGLRasterDEMSource.h",
"platform/darwin/src/MGLRasterStyleLayer.h",
"platform/darwin/src/MGLRasterTileSource.h",
"platform/darwin/src/MGLSettings.h",
"platform/darwin/src/MGLShape.h",
"platform/darwin/src/MGLShapeCollection.h",
"platform/darwin/src/MGLShapeOfflineRegion.h",
"platform/darwin/src/MGLShapeSource.h",
"platform/darwin/src/MGLSource.h",
"platform/darwin/src/MGLStyle.h",
"platform/darwin/src/MGLStyleLayer.h",
"platform/darwin/src/MGLStyleValue.h",
"platform/darwin/src/MGLSymbolStyleLayer.h",
"platform/darwin/src/MGLTilePyramidOfflineRegion.h",
"platform/darwin/src/MGLTileServerOptions.h",
"platform/darwin/src/MGLTileSource.h",
"platform/darwin/src/MGLTypes.h",
"platform/darwin/src/MGLVectorStyleLayer.h",
"platform/darwin/src/MGLVectorTileSource.h",
"platform/darwin/src/NSExpression+MGLAdditions.h",
"platform/darwin/src/NSPredicate+MGLAdditions.h",
"platform/darwin/src/NSValue+MGLAdditions.h",
"platform/ios/src/MGLAnnotationImage.h",
"platform/ios/src/MGLAnnotationView.h",
"platform/ios/src/MGLCalloutView.h",
"platform/ios/src/MGLCameraChangeReason.h",
"platform/ios/src/MGLCompassButton.h",
"platform/ios/src/MGLMapProjection.h",
"platform/ios/src/MGLMapView+IBAdditions.h",
"platform/ios/src/MGLMapView.h",
"platform/ios/src/MGLMapViewDelegate.h",
"platform/ios/src/MGLUserLocation.h",
"platform/ios/src/MGLUserLocationAnnotationView.h",
"platform/ios/src/MGLUserLocationAnnotationViewStyle.h",
"platform/darwin/src/MLNAnnotation.h",
"platform/darwin/src/MLNAttributedExpression.h",
"platform/darwin/src/MLNAttributionInfo.h",
"platform/darwin/src/MLNBackgroundStyleLayer.h",
"platform/darwin/src/MLNCircleStyleLayer.h",
"platform/darwin/src/MLNClockDirectionFormatter.h",
"platform/darwin/src/MLNCluster.h",
"platform/darwin/src/MLNCompassDirectionFormatter.h",
"platform/darwin/src/MLNComputedShapeSource.h",
"platform/darwin/src/MLNCoordinateFormatter.h",
"platform/darwin/src/MLNDefaultStyle.h",
"platform/darwin/src/MLNDistanceFormatter.h",
"platform/darwin/src/MLNFeature.h",
"platform/darwin/src/MLNFillExtrusionStyleLayer.h",
"platform/darwin/src/MLNFillStyleLayer.h",
"platform/darwin/src/MLNForegroundStyleLayer.h",
"platform/darwin/src/MLNFoundation.h",
"platform/darwin/src/MLNGeometry.h",
"platform/darwin/src/MLNHeatmapStyleLayer.h",
"platform/darwin/src/MLNHillshadeStyleLayer.h",
"platform/darwin/src/MLNImageSource.h",
"platform/darwin/src/MLNLight.h",
"platform/darwin/src/MLNLineStyleLayer.h",
"platform/darwin/src/MLNLocationManager.h",
"platform/darwin/src/MLNLoggingConfiguration.h",
"platform/darwin/src/MLNMapCamera.h",
"platform/darwin/src/MLNMapSnapshotter.h",
"platform/darwin/src/MLNMultiPoint.h",
"platform/darwin/src/MLNNetworkConfiguration.h",
"platform/darwin/src/MLNOfflinePack.h",
"platform/darwin/src/MLNOfflineRegion.h",
"platform/darwin/src/MLNOfflineStorage.h",
"platform/darwin/src/MLNOpenGLStyleLayer.h",
"platform/darwin/src/MLNOverlay.h",
"platform/darwin/src/MLNPointAnnotation.h",
"platform/darwin/src/MLNPointCollection.h",
"platform/darwin/src/MLNPolygon.h",
"platform/darwin/src/MLNPolyline.h",
"platform/darwin/src/MLNRasterDEMSource.h",
"platform/darwin/src/MLNRasterStyleLayer.h",
"platform/darwin/src/MLNRasterTileSource.h",
"platform/darwin/src/MLNSettings.h",
"platform/darwin/src/MLNShape.h",
"platform/darwin/src/MLNShapeCollection.h",
"platform/darwin/src/MLNShapeOfflineRegion.h",
"platform/darwin/src/MLNShapeSource.h",
"platform/darwin/src/MLNSource.h",
"platform/darwin/src/MLNStyle.h",
"platform/darwin/src/MLNStyleLayer.h",
"platform/darwin/src/MLNStyleValue.h",
"platform/darwin/src/MLNSymbolStyleLayer.h",
"platform/darwin/src/MLNTilePyramidOfflineRegion.h",
"platform/darwin/src/MLNTileServerOptions.h",
"platform/darwin/src/MLNTileSource.h",
"platform/darwin/src/MLNTypes.h",
"platform/darwin/src/MLNVectorStyleLayer.h",
"platform/darwin/src/MLNVectorTileSource.h",
"platform/darwin/src/NSExpression+MLNAdditions.h",
"platform/darwin/src/NSPredicate+MLNAdditions.h",
"platform/darwin/src/NSValue+MLNAdditions.h",
"platform/ios/src/MLNAnnotationImage.h",
"platform/ios/src/MLNAnnotationView.h",
"platform/ios/src/MLNCalloutView.h",
"platform/ios/src/MLNCameraChangeReason.h",
"platform/ios/src/MLNCompassButton.h",
"platform/ios/src/MLNMapProjection.h",
"platform/ios/src/MLNMapView+IBAdditions.h",
"platform/ios/src/MLNMapView.h",
"platform/ios/src/MLNMapViewDelegate.h",
"platform/ios/src/MLNUserLocation.h",
"platform/ios/src/MLNUserLocationAnnotationView.h",
"platform/ios/src/MLNUserLocationAnnotationViewStyle.h",
]
apple_static_xcframework(
@@ -190,74 +190,74 @@ apple_resource_bundle(
objc_library(
name = "objcpp-sdk",
srcs = [
"platform/darwin/src/MGLAttributionInfo.mm",
"platform/darwin/src/MGLBackgroundStyleLayer.mm",
"platform/darwin/src/MGLCircleStyleLayer.mm",
"platform/darwin/src/MGLComputedShapeSource.mm",
"platform/darwin/src/MGLDefaultStyle.mm",
"platform/darwin/src/MGLFeature.mm",
"platform/darwin/src/MGLFillExtrusionStyleLayer.mm",
"platform/darwin/src/MGLFillStyleLayer.mm",
"platform/darwin/src/MGLForegroundStyleLayer.mm",
"platform/darwin/src/MGLFoundation.mm",
"platform/darwin/src/MGLGeometry.mm",
"platform/darwin/src/MGLHeatmapStyleLayer.mm",
"platform/darwin/src/MGLHillshadeStyleLayer.mm",
"platform/darwin/src/MGLImageSource.mm",
"platform/darwin/src/MGLLight.mm",
"platform/darwin/src/MGLLineStyleLayer.mm",
"platform/darwin/src/MGLLoggingConfiguration.mm",
"platform/darwin/src/MGLMapCamera.mm",
"platform/darwin/src/MGLMapSnapshotter.mm",
"platform/darwin/src/MGLMultiPoint.mm",
"platform/darwin/src/MGLNetworkConfiguration.mm",
"platform/darwin/src/MGLOfflinePack.mm",
"platform/darwin/src/MGLOfflineStorage.mm",
"platform/darwin/src/MGLOpenGLStyleLayer.mm",
"platform/darwin/src/MGLPointAnnotation.mm",
"platform/darwin/src/MGLPointCollection.mm",
"platform/darwin/src/MGLPolygon.mm",
"platform/darwin/src/MGLPolyline.mm",
"platform/darwin/src/MGLRasterDEMSource.mm",
"platform/darwin/src/MGLRasterStyleLayer.mm",
"platform/darwin/src/MGLRasterTileSource.mm",
"platform/darwin/src/MGLSettings.mm",
"platform/darwin/src/MGLShape.mm",
"platform/darwin/src/MGLShapeCollection.mm",
"platform/darwin/src/MGLShapeOfflineRegion.mm",
"platform/darwin/src/MGLShapeSource.mm",
"platform/darwin/src/MGLSource.mm",
"platform/darwin/src/MGLStyle.mm",
"platform/darwin/src/MGLStyleLayer.mm",
"platform/darwin/src/MGLStyleLayerManager.mm",
"platform/darwin/src/MGLStyleValue.mm",
"platform/darwin/src/MGLSymbolStyleLayer.mm",
"platform/darwin/src/MGLTilePyramidOfflineRegion.mm",
"platform/darwin/src/MGLTileServerOptions.mm",
"platform/darwin/src/MGLTileSource.mm",
"platform/darwin/src/MGLVectorStyleLayer.mm",
"platform/darwin/src/MGLVectorTileSource.mm",
"platform/darwin/src/NSArray+MGLAdditions.mm",
"platform/darwin/src/NSBundle+MGLAdditions.mm",
"platform/darwin/src/NSCoder+MGLAdditions.mm",
"platform/darwin/src/NSComparisonPredicate+MGLAdditions.mm",
"platform/darwin/src/NSCompoundPredicate+MGLAdditions.mm",
"platform/darwin/src/NSDate+MGLAdditions.mm",
"platform/darwin/src/NSDictionary+MGLAdditions.mm",
"platform/darwin/src/NSExpression+MGLAdditions.mm",
"platform/darwin/src/NSPredicate+MGLAdditions.mm",
"platform/darwin/src/NSValue+MGLStyleAttributeAdditions.mm",
"platform/ios/src/MGLAnnotationView.mm",
"platform/ios/src/MGLCompassButton.mm",
"platform/ios/src/MGLFaux3DUserLocationAnnotationView.mm",
"platform/ios/src/MGLMapAccessibilityElement.mm",
"platform/ios/src/MGLMapProjection.mm",
"platform/ios/src/MGLMapView.mm",
"platform/ios/src/MGLMapView+Impl.mm",
"platform/ios/src/MGLMapView+OpenGL.mm",
"platform/ios/src/MGLScaleBar.mm",
"platform/ios/src/UIColor+MGLAdditions.mm",
"platform/ios/src/UIImage+MGLAdditions.mm",
"platform/darwin/src/MLNAttributionInfo.mm",
"platform/darwin/src/MLNBackgroundStyleLayer.mm",
"platform/darwin/src/MLNCircleStyleLayer.mm",
"platform/darwin/src/MLNComputedShapeSource.mm",
"platform/darwin/src/MLNDefaultStyle.mm",
"platform/darwin/src/MLNFeature.mm",
"platform/darwin/src/MLNFillExtrusionStyleLayer.mm",
"platform/darwin/src/MLNFillStyleLayer.mm",
"platform/darwin/src/MLNForegroundStyleLayer.mm",
"platform/darwin/src/MLNFoundation.mm",
"platform/darwin/src/MLNGeometry.mm",
"platform/darwin/src/MLNHeatmapStyleLayer.mm",
"platform/darwin/src/MLNHillshadeStyleLayer.mm",
"platform/darwin/src/MLNImageSource.mm",
"platform/darwin/src/MLNLight.mm",
"platform/darwin/src/MLNLineStyleLayer.mm",
"platform/darwin/src/MLNLoggingConfiguration.mm",
"platform/darwin/src/MLNMapCamera.mm",
"platform/darwin/src/MLNMapSnapshotter.mm",
"platform/darwin/src/MLNMultiPoint.mm",
"platform/darwin/src/MLNNetworkConfiguration.mm",
"platform/darwin/src/MLNOfflinePack.mm",
"platform/darwin/src/MLNOfflineStorage.mm",
"platform/darwin/src/MLNOpenGLStyleLayer.mm",
"platform/darwin/src/MLNPointAnnotation.mm",
"platform/darwin/src/MLNPointCollection.mm",
"platform/darwin/src/MLNPolygon.mm",
"platform/darwin/src/MLNPolyline.mm",
"platform/darwin/src/MLNRasterDEMSource.mm",
"platform/darwin/src/MLNRasterStyleLayer.mm",
"platform/darwin/src/MLNRasterTileSource.mm",
"platform/darwin/src/MLNSettings.mm",
"platform/darwin/src/MLNShape.mm",
"platform/darwin/src/MLNShapeCollection.mm",
"platform/darwin/src/MLNShapeOfflineRegion.mm",
"platform/darwin/src/MLNShapeSource.mm",
"platform/darwin/src/MLNSource.mm",
"platform/darwin/src/MLNStyle.mm",
"platform/darwin/src/MLNStyleLayer.mm",
"platform/darwin/src/MLNStyleLayerManager.mm",
"platform/darwin/src/MLNStyleValue.mm",
"platform/darwin/src/MLNSymbolStyleLayer.mm",
"platform/darwin/src/MLNTilePyramidOfflineRegion.mm",
"platform/darwin/src/MLNTileServerOptions.mm",
"platform/darwin/src/MLNTileSource.mm",
"platform/darwin/src/MLNVectorStyleLayer.mm",
"platform/darwin/src/MLNVectorTileSource.mm",
"platform/darwin/src/NSArray+MLNAdditions.mm",
"platform/darwin/src/NSBundle+MLNAdditions.mm",
"platform/darwin/src/NSCoder+MLNAdditions.mm",
"platform/darwin/src/NSComparisonPredicate+MLNAdditions.mm",
"platform/darwin/src/NSCompoundPredicate+MLNAdditions.mm",
"platform/darwin/src/NSDate+MLNAdditions.mm",
"platform/darwin/src/NSDictionary+MLNAdditions.mm",
"platform/darwin/src/NSExpression+MLNAdditions.mm",
"platform/darwin/src/NSPredicate+MLNAdditions.mm",
"platform/darwin/src/NSValue+MLNStyleAttributeAdditions.mm",
"platform/ios/src/MLNAnnotationView.mm",
"platform/ios/src/MLNCompassButton.mm",
"platform/ios/src/MLNFaux3DUserLocationAnnotationView.mm",
"platform/ios/src/MLNMapAccessibilityElement.mm",
"platform/ios/src/MLNMapProjection.mm",
"platform/ios/src/MLNMapView.mm",
"platform/ios/src/MLNMapView+Impl.mm",
"platform/ios/src/MLNMapView+OpenGL.mm",
"platform/ios/src/MLNScaleBar.mm",
"platform/ios/src/UIColor+MLNAdditions.mm",
"platform/ios/src/UIImage+MLNAdditions.mm",
],
copts = CPP_FLAGS + MAPLIBRE_FLAGS + [
"-fcxx-modules",
@@ -291,33 +291,33 @@ objc_library(
objc_library(
name = "objc-sdk",
srcs = [
"platform/darwin/src/MGLAttributedExpression.m",
"platform/darwin/src/MGLClockDirectionFormatter.m",
"platform/darwin/src/MGLCompassDirectionFormatter.m",
"platform/darwin/src/MGLCoordinateFormatter.m",
"platform/darwin/src/MGLDistanceFormatter.m",
"platform/darwin/src/MGLLocationManager.m",
"platform/darwin/src/MGLReachability.m",
"platform/darwin/src/MGLRendererConfiguration.m",
"platform/darwin/src/MGLTypes.m",
"platform/darwin/src/NSString+MGLAdditions.m",
"platform/darwin/src/NSURL+MGLAdditions.m",
"platform/darwin/src/NSValue+MGLAdditions.m",
"platform/ios/src/MGLAnnotationContainerView.m",
"platform/ios/src/MGLAnnotationImage.m",
"platform/ios/src/MGLCompactCalloutView.m",
"platform/ios/src/MGLUserLocation.m",
"platform/ios/src/MGLUserLocationAnnotationView.m",
"platform/ios/src/MGLUserLocationAnnotationViewStyle.m",
"platform/ios/src/MGLUserLocationHeadingArrowLayer.m",
"platform/ios/src/MGLUserLocationHeadingBeamLayer.m",
"platform/ios/src/NSOrthography+MGLAdditions.m",
"platform/ios/src/UIDevice+MGLAdditions.m",
"platform/ios/src/UIView+MGLAdditions.m",
"platform/ios/src/UIViewController+MGLAdditions.m",
"platform/darwin/src/MLNAttributedExpression.m",
"platform/darwin/src/MLNClockDirectionFormatter.m",
"platform/darwin/src/MLNCompassDirectionFormatter.m",
"platform/darwin/src/MLNCoordinateFormatter.m",
"platform/darwin/src/MLNDistanceFormatter.m",
"platform/darwin/src/MLNLocationManager.m",
"platform/darwin/src/MLNReachability.m",
"platform/darwin/src/MLNRendererConfiguration.m",
"platform/darwin/src/MLNTypes.m",
"platform/darwin/src/NSString+MLNAdditions.m",
"platform/darwin/src/NSURL+MLNAdditions.m",
"platform/darwin/src/NSValue+MLNAdditions.m",
"platform/ios/src/MLNAnnotationContainerView.m",
"platform/ios/src/MLNAnnotationImage.m",
"platform/ios/src/MLNCompactCalloutView.m",
"platform/ios/src/MLNUserLocation.m",
"platform/ios/src/MLNUserLocationAnnotationView.m",
"platform/ios/src/MLNUserLocationAnnotationViewStyle.m",
"platform/ios/src/MLNUserLocationHeadingArrowLayer.m",
"platform/ios/src/MLNUserLocationHeadingBeamLayer.m",
"platform/ios/src/NSOrthography+MLNAdditions.m",
"platform/ios/src/UIDevice+MLNAdditions.m",
"platform/ios/src/UIView+MLNAdditions.m",
"platform/ios/src/UIViewController+MLNAdditions.m",
],
hdrs = [
"platform/darwin/include/mbgl/util/image+MGLAdditions.hpp",
"platform/darwin/include/mbgl/util/image+MLNAdditions.hpp",
],
copts = WARNING_FLAGS + MAPLIBRE_FLAGS + [
"-fmodules",

View File

@@ -1,5 +1,5 @@
#import <Mapbox/Mapbox.h>
@interface LimeGreenStyleLayer : MGLOpenGLStyleLayer
@interface LimeGreenStyleLayer : MLNOpenGLStyleLayer
@end

View File

@@ -9,7 +9,7 @@
GLuint _aPos;
}
- (void)didMoveToMapView:(MGLMapView *)mapView {
- (void)didMoveToMapView:(MLNMapView *)mapView {
static const GLchar *vertexShaderSource = "attribute vec2 a_pos; void main() { gl_Position = vec4(a_pos, 1, 1); }";
static const GLchar *fragmentShaderSource = "void main() { gl_FragColor = vec4(0, 0.5, 0, 0.5); }";
@@ -32,7 +32,7 @@
glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(GLfloat), triangle, GL_STATIC_DRAW);
}
- (void)drawInMapView:(MGLMapView *)mapView withContext:(MGLStyleLayerDrawingContext)context {
- (void)drawInMapView:(MLNMapView *)mapView withContext:(MLNStyleLayerDrawingContext)context {
glUseProgram(_program);
glBindBuffer(GL_ARRAY_BUFFER, _buffer);
glEnableVertexAttribArray(_aPos);
@@ -42,7 +42,7 @@
glDrawArrays(GL_TRIANGLE_STRIP, 0, 3);
}
- (void)willMoveFromMapView:(MGLMapView *)mapView {
- (void)willMoveFromMapView:(MLNMapView *)mapView {
if (!_program) {
return;
}

View File

@@ -1,10 +1,10 @@
# Customizing Fonts
The Mapbox Maps SDK can render text that is part of an `MGLSymbolStyleLayer` in a font of your choice. The font customization options discussed in this document do not apply to user interface elements such as the scale bar or annotation callout views.
The Mapbox Maps SDK can render text that is part of an `MLNSymbolStyleLayer` in a font of your choice. The font customization options discussed in this document do not apply to user interface elements such as the scale bar or annotation callout views.
## Server-side fonts
By default, the map renders characters using glyphs downloaded from the [Mapbox Fonts API](https://docs.mapbox.com/api/maps/#fonts). You apply fonts in [Mapbox Studio](https://studio.mapbox.com/), in the `text-font` layout property in style JSON, or in the `MGLSymbolStyleLayer.textFontNames` property at runtime. The values in these properties must be font display names, not font family names or PostScript names.
By default, the map renders characters using glyphs downloaded from the [Mapbox Fonts API](https://docs.mapbox.com/api/maps/#fonts). You apply fonts in [Mapbox Studio](https://studio.mapbox.com/), in the `text-font` layout property in style JSON, or in the `MLNSymbolStyleLayer.textFontNames` property at runtime. The values in these properties must be font display names, not font family names or PostScript names.
Each font name in the list must match a font that is registered in Mapbox Studio; otherwise, the text will not load, even if one of the fonts is available. Each font name must be included in the `{fontstack}` portion of the JSON stylesheet’s [`glyphs`](https://docs.mapbox.com/mapbox-gl-js/style-spec/glyphs/) property.
@@ -12,10 +12,10 @@ Each font name in the list must match a font that is registered in Mapbox Studio
By default, Chinese hanzi, Japanese kana, and Korean hangul characters (CJK) are rendered on the client side. Client-side text rendering uses less bandwidth than server-side text rendering, especially when viewing regions of the map that feature a wide variety of CJK characters.
First, the map attempts to apply a font that you specify the same way as you would specify a server-side font: in [Mapbox Studio](https://studio.mapbox.com/), in the `text-font` layout property in style JSON, or in the `MGLSymbolStyleLayer.textFontNames` property at runtime. Instead of downloading the glyphs, the map tries to find a [system font](https://developer.apple.com/fonts/system-fonts/) or a font [bundled with your application](https://developer.apple.com/documentation/uikit/text_display_and_fonts/adding_a_custom_font_to_your_app) that matches one of these fonts based on its family name (for example, “PingFang TC”), display name (“PingFang TC Ultralight”), or PostScript name (“PingFangTC-Ultralight”).
First, the map attempts to apply a font that you specify the same way as you would specify a server-side font: in [Mapbox Studio](https://studio.mapbox.com/), in the `text-font` layout property in style JSON, or in the `MLNSymbolStyleLayer.textFontNames` property at runtime. Instead of downloading the glyphs, the map tries to find a [system font](https://developer.apple.com/fonts/system-fonts/) or a font [bundled with your application](https://developer.apple.com/documentation/uikit/text_display_and_fonts/adding_a_custom_font_to_your_app) that matches one of these fonts based on its family name (for example, “PingFang TC”), display name (“PingFang TC Ultralight”), or PostScript name (“PingFangTC-Ultralight”).
If the symbol layer does not specify an available font that contains the required glyphs, then the map tries to find a matching font in the [`MGLIdeographicFontFamilyName`](infoplist-keys.html#mglideographicfontfamilyname) Info.plist key. Like the `MGLSymbolStyleLayer.textFontNames` property, this key can contain a family name, display name, or PostScript name. This key is a global fallback that applies to all layers uniformly. It can either be a single string or an array of strings, which the map tries to apply in order from most preferred to least preferred.
If the symbol layer does not specify an available font that contains the required glyphs, then the map tries to find a matching font in the [`MLNIdeographicFontFamilyName`](infoplist-keys.html#mglideographicfontfamilyname) Info.plist key. Like the `MLNSymbolStyleLayer.textFontNames` property, this key can contain a family name, display name, or PostScript name. This key is a global fallback that applies to all layers uniformly. It can either be a single string or an array of strings, which the map tries to apply in order from most preferred to least preferred.
Each character is rendered in the first font you specify that has a glyph for the character. If the entire list of fonts is exhausted, the map uses the system’s font cascade list, which may vary based on the device model and system language.
To disable client-side rendering of CJK characters, set the `MGLIdeographicFontFamilyName` key to the Boolean value `NO`. The map will revert to server-side font rendering.
To disable client-side rendering of CJK characters, set the `MLNIdeographicFontFamilyName` key to the Boolean value `NO`. The map will revert to server-side font rendering.

View File

@@ -82,8 +82,8 @@ By default, this SDK makes it easy for your users to rotate or tilt the map
using multitouch trackpad gestures or keyboard shortcuts.
<% } -%>
If you do not intend your design to accommodate rotation and tilting, disable
these gestures using the `MGLMapView.rotateEnabled` and
`MGLMapView.pitchEnabled` properties, respectively, or the corresponding
these gestures using the `MLNMapView.rotateEnabled` and
`MLNMapView.pitchEnabled` properties, respectively, or the corresponding
inspectables in Interface Builder.
### Interactivity
@@ -97,7 +97,7 @@ An icon with a shadow or shading effect may appear to be clickable.
<% } -%>
You can make an icon or text label interactive by installing a gesture
recognizer and performing feature querying (e.g.,
`-[MGLMapView visibleFeaturesAtPoint:]`) to get details about the selected
`-[MLNMapView visibleFeaturesAtPoint:]`) to get details about the selected
feature.
<% if (macOS) { -%>
You can install cursor or tooltip tracking rectangles to indicate interactive
@@ -130,8 +130,8 @@ For more information about user interface design, consult Apple’s
## Applying your style
You set an `MGLMapView` object’s style either in code, by setting the
`MGLMapView.styleURL` property, or in Interface Builder, by setting the “Style
You set an `MLNMapView` object’s style either in code, by setting the
`MLNMapView.styleURL` property, or in Interface Builder, by setting the “Style
URL” inspectable. The URL must point to a local or remote style JSON file. The
style JSON file format is defined by the
[Mapbox Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/). This
@@ -143,8 +143,8 @@ otherwise noted in the
The _runtime styling API_ enables you to modify every aspect of a style
dynamically as a user interacts with your application. The style itself is
represented at runtime by an `MGLStyle` object, which provides access to various
`MGLSource` and `MGLStyleLayer` objects that represent content sources and style
represented at runtime by an `MLNStyle` object, which provides access to various
`MLNSource` and `MLNStyleLayer` objects that represent content sources and style
layers, respectively.
<% if (iOS) { -%>
For more information about the capabilities exposed by the runtime styling API,
@@ -174,15 +174,15 @@ source | content source
Each source defined by a style JSON file is represented at runtime by a content
source object that you can use to initialize new style layers. The content
source object is a member of one of the following subclasses of `MGLSource`:
source object is a member of one of the following subclasses of `MLNSource`:
In style JSON | In the SDK
--------------|-----------
`vector` | `MGLVectorTileSource`
`raster` | `MGLRasterTileSource`
`raster-dem` | `MGLRasterDEMSource`
`geojson` | `MGLShapeSource`
`image` | `MGLImageSource`
`vector` | `MLNVectorTileSource`
`raster` | `MLNRasterTileSource`
`raster-dem` | `MLNRasterDEMSource`
`geojson` | `MLNShapeSource`
`image` | `MLNImageSource`
`canvas` and `video` sources are not supported.
@@ -194,56 +194,56 @@ subset of the keys defined in version 2.1.0 of the
[TileJSON](https://github.com/mapbox/tilejson-spec/tree/master/2.1.0)
specification. As an alternative to authoring a custom TileJSON file, you may
supply various tile source options when creating a raster or vector tile source.
These options are detailed in the `MGLTileSourceOption` documentation:
These options are detailed in the `MLNTileSourceOption` documentation:
In style JSON | In TileJSON | In the SDK
--------------|---------------|-----------
`url` | — | `configurationURL` parameter in `-[MGLTileSource initWithIdentifier:configurationURL:]`
`tiles` | `tiles` | `tileURLTemplates` parameter in `-[MGLTileSource initWithIdentifier:tileURLTemplates:options:]`
`minzoom` | `minzoom` | `MGLTileSourceOptionMinimumZoomLevel`
`maxzoom` | `maxzoom` | `MGLTileSourceOptionMaximumZoomLevel`
`bounds` | `bounds` | `MGLTileSourceOptionCoordinateBounds`
`tileSize` | — | `MGLTileSourceOptionTileSize`
`attribution` | `attribution` | `MGLTileSourceOptionAttributionHTMLString` (but consider specifying `MGLTileSourceOptionAttributionInfos` instead for improved security)
`scheme` | `scheme` | `MGLTileSourceOptionTileCoordinateSystem`
`encoding` | – | `MGLTileSourceOptionDEMEncoding`
`url` | — | `configurationURL` parameter in `-[MLNTileSource initWithIdentifier:configurationURL:]`
`tiles` | `tiles` | `tileURLTemplates` parameter in `-[MLNTileSource initWithIdentifier:tileURLTemplates:options:]`
`minzoom` | `minzoom` | `MLNTileSourceOptionMinimumZoomLevel`
`maxzoom` | `maxzoom` | `MLNTileSourceOptionMaximumZoomLevel`
`bounds` | `bounds` | `MLNTileSourceOptionCoordinateBounds`
`tileSize` | — | `MLNTileSourceOptionTileSize`
`attribution` | `attribution` | `MLNTileSourceOptionAttributionHTMLString` (but consider specifying `MLNTileSourceOptionAttributionInfos` instead for improved security)
`scheme` | `scheme` | `MLNTileSourceOptionTileCoordinateSystem`
`encoding` | – | `MLNTileSourceOptionDEMEncoding`
### Shape sources
Shape sources also accept various options. These options are detailed in the
`MGLShapeSourceOption` documentation:
`MLNShapeSourceOption` documentation:
In style JSON | In the SDK
-----------------|-----------
`data` | `url` parameter in `-[MGLShapeSource initWithIdentifier:URL:options:]`
`maxzoom` | `MGLShapeSourceOptionMaximumZoomLevel`
`buffer` | `MGLShapeSourceOptionBuffer`
`tolerance` | `MGLShapeSourceOptionSimplificationTolerance`
`cluster` | `MGLShapeSourceOptionClustered`
`clusterRadius` | `MGLShapeSourceOptionClusterRadius`
`clusterMaxZoom` | `MGLShapeSourceOptionMaximumZoomLevelForClustering`
`lineMetrics` | `MGLShapeSourceOptionLineDistanceMetrics`
`data` | `url` parameter in `-[MLNShapeSource initWithIdentifier:URL:options:]`
`maxzoom` | `MLNShapeSourceOptionMaximumZoomLevel`
`buffer` | `MLNShapeSourceOptionBuffer`
`tolerance` | `MLNShapeSourceOptionSimplificationTolerance`
`cluster` | `MLNShapeSourceOptionClustered`
`clusterRadius` | `MLNShapeSourceOptionClusterRadius`
`clusterMaxZoom` | `MLNShapeSourceOptionMaximumZoomLevelForClustering`
`lineMetrics` | `MLNShapeSourceOptionLineDistanceMetrics`
To create a shape source from local GeoJSON data, first
[convert the GeoJSON data into a shape](working-with-geojson-data.html#converting-geojson-data-into-shape-objects),
then use the `-[MGLShapeSource initWithIdentifier:shape:options:]` method.
then use the `-[MLNShapeSource initWithIdentifier:shape:options:]` method.
### Image sources
Image sources accept a non-axis aligned quadrilateral as their geographic coordinates.
These coordinates, in `MGLCoordinateQuad`, are described in counterclockwise order,
These coordinates, in `MLNCoordinateQuad`, are described in counterclockwise order,
in contrast to the clockwise order defined in the style specification.
## Configuring the map content’s appearance
Each layer defined by the style JSON file is represented at runtime by a style
layer object, which you can use to refine the map’s appearance. The style layer
object is a member of one of the following subclasses of `MGLStyleLayer`:
object is a member of one of the following subclasses of `MLNStyleLayer`:
In style JSON | In the SDK
--------------|-----------
<% for (const layer of layers) { -%>
`<%- layer.type %>` | `MGL<%- camelize(layer.type) %>StyleLayer`
`<%- layer.type %>` | `MLN<%- camelize(layer.type) %>StyleLayer`
<% } -%>
You configure layout and paint attributes by setting properties on these style
@@ -259,7 +259,7 @@ In style JSON | In Objective-C | In Swift
--------------|----------------|---------
<% for (const name in renamedProperties[type]) { -%>
<% if (renamedProperties[type].hasOwnProperty(name)) { -%>
`<%- originalPropertyName(renamedProperties[type][name]) %>` | `MGL<%- camelize(type) %>StyleLayer.<%- objCName(renamedProperties[type][name]) %>` | `MGL<%- camelize(type) %>StyleLayer.<%- objCGetter(renamedProperties[type][name]) %>`
`<%- originalPropertyName(renamedProperties[type][name]) %>` | `MLN<%- camelize(type) %>StyleLayer.<%- objCName(renamedProperties[type][name]) %>` | `MLN<%- camelize(type) %>StyleLayer.<%- objCGetter(renamedProperties[type][name]) %>`
<% } -%>
<% } -%>
<% } -%>
@@ -358,13 +358,13 @@ In style specification | Method, function, or predicate type | Format string syn
`>=` | `NSGreaterThanOrEqualToPredicateOperatorType` | `key >= value`
`all` | `NSAndPredicateType` | `p0 AND … AND pn`
`any` | `NSOrPredicateType` | `p0 OR … OR pn`
`case` | `+[NSExpression expressionForConditional:trueExpression:falseExpression:]` or `MGL_IF` or `+[NSExpression mgl_expressionForConditional:trueExpression:falseExpresssion:]` | `TERNARY(1 = 2, YES, NO)` or `MGL_IF(1 = 2, YES, 2 = 2, YES, NO)`
`case` | `+[NSExpression expressionForConditional:trueExpression:falseExpression:]` or `MLN_IF` or `+[NSExpression mgl_expressionForConditional:trueExpression:falseExpresssion:]` | `TERNARY(1 = 2, YES, NO)` or `MLN_IF(1 = 2, YES, 2 = 2, YES, NO)`
`coalesce` | `mgl_coalesce:` | `mgl_coalesce({x, y, z})`
`match` | `MGL_MATCH` or `+[NSExpression mgl_expressionForMatchingExpression:inDictionary:defaultExpression:]` | `MGL_MATCH(x, 0, 'zero match', 1, 'one match', 'two match', 'default')`
`within` | `NSInPredicateOperatorType` | `SELF IN %@` or `%@ CONTAINS SELF` where `%@` is an `MGLShape`
`match` | `MLN_MATCH` or `+[NSExpression mgl_expressionForMatchingExpression:inDictionary:defaultExpression:]` | `MLN_MATCH(x, 0, 'zero match', 1, 'one match', 'two match', 'default')`
`within` | `NSInPredicateOperatorType` | `SELF IN %@` or `%@ CONTAINS SELF` where `%@` is an `MLNShape`
`interpolate` | `mgl_interpolate:withCurveType:parameters:stops:` or `+[NSExpression mgl_expressionForInterpolatingExpression:withCurveType:parameters:stops:]` |
`step` | `mgl_step:from:stops:` or `+[NSExpression mgl_expressionForSteppingExpression:fromExpression:stops:]` |
`let` | `mgl_expressionWithContext:` | `MGL_LET('ios', 11, 'macos', 10.13, $ios + $macos)`
`let` | `mgl_expressionWithContext:` | `MLN_LET('ios', 11, 'macos', 10.13, $ios + $macos)`
`var` | `+[NSExpression expressionForVariable:]` | `$variable`
`concat` | `mgl_join:` or `-[NSExpression mgl_expressionByAppendingExpression:]` | `mgl_join({'Old', ' ', 'MacDonald'})`
`downcase` | `lowercase:` | `lowercase('DOWNTOWN')`
@@ -389,7 +389,7 @@ In style specification | Method, function, or predicate type | Format string syn
`atan` | `mgl_atan:` | `mgl_atan(20)`
`ceil` | `ceiling:` | `ceiling(0.99999)`
`cos` | `mgl_cos:` | `mgl_cos(0)`
`distance` | | `mgl_distanceFrom(%@)` where `%@` is an `MGLShape`
`distance` | | `mgl_distanceFrom(%@)` where `%@` is an `MLNShape`
`e` | | `%@` representing `NSNumber` containing `M_E`
`floor` | `floor:` | `floor(-0.99999)`
`ln` | `ln:` | `ln(2)`
@@ -409,12 +409,12 @@ In style specification | Method, function, or predicate type | Format string syn
`format` | `+[NSExpression mgl_expressionForAttributedExpressions:]` or `mgl_attributed:` | `mgl_attributed({x, y, z})`
For operators that have no corresponding `NSExpression` symbol, use the
`MGL_FUNCTION()` format string syntax.
`MLN_FUNCTION()` format string syntax.
## Filtering sources
You can filter a shape or vector tile source by setting the
`MGLVectorStyleLayer.predicate` property to an `NSPredicate` object. Below is a
`MLNVectorStyleLayer.predicate` property to an `NSPredicate` object. Below is a
table of style JSON operators and the corresponding operators used in the
predicate format string:
@@ -437,13 +437,13 @@ In style JSON | In the format string
## Specifying the text format
The following format attributes are defined as `NSString` constans that you
can use to update the formatting of `MGLSymbolStyleLayer.text` property.
can use to update the formatting of `MLNSymbolStyleLayer.text` property.
In style JSON | In Objective-C | In Swift
--------------|-----------------------|---------
`text-font` | `MGLFontNamesAttribute` | `.fontNamesAttribute`
`font-scale` | `MGLFontScaleAttribute` | `.fontScaleAttribute`
`text-color` | `MGLFontColorAttribute` | `.fontColorAttribute`
`text-font` | `MLNFontNamesAttribute` | `.fontNamesAttribute`
`font-scale` | `MLNFontScaleAttribute` | `.fontScaleAttribute`
`text-color` | `MLNFontColorAttribute` | `.fontColorAttribute`
See the “[Predicates and Expressions](predicates-and-expressions.html)” guide for
a full description of the supported operators and operand types.

View File

@@ -34,11 +34,11 @@ Style function syntax:
```swift
let stops = [
0: MGLStyleValue<UIColor>(rawValue: .yellow),
2.5: MGLStyleValue(rawValue: .orange),
5: MGLStyleValue(rawValue: .red),
7.5: MGLStyleValue(rawValue: .blue),
10: MGLStyleValue(rawValue: .white),
0: MLNStyleValue<UIColor>(rawValue: .yellow),
2.5: MLNStyleValue(rawValue: .orange),
5: MLNStyleValue(rawValue: .red),
7.5: MLNStyleValue(rawValue: .blue),
10: MLNStyleValue(rawValue: .white),
]
```
@@ -52,7 +52,7 @@ Style functions supported four interpolation modes: exponential/linear, interval
### Linear
`+[NSExpression(MGLAdditions) mgl_expressionForInterpolatingExpression:withCurveType:parameters:stops:]` takes the interpolation type as a parameter. If you previously used the default interpolation base, use the curve type `MGLExpressionInterpolationMode.linear`. See the [`mgl_interpolate:withCurveType:parameters:stops:`](predicates-and-expressions.html#code-mgl_interpolate-withcurvetype-parameters-stops-code) documentation for more details.
`+[NSExpression(MLNAdditions) mgl_expressionForInterpolatingExpression:withCurveType:parameters:stops:]` takes the interpolation type as a parameter. If you previously used the default interpolation base, use the curve type `MLNExpressionInterpolationMode.linear`. See the [`mgl_interpolate:withCurveType:parameters:stops:`](predicates-and-expressions.html#code-mgl_interpolate-withcurvetype-parameters-stops-code) documentation for more details.
The stops dictionary below, shows colors that continuously shift from yellow to orange to red to blue to white based on the attribute value.
@@ -60,26 +60,26 @@ Style function syntax:
```swift
let url = URL(string: "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_week.geojson")!
let symbolSource = MGLSource(identifier: "source")
let symbolLayer = MGLSymbolStyleLayer(identifier: "place-city-sm", source: symbolSource)
let symbolSource = MLNSource(identifier: "source")
let symbolLayer = MLNSymbolStyleLayer(identifier: "place-city-sm", source: symbolSource)
let source = MGLShapeSource(identifier: "earthquakes", url: url, options: nil)
let source = MLNShapeSource(identifier: "earthquakes", url: url, options: nil)
mapView.style?.addSource(source)
let stops = [
0: MGLStyleValue<UIColor>(rawValue: .yellow),
2.5: MGLStyleValue(rawValue: .orange),
5: MGLStyleValue(rawValue: .red),
7.5: MGLStyleValue(rawValue: .blue),
10: MGLStyleValue(rawValue: .white),
0: MLNStyleValue<UIColor>(rawValue: .yellow),
2.5: MLNStyleValue(rawValue: .orange),
5: MLNStyleValue(rawValue: .red),
7.5: MLNStyleValue(rawValue: .blue),
10: MLNStyleValue(rawValue: .white),
]
let layer = MGLCircleStyleLayer(identifier: "circles", source: source)
layer.circleColor = MGLStyleValue(interpolationMode: .exponential,
let layer = MLNCircleStyleLayer(identifier: "circles", source: source)
layer.circleColor = MLNStyleValue(interpolationMode: .exponential,
sourceStops: stops,
attributeName: "mag",
options: [.defaultValue: MGLStyleValue<UIColor>(rawValue: .green)])
layer.circleRadius = MGLStyleValue(rawValue: 10)
options: [.defaultValue: MLNStyleValue<UIColor>(rawValue: .green)])
layer.circleRadius = MLNStyleValue(rawValue: 10)
mapView.style?.insertLayer(layer, below: symbolLayer)
```
@@ -89,9 +89,9 @@ Current syntax:
### Exponential
If you previously used an interpolation base greater than `0` (other than `1`), you can use `MGLExpressionInterpolationMode.exponential` as the curve type for `+[NSExpression(MGLAdditions) mgl_expressionForInterpolatingExpression:withCurveType:parameters:stops:]` or `'exponential'` as the curve type for [`mgl_interpolate:withCurveType:parameters:stops:`](predicates-and-expressions.html#code-mgl_interpolate-withcurvetype-parameters-stops-code). The `parameters` argument takes that interpolation base. This interpolates between values exponentially, creating an accelerated ramp effect.
If you previously used an interpolation base greater than `0` (other than `1`), you can use `MLNExpressionInterpolationMode.exponential` as the curve type for `+[NSExpression(MLNAdditions) mgl_expressionForInterpolatingExpression:withCurveType:parameters:stops:]` or `'exponential'` as the curve type for [`mgl_interpolate:withCurveType:parameters:stops:`](predicates-and-expressions.html#code-mgl_interpolate-withcurvetype-parameters-stops-code). The `parameters` argument takes that interpolation base. This interpolates between values exponentially, creating an accelerated ramp effect.
Here’s a visualization from Mapbox Studio (see [Mapbox Studio and iOS](https://www.mapbox.com/ios-sdk/maps/overview/mapbox-studio/)) comparing interpolation base values of `1.5` and `0.5` based on zoom. In order to convert camera style functions, use `$zoomLevel` or `MGL_FUNCTION('zoomLevel')` as the attribute key.
Here’s a visualization from Mapbox Studio (see [Mapbox Studio and iOS](https://www.mapbox.com/ios-sdk/maps/overview/mapbox-studio/)) comparing interpolation base values of `1.5` and `0.5` based on zoom. In order to convert camera style functions, use `$zoomLevel` or `MLN_FUNCTION('zoomLevel')` as the attribute key.
<img src="img/data-driven-styling/exponential-function.png" height=344/>
<img src="img/data-driven-styling/exponential-function-1.png" height=344/>
@@ -102,12 +102,12 @@ Style function syntax:
```swift
let stops = [
12: MGLStyleValue<NSNumber>(rawValue: 0.5),
14: MGLStyleValue(rawValue: 2),
18: MGLStyleValue(rawValue: 18),
12: MLNStyleValue<NSNumber>(rawValue: 0.5),
14: MLNStyleValue(rawValue: 2),
18: MLNStyleValue(rawValue: 18),
]
layer.circleRadius = MGLStyleValue(interpolationMode: .exponential,
layer.circleRadius = MLNStyleValue(interpolationMode: .exponential,
cameraStops: stops,
options: [.interpolationBase: 1.5])
```
@@ -118,7 +118,7 @@ Current syntax:
### Interval
Steps, or intervals, create a range using the keys from the stops dictionary. The range is from the given key to just less than the next key. The attribute values that fall into that range are then styled using the layout or paint value assigned to that key. You can use the `+[NSExpression(MGLAdditions) mgl_expressionForSteppingExpression:fromExpression:stops:]` method or the custom function [`mgl_step:from:stops:`](predicates-and-expressions.html#code-mgl_step-from-stops-code) for cases where you previously used interval interpolation mode. The first parameter takes the feature attribute name and the second parameter (`from:`) optionally takes the default or fallback value for that function. The final parameter takes a stops dictionary as an argument.
Steps, or intervals, create a range using the keys from the stops dictionary. The range is from the given key to just less than the next key. The attribute values that fall into that range are then styled using the layout or paint value assigned to that key. You can use the `+[NSExpression(MLNAdditions) mgl_expressionForSteppingExpression:fromExpression:stops:]` method or the custom function [`mgl_step:from:stops:`](predicates-and-expressions.html#code-mgl_step-from-stops-code) for cases where you previously used interval interpolation mode. The first parameter takes the feature attribute name and the second parameter (`from:`) optionally takes the default or fallback value for that function. The final parameter takes a stops dictionary as an argument.
When we use the stops dictionary given above with an `'mgl_step:from:stops:'`, we create ranges where earthquakes with a magnitude of 0 to just less than 2.5 would be yellow, 2.5 to just less than 5 would be orange, and so on.
@@ -126,17 +126,17 @@ Style function syntax:
```swift
let stops = [
0: MGLStyleValue<UIColor>(rawValue: .yellow),
2.5: MGLStyleValue(rawValue: .orange),
5: MGLStyleValue(rawValue: .red),
7.5: MGLStyleValue(rawValue: .blue),
10: MGLStyleValue(rawValue: .white),
0: MLNStyleValue<UIColor>(rawValue: .yellow),
2.5: MLNStyleValue(rawValue: .orange),
5: MLNStyleValue(rawValue: .red),
7.5: MLNStyleValue(rawValue: .blue),
10: MLNStyleValue(rawValue: .white),
]
layer.circleColor = MGLStyleValue(interpolationMode: .interval,
layer.circleColor = MLNStyleValue(interpolationMode: .interval,
sourceStops: stops,
attributeName: "mag",
options: [.defaultValue: MGLStyleValue<UIColor>(rawValue: .green)])
options: [.defaultValue: MLNStyleValue<UIColor>(rawValue: .green)])
````
Current syntax:
@@ -145,9 +145,9 @@ Current syntax:
### Categorical
Categorical interpolation mode took a stops dictionary. If the value for a specified feature attribute name matched one in that stops dictionary, the style value for that attribute value would be used. Categorical style functions can now be replaced with `MGL_MATCH`.
Categorical interpolation mode took a stops dictionary. If the value for a specified feature attribute name matched one in that stops dictionary, the style value for that attribute value would be used. Categorical style functions can now be replaced with `MLN_MATCH`.
`MGL_MATCH` takes an initial condition, which in this case is an attribute key. This is followed by possible matches for that key and the value to assign to the layer property if there is a match. The final argument can be a default style value that is to be used if none of the specified values match.
`MLN_MATCH` takes an initial condition, which in this case is an attribute key. This is followed by possible matches for that key and the value to assign to the layer property if there is a match. The final argument can be a default style value that is to be used if none of the specified values match.
There are three main types of events in the USGS dataset: earthquakes, explosions, and quarry blasts. In this case, the color of the circle layer will be determined by the type of event, with a default value of blue to catch any events that do not fall into any of those categories.
@@ -155,15 +155,15 @@ Style function syntax:
```swift
let categoricalStops = [
"earthquake": MGLStyleValue<UIColor>(rawValue: .orange),
"explosion": MGLStyleValue(rawValue: .red),
"quarry blast": MGLStyleValue(rawValue: .yellow),
"earthquake": MLNStyleValue<UIColor>(rawValue: .orange),
"explosion": MLNStyleValue(rawValue: .red),
"quarry blast": MLNStyleValue(rawValue: .yellow),
]
layer.circleColor = MGLStyleValue(interpolationMode: .categorical,
layer.circleColor = MLNStyleValue(interpolationMode: .categorical,
sourceStops: categoricalStops,
attributeName: "type",
options: [.defaultValue: MGLStyleValue<UIColor>(rawValue: .blue)])
options: [.defaultValue: MLNStyleValue<UIColor>(rawValue: .blue)])
```
Current syntax:
@@ -178,10 +178,10 @@ Identity interpolation mode used the attribute’s value as the style layer prop
Style function syntax:
```swift
layer.circleRadius = MGLStyleValue(interpolationMode: .identity,
layer.circleRadius = MLNStyleValue(interpolationMode: .identity,
sourceStops: nil,
attributeName: "mag",
options: [.defaultValue: MGLStyleValue<NSNumber>(rawValue: 0)])
options: [.defaultValue: MLNStyleValue<NSNumber>(rawValue: 0)])
```
Current syntax:
@@ -203,7 +203,7 @@ You can also cast attribute values in order to use them. One example is to cast
### Constant Values
For constant values that do not necessarily change based on camera or attribute values, use `[NSExpression expressionForConstantValue:]` (previously `[MGLStyleValue valueWithRawValue:]`).
For constant values that do not necessarily change based on camera or attribute values, use `[NSExpression expressionForConstantValue:]` (previously `[MLNStyleValue valueWithRawValue:]`).
## Resources

View File

@@ -11,13 +11,13 @@ syntax supported by this SDK. For a more general introduction to predicates and
expressions, consult the
_[Predicate Programming Guide](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Predicates/AdditionalChapters/Introduction.html)_
in Apple developer documentation. For additional detail on how this SDK has
extended the `NSExpression` class, consult the [`NSExpression(MGLAdditions)`](./Categories/NSExpression(MGLAdditions).html)
extended the `NSExpression` class, consult the [`NSExpression(MLNAdditions)`](./Categories/NSExpression(MLNAdditions).html)
section of this documentation.
## Using predicates to filter vector data
Most style layer classes display `MGLFeature` objects that you can show or hide
based on the feature’s attributes. Use the `MGLVectorStyleLayer.predicate`
Most style layer classes display `MLNFeature` objects that you can show or hide
based on the feature’s attributes. Use the `MLNVectorStyleLayer.predicate`
property to include only the features in the source layer that satisfy a
condition that you define.
@@ -55,15 +55,15 @@ The following aggregate operators are supported:
`NSInPredicateOperatorType` | `key IN { 'iOS', 'macOS', 'tvOS', 'watchOS' }`
`NSContainsPredicateOperatorType` | `{ 'iOS', 'macOS', 'tvOS', 'watchOS' } CONTAINS key`
You can use the `IN` and `CONTAINS` operators to test whether a value appears in a collection, whether a string is a substring of a larger string, or whether the evaluated feature (`SELF`) lies within a given `MGLShape` or `MGLFeature`. For example, to show one delicious local chain of sandwich shops, but not similarly named steakhouses and pizzerias:
You can use the `IN` and `CONTAINS` operators to test whether a value appears in a collection, whether a string is a substring of a larger string, or whether the evaluated feature (`SELF`) lies within a given `MLNShape` or `MLNFeature`. For example, to show one delicious local chain of sandwich shops, but not similarly named steakhouses and pizzerias:
```objc
MGLPolygon *cincinnati = [MGLPolygon polygonWithCoordinates:cincinnatiCoordinates count:sizeof(cincinnatiCoordinates) / sizeof(cincinnatiCoordinates[0])];
MLNPolygon *cincinnati = [MLNPolygon polygonWithCoordinates:cincinnatiCoordinates count:sizeof(cincinnatiCoordinates) / sizeof(cincinnatiCoordinates[0])];
deliLayer.predicate = [NSPredicate predicateWithFormat:@"class = 'food_and_drink' AND name CONTAINS 'Izzy' AND SELF IN %@", cincinnati];
```
```swift
let cincinnati = MGLPolygon(coordinates: &cincinnatiCoordinates, count: UInt(cincinnatiCoordinates.count))
let cincinnati = MLNPolygon(coordinates: &cincinnatiCoordinates, count: UInt(cincinnatiCoordinates.count))
deliLayer.predicate = NSPredicate(format: "class = 'food_and_drink' AND name CONTAINS 'Izzy' AND SELF IN %@", cincinnati)
```
@@ -135,8 +135,8 @@ of `-[NSNumber numberWithFloat:]` to avoid precision issues.
### Key paths
A key path expression refers to an attribute of the `MGLFeature` object being
evaluated for display. For example, if a polygon’s `MGLFeature.attributes`
A key path expression refers to an attribute of the `MLNFeature` object being
evaluated for display. For example, if a polygon’s `MLNFeature.attributes`
dictionary contains the `floorCount` key, then the key path `floorCount` refers
to the value of the `floorCount` attribute when evaluating that particular
polygon.
@@ -247,7 +247,7 @@ Conditionals are supported via the built-in
`+[NSExpression expressionForConditional:trueExpression:falseExpression:]`
method and `TERNARY()` operator. If you need to express multiple cases
(“else-if”), you can either nest a conditional within a conditional or use the
[`MGL_IF()`](#code-mgl_if-code) or [`MGL_MATCH()`](#code-mgl_match-code) function.
[`MLN_IF()`](#code-mgl_if-code) or [`MLN_MATCH()`](#code-mgl_match-code) function.
### Aggregates
@@ -285,15 +285,15 @@ The following variables are defined by this SDK for use with style layers:
<ul>
<li>
<code>Point</code> for point features, corresponding to the
<code>MGLPointAnnotation</code> class
<code>MLNPointAnnotation</code> class
</li>
<li>
<code>LineString</code> for polyline features, corresponding to
the <code>MGLPolyline</code> class
the <code>MLNPolyline</code> class
</li>
<li>
<code>Polygon</code> for polygon features, corresponding to the
<code>MGLPolygon</code> class
<code>MLNPolygon</code> class
</li>
</ul>
This variable corresponds to the
@@ -330,7 +330,7 @@ The following variables are defined by this SDK for use with style layers:
A number that indicates the relative distance along a line at a given
point along the line. This variable evaluates to 0 at the beginning of the
line and 1 at the end of the line. It can only be used with the
`MGLLineStyleLayer.lineGradient` property. It corresponds to the
`MLNLineStyleLayer.lineGradient` property. It corresponds to the
<code>NSExpression.lineProgressVariableExpression</code> property.
</td>
</tr>
@@ -343,11 +343,11 @@ of a [Mapbox-specific function](#mapbox-specific-functions) that takes an
`NSDictionary` as an argument:
```objc
[NSExpression expressionWithFormat:@"MGL_LET('floorCount', 2, $floorCount + 1)"];
[NSExpression expressionWithFormat:@"MLN_LET('floorCount', 2, $floorCount + 1)"];
```
```swift
NSExpression(format: "MGL_LET(floorCount, 2, $floorCount + 1)")
NSExpression(format: "MLN_LET(floorCount, 2, $floorCount + 1)")
```
## Mapbox-specific functions
@@ -546,7 +546,7 @@ operator in the Mapbox Style Specification.
<dt>Selector:</dt>
<dd><code>mgl_distanceFrom:</code></dd>
<dt>Format string syntax:</dt>
<dd><code>mgl_distanceFrom(%@)</code> with an <code>MGLShape</code></dd>
<dd><code>mgl_distanceFrom(%@)</code> with an <code>MLNShape</code></dd>
</dl>
Returns the straight-line distance from the evaluated object to the given shape.
@@ -579,28 +579,28 @@ operator in the Mapbox Style Specification.
<dd><code>mgl_attributed({x, y, z})</code></dd>
</dl>
Concatenates and returns the array of `MGLAttributedExpression` objects, for use
with the `MGLSymbolStyleLayer.text` property.
Concatenates and returns the array of `MLNAttributedExpression` objects, for use
with the `MLNSymbolStyleLayer.text` property.
`MGLAttributedExpression.attributes` valid attributes.
`MLNAttributedExpression.attributes` valid attributes.
Key | Value Type
--- | ---
`MGLFontNamesAttribute` | An `NSExpression` evaluating to an `NSString` array.
`MGLFontScaleAttribute` | An `NSExpression` evaluating to an `NSNumber` value.
`MGLFontColorAttribute` | An `NSExpression` evaluating to an `UIColor` (iOS) or `NSColor` (macOS).
`MLNFontNamesAttribute` | An `NSExpression` evaluating to an `NSString` array.
`MLNFontScaleAttribute` | An `NSExpression` evaluating to an `NSNumber` value.
`MLNFontColorAttribute` | An `NSExpression` evaluating to an `UIColor` (iOS) or `NSColor` (macOS).
This function corresponds to the
[`format`](https://maplibre.org/maplibre-gl-js-docs/style-spec/#expressions-types-format)
operator in the Mapbox Style Specification.
### `MGL_LET`
### `MLN_LET`
<dl>
<dt>Selector:</dt>
<dd><code>MGL_LET:</code></dd>
<dd><code>MLN_LET:</code></dd>
<dt>Format string syntax:</dt>
<dd><code>MGL_LET('age', uppercase('old'), 'name', uppercase('MacDonald'), mgl_join({$age, $name}))</code></dd>
<dd><code>MLN_LET('age', uppercase('old'), 'name', uppercase('MacDonald'), mgl_join({$age, $name}))</code></dd>
<dt>Arguments:</dt>
<dd>
Any number of variable names interspersed with their assigned
@@ -615,13 +615,13 @@ Compared to the
function, this function takes the variable names and values inline before the
expression that contains references to those variables.
### `MGL_MATCH`
### `MLN_MATCH`
<dl>
<dt>Selector:</dt>
<dd><code>MGL_MATCH:</code></dd>
<dd><code>MLN_MATCH:</code></dd>
<dt>Format string syntax:</dt>
<dd><code>MGL_MATCH(x, 0, 'zero match', 1, 'one match', 2, 'two match', 'default')</code></dd>
<dd><code>MLN_MATCH(x, 0, 'zero match', 1, 'one match', 2, 'two match', 'default')</code></dd>
<dt>Arguments:</dt>
<dd>
An input expression, then any number of argument pairs, followed by a default
@@ -638,18 +638,18 @@ Returns the result of matching the input expression against the given constant
values.
This function corresponds to the
`+[NSExpression(MGLAdditions) mgl_expressionForMatchingExpression:inDictionary:defaultExpression:]`
`+[NSExpression(MLNAdditions) mgl_expressionForMatchingExpression:inDictionary:defaultExpression:]`
method and the
[`match`](https://maplibre.org/maplibre-gl-js-docs/style-spec/#expressions-match)
operator in the Mapbox Style Specification.
### `MGL_IF`
### `MLN_IF`
<dl>
<dt>Selector:</dt>
<dd><code>MGL_IF:</code></dd>
<dd><code>MLN_IF:</code></dd>
<dt>Format string syntax:</dt>
<dd><code>MGL_IF(1 = 2, YES, 2 = 2, YES, NO)</code></dd>
<dd><code>MLN_IF(1 = 2, YES, 2 = 2, YES, NO)</code></dd>
<dt>Arguments:</dt>
<dd>
Alternating <code>NSPredicate</code> conditionals and resulting expressions,
@@ -665,18 +665,18 @@ and is supported on iOS 8._x_ and macOS 10.10._x_; however, each conditional
passed into this function must be wrapped in a constant expression.
This function corresponds to the
`+[NSExpression(MGLAdditions) mgl_expressionForConditional:trueExpression:falseExpresssion:]`
`+[NSExpression(MLNAdditions) mgl_expressionForConditional:trueExpression:falseExpresssion:]`
method and the
[`case`](https://maplibre.org/maplibre-gl-js-docs/style-spec/#expressions-case)
operator in the Mapbox Style Specification.
### `MGL_FUNCTION`
### `MLN_FUNCTION`
<dl>
<dt>Selector:</dt>
<dd><code>MGL_FUNCTION:</code></dd>
<dd><code>MLN_FUNCTION:</code></dd>
<dt>Format string syntax:</dt>
<dd><code>MGL_FUNCTION('typeof', mystery)</code></dd>
<dd><code>MLN_FUNCTION('typeof', mystery)</code></dd>
<dt>Arguments:</dt>
<dd>
Any arguments required by the expression operator.
@@ -699,7 +699,7 @@ or may result in undefined behavior.
The Mapbox Style Specification defines some operators for which no custom
function is available. To use these operators in an `NSExpression`, call the
[`MGL_FUNCTION()`](#code-mgl_function-code) function with the same arguments
[`MLN_FUNCTION()`](#code-mgl_function-code) function with the same arguments
that the operator expects.
### `boolValue`
@@ -737,7 +737,7 @@ otherwise <code>TRUE</code>.
<dd>
An <code>NSExpression</code> that evaluates to an <code>NSString</code>
representing the key to look up in the dictionary or the feature attribute to
look up in the evaluated object (see <code>MGLFeature.attributes</code>).
look up in the evaluated object (see <code>MLNFeature.attributes</code>).
</dd>
</dl>
@@ -781,7 +781,7 @@ defined in the context dictionary.
This function corresponds to the
[`let`](https://maplibre.org/maplibre-gl-js-docs/style-spec/#expressions-let)
operator in the Mapbox Style Specification. See also the
[`MGL_LET`](#code-mgl_let-code) function, which is used on its own without the
[`MLN_LET`](#code-mgl_let-code) function, which is used on its own without the
`FUNCTION()` operator.
### `mgl_interpolateWithCurveType:parameters:stops:`
@@ -837,7 +837,7 @@ use a stop dictionary with the zoom levels 0, 10, and 20 as keys and the colors
yellow, orange, and red as the values.
This function corresponds to the
`+[NSExpression(MGLAdditions) mgl_expressionForInterpolatingExpression:withCurveType:parameters:stops:]`
`+[NSExpression(MLNAdditions) mgl_expressionForInterpolatingExpression:withCurveType:parameters:stops:]`
method and the
[`interpolate`](https://maplibre.org/maplibre-gl-js-docs/style-spec/#expressions-interpolate)
operator in the Mapbox Style Specification. See also the
@@ -921,7 +921,7 @@ use a stop dictionary with the zoom levels 0, 10, and 20 as keys and the colors
yellow, orange, and red as the values.
This function corresponds to the
`+[NSExpression(MGLAdditions) mgl_expressionForSteppingExpression:fromExpression:stops:]`
`+[NSExpression(MLNAdditions) mgl_expressionForSteppingExpression:fromExpression:stops:]`
method and the
[`step`](https://maplibre.org/maplibre-gl-js-docs/style-spec/#expressions-step)
operator in the Mapbox Style Specification.
@@ -942,7 +942,7 @@ operator in the Mapbox Style Specification.
The target string with each of the argument strings appended in order.
This function corresponds to the
`-[NSExpression(MGLAdditions) mgl_expressionByAppendingExpression:]`
`-[NSExpression(MLNAdditions) mgl_expressionByAppendingExpression:]`
method and is similar to the
[`concat`](https://maplibre.org/maplibre-gl-js-docs/style-spec/#expressions-concat)
operator in the Mapbox Style Specification. See also the

View File

@@ -10,8 +10,8 @@
-->
# Tile URL Templates
`MGLTileSource` objects, specifically `MGLRasterTileSource` and
`MGLVectorTileSource` objects, can be created using an initializer that accepts
`MLNTileSource` objects, specifically `MLNRasterTileSource` and
`MLNVectorTileSource` objects, can be created using an initializer that accepts
an array of tile URL templates. Tile URL templates are strings that specify the
URLs of the vector tiles or raster tile images to load. A template resembles an
absolute URL, but with any number of placeholder strings that the source
@@ -54,18 +54,18 @@ all of which are optional:
is 2<sup><var>z</var></sup>−1, the tile’s bottom edge corresponds to
−arctan(sinh(π)), or approximately 85.0511 degrees south. The y axis is
inverted if the <code>options</code> parameter contains
<code>MGLTileSourceOptionTileCoordinateSystem</code> with a value of
<code>MGLTileCoordinateSystemTMS</code>.</td>
<code>MLNTileSourceOptionTileCoordinateSystem</code> with a value of
<code>MLNTileCoordinateSystemTMS</code>.</td>
</tr>
<tr>
<td><code>{z}</code></td>
<td>The tile’s zoom level. At zoom level 0, each tile covers the entire
world map; at zoom level 1, it covers ¼ of the world; at zoom level 2,
<sup>1</sup>⁄<sub>16</sub> of the world, and so on. For tiles loaded by
a <code>MGLRasterTileSource</code> object, whether the tile zoom level
a <code>MLNRasterTileSource</code> object, whether the tile zoom level
matches the map’s current zoom level depends on the value of the
source’s tile size as specified in the
<code>MGLTileSourceOptionTileSize</code> key of the <code>options</code>
<code>MLNTileSourceOptionTileSize</code> key of the <code>options</code>
parameter.</td>
</tr>
<tr>

View File

@@ -12,52 +12,52 @@ will be hosted on Mapbox servers. When a user loads your style, the SDK
automatically loads the GeoJSON data for display.
Alternatively, if you need to host the GeoJSON file elsewhere or bundle it with
your application, you can use a GeoJSON file as the basis of an `MGLShapeSource`
your application, you can use a GeoJSON file as the basis of an `MLNShapeSource`
object. Pass the file’s URL into the
`-[MGLShapeSource initWithIdentifier:URL:options:]` initializer and add the
shape source to the map using the `-[MGLStyle addSource:]` method. The URL may
`-[MLNShapeSource initWithIdentifier:URL:options:]` initializer and add the
shape source to the map using the `-[MLNStyle addSource:]` method. The URL may
be a local file URL, an HTTP URL, or an HTTPS URL.
Once you’ve added the GeoJSON file to the map via an `MGLShapeSource` object,
Once you’ve added the GeoJSON file to the map via an `MLNShapeSource` object,
you can configure the appearance of its data and control what data is visible
using `MGLStyleLayer` objects. You can also
using `MLNStyleLayer` objects. You can also
[access the data programmatically](#extracting-geojson-data-from-the-map).
## Converting GeoJSON data into shape objects
If you have GeoJSON data in the form of source code (also known as “GeoJSON
text”), you can convert it into an `MGLShape`, `MGLFeature`, or
`MGLShapeCollectionFeature` object that the `MGLShapeSource` class understands
text”), you can convert it into an `MLNShape`, `MLNFeature`, or
`MLNShapeCollectionFeature` object that the `MLNShapeSource` class understands
natively. First, create an `NSData` object out of the source code string or file
contents, then pass that data object into the
`+[MGLShape shapeWithData:encoding:error:]` method. Finally, you can pass the
`+[MLNShape shapeWithData:encoding:error:]` method. Finally, you can pass the
resulting shape or feature object into the
`-[MGLShapeSource initWithIdentifier:shape:options:]` initializer and add it to
`-[MLNShapeSource initWithIdentifier:shape:options:]` initializer and add it to
the map, or you can use the object and its properties to power non-map-related
functionality in your application.
To include multiple shapes in the source, create and pass an `MGLShapeCollection` or
`MGLShapeCollectionFeature` object to
`-[MGLShapeSource initWithIdentifier:shape:options:]`. Alternatively, use the
`-[MGLShapeSource initWithIdentifier:features:options:]` or
`-[MGLShapeSource initWithIdentifier:shapes:options:]` method to create a shape source
with an array. `-[MGLShapeSource initWithIdentifier:features:options:]` accepts only `MGLFeature`
instances, such as `MGLPointFeature` objects, whose attributes you can use when
applying a predicate to `MGLVectorStyleLayer` or configuring a style layer’s
To include multiple shapes in the source, create and pass an `MLNShapeCollection` or
`MLNShapeCollectionFeature` object to
`-[MLNShapeSource initWithIdentifier:shape:options:]`. Alternatively, use the
`-[MLNShapeSource initWithIdentifier:features:options:]` or
`-[MLNShapeSource initWithIdentifier:shapes:options:]` method to create a shape source
with an array. `-[MLNShapeSource initWithIdentifier:features:options:]` accepts only `MLNFeature`
instances, such as `MLNPointFeature` objects, whose attributes you can use when
applying a predicate to `MLNVectorStyleLayer` or configuring a style layer’s
appearance.
## Extracting GeoJSON data from the map
Any `MGLShape`, `MGLFeature`, or `MGLShapeCollectionFeature` object has an
`-[MGLShape geoJSONDataUsingEncoding:]` method that you can use to create a
Any `MLNShape`, `MLNFeature`, or `MLNShapeCollectionFeature` object has an
`-[MLNShape geoJSONDataUsingEncoding:]` method that you can use to create a
GeoJSON source code representation of the object. You can extract a feature
object from the map using a method such as
`-[MGLMapView visibleFeaturesAtPoint:]`.
`-[MLNMapView visibleFeaturesAtPoint:]`.
## About GeoJSON deserialization
The process of converting GeoJSON text into `MGLShape`, `MGLFeature`, or
`MGLShapeCollectionFeature` objects is known as “GeoJSON deserialization”.
The process of converting GeoJSON text into `MLNShape`, `MLNFeature`, or
`MLNShapeCollectionFeature` objects is known as “GeoJSON deserialization”.
GeoJSON geometries, features, and feature collections are known in this SDK as
shapes, features, and shape collection features, respectively.
@@ -67,27 +67,27 @@ the Core Location framework:
GeoJSON object type | SDK type
--------------------|---------
`Position` (longitude, latitude) | `CLLocationCoordinate2D` (latitude, longitude)
`Point` | `MGLPointAnnotation`
`MultiPoint` | `MGLPointCollection`
`LineString` | `MGLPolyline`
`MultiLineString` | `MGLMultiPolyline`
`Polygon` | `MGLPolygon`
Linear ring | `MGLPolygon.coordinates`, `MGLPolygon.interiorPolygons`
`MultiPolygon` | `MGLMultiPolygon`
`GeometryCollection` | `MGLShapeCollection`
`Feature` | `MGLFeature`
`FeatureCollection` | `MGLShapeCollectionFeature`
`Point` | `MLNPointAnnotation`
`MultiPoint` | `MLNPointCollection`
`LineString` | `MLNPolyline`
`MultiLineString` | `MLNMultiPolyline`
`Polygon` | `MLNPolygon`
Linear ring | `MLNPolygon.coordinates`, `MLNPolygon.interiorPolygons`
`MultiPolygon` | `MLNMultiPolygon`
`GeometryCollection` | `MLNShapeCollection`
`Feature` | `MLNFeature`
`FeatureCollection` | `MLNShapeCollectionFeature`
A `Feature` object in GeoJSON corresponds to an instance of an `MGLShape`
subclass conforming to the `MGLFeature` protocol. There is a distinct
`MGLFeature`-conforming class for each type of geometry that a GeoJSON feature
A `Feature` object in GeoJSON corresponds to an instance of an `MLNShape`
subclass conforming to the `MLNFeature` protocol. There is a distinct
`MLNFeature`-conforming class for each type of geometry that a GeoJSON feature
can contain. This allows features to be used as raw shapes where convenient. For
example, some features can be added to a map view as annotations. Note that
identifiers and attributes will not be available for feature querying when a
feature is used as an annotation.
In contrast to the GeoJSON standard, it is possible for `MGLShape` subclasses
other than `MGLPointAnnotation` to straddle the antimeridian.
In contrast to the GeoJSON standard, it is possible for `MLNShape` subclasses
other than `MLNPointAnnotation` to straddle the antimeridian.
The following GeoJSON data types correspond straightforwardly to Foundation data
types when they occur as feature identifiers or property values:

View File

@@ -384,14 +384,14 @@ pre code {
content: "(Protocol)";
}
.nav-group-task[data-name="MGLForegroundStyleLayer"],
.nav-group-task[data-name="MGLMultiPoint"],
.nav-group-task[data-name="MGLShape"],
.nav-group-task[data-name="MGLSource"],
.nav-group-task[data-name="MGLStyleFunction"],
.nav-group-task[data-name="MGLStyleLayer"],
.nav-group-task[data-name="MGLTileSource"],
.nav-group-task[data-name="MGLVectorStyleLayer"] {
.nav-group-task[data-name="MLNForegroundStyleLayer"],
.nav-group-task[data-name="MLNMultiPoint"],
.nav-group-task[data-name="MLNShape"],
.nav-group-task[data-name="MLNSource"],
.nav-group-task[data-name="MLNStyleFunction"],
.nav-group-task[data-name="MLNStyleLayer"],
.nav-group-task[data-name="MLNTileSource"],
.nav-group-task[data-name="MLNVectorStyleLayer"] {
.nav-group-task-link::after {
@extend %nav-group-task-gloss;
content: "(Abstract Class)";

View File

@@ -5,8 +5,8 @@
#include <CoreGraphics/CGImage.h>
// Creates a CGImage from a PremultipliedImage, taking over the memory ownership.
CGImageRef CGImageCreateWithMGLPremultipliedImage(mbgl::PremultipliedImage&&);
CGImageRef CGImageCreateWithMLNPremultipliedImage(mbgl::PremultipliedImage&&);
// Creates a PremultipliedImage by copying the pixels of the CGImage.
// Does not alter the retain count of the supplied CGImage.
mbgl::PremultipliedImage MGLPremultipliedImageFromCGImage(CGImageRef);
mbgl::PremultipliedImage MLNPremultipliedImageFromCGImage(CGImageRef);

View File

@@ -7,7 +7,7 @@ const path = require('path');
const execFileSync = require('child_process').execFileSync;
const _ = require('lodash');
const keyword = /\bMGL_EXPORT\b/;
const keyword = /\bMLN_EXPORT\b/;
let scanned = [];

View File

@@ -10,7 +10,7 @@ const assert = require('assert');
require('../../../../../scripts/style-code');
const cocoaConventions = require('./style-spec-cocoa-conventions-v8.json');
const prefix = 'MGL';
const prefix = 'MLN';
const suffix = 'StyleLayer';
let spec = _.merge(require('../../../scripts/style-spec'), require('./style-spec-overrides-v8.json'));
@@ -140,7 +140,7 @@ global.arrayType = function (property) {
global.testImplementation = function (property, layerType, isFunction) {
let helperMsg = testHelperMessage(property, layerType, isFunction);
return `layer.${objCName(property)} = [MGLRuntimeStylingHelper ${helperMsg}];`;
return `layer.${objCName(property)} = [MLNRuntimeStylingHelper ${helperMsg}];`;
};
global.objCTestValue = function (property, layerType, arraysAsStructs, indent) {
@@ -159,13 +159,13 @@ global.objCTestValue = function (property, layerType, arraysAsStructs, indent) {
case 'resolvedImage':
return layerType === 'string' ?
`@"${_.startCase(propertyName)}"` :
`@"MGL_FUNCTION('image', '${_.startCase(propertyName)}')"`;
`@"MLN_FUNCTION('image', '${_.startCase(propertyName)}')"`;
case 'string':
return `@"'${_.startCase(propertyName)}'"`;
case 'enum':
return `@"'${_.last(_.keys(property.values))}'"`;
case 'color':
return '@"%@", [MGLColor redColor]';
return '@"%@", [MLNColor redColor]';
case 'array':
switch (arrayType(property)) {
case 'dasharray':
@@ -184,7 +184,7 @@ global.objCTestValue = function (property, layerType, arraysAsStructs, indent) {
case 'translate': {
if (arraysAsStructs) {
let iosValue = '[NSValue valueWithCGVector:CGVectorMake(1, 1)]'.indent(indent * 4);
let macosValue = '[NSValue valueWithMGLVector:CGVectorMake(1, -1)]'.indent(indent * 4);
let macosValue = '[NSValue valueWithMLNVector:CGVectorMake(1, -1)]'.indent(indent * 4);
return `@"%@",\n#if TARGET_OS_IPHONE\n${iosValue}\n#else\n${macosValue}\n#endif\n${''.indent((indent - 1) * 4)}`;
}
return '@"{1, 1}"';
@@ -277,12 +277,12 @@ global.mbglExpressionTestValue = function (property, layerType) {
global.testGetterImplementation = function (property, layerType, isFunction) {
let helperMsg = testHelperMessage(property, layerType, isFunction);
let value = `[MGLRuntimeStylingHelper ${helperMsg}]`;
let value = `[MLNRuntimeStylingHelper ${helperMsg}]`;
if (property.type === 'enum') {
if (isFunction) {
return `XCTAssertEqualObjects(gLayer.${objCName(property)}, ${value});`;
}
return `XCTAssert([gLayer.${objCName(property)} isKindOfClass:[MGLConstantStyleValue class]]);
return `XCTAssert([gLayer.${objCName(property)} isKindOfClass:[MLNConstantStyleValue class]]);
XCTAssertEqualObjects(gLayer.${objCName(property)}, ${value});`;
}
return `XCTAssertEqualObjects(gLayer.${objCName(property)}, ${value});`;
@@ -358,7 +358,7 @@ global.propertyDoc = function (propertyName, property, layerType, kind) {
let layoutProperties = spec[`layout_${layerType}`] || [];
let paintProperties = spec[`paint_${layerType}`] || [];
if (symbol in layoutProperties || symbol in paintProperties) {
return '`MGL' + camelize(layerType) + 'StyleLayer.' + camelizeWithLeadingLowercase(symbol) + '`';
return '`MLN' + camelize(layerType) + 'StyleLayer.' + camelizeWithLeadingLowercase(symbol) + '`';
}
}
if ('values' in property && Object.keys(property.values).indexOf(symbol) !== -1) {
@@ -484,7 +484,7 @@ global.describeType = function (property) {
case 'resolvedImage':
return 'string';
case 'enum':
return '`MGL' + camelize(property.name) + '`';
return '`MLN' + camelize(property.name) + '`';
case 'color':
return '`UIColor`';
case 'array':
@@ -495,11 +495,11 @@ global.describeType = function (property) {
case 'translate':
return '`CGVector`';
case 'position':
return '`MGLSphericalPosition`';
return '`MLNSphericalPosition`';
case 'anchor':
return '`MGLTextAnchor` array';
return '`MLNTextAnchor` array';
case 'mode':
return '`MGLTextWritingMode` array';
return '`MLNTextWritingMode` array';
default:
return 'array';
}
@@ -580,7 +580,7 @@ global.describeValue = function (value, property, layerType) {
case 'translate':
return 'an `NSValue` object containing a `CGVector` struct set to' + ` ${formatNumber(value[0])}${units} rightward and ${formatNumber(value[1])}${units} downward`;
case 'position':
return 'an `MGLSphericalPosition` struct set to' + ` ${formatNumber(value[0])} radial, ${formatNumber(value[1])} azimuthal and ${formatNumber(value[2])} polar`;
return 'an `MLNSphericalPosition` struct set to' + ` ${formatNumber(value[0])} radial, ${formatNumber(value[1])} azimuthal and ${formatNumber(value[2])} polar`;
default:
return 'the array `' + value.join('`, `') + '`';
}
@@ -622,7 +622,7 @@ global.propertyType = function (property) {
case 'enum':
return 'NSValue *';
case 'color':
return 'MGLColor *';
return 'MLNColor *';
case 'array':
switch (arrayType(property)) {
case 'dasharray':
@@ -668,7 +668,7 @@ global.valueTransformerArguments = function (property) {
case 'string':
return ['std::string', objCType];
case 'enum':
return [mbglType(property), 'NSValue *', mbglType(property), `MGL${camelize(property.name)}`];
return [mbglType(property), 'NSValue *', mbglType(property), `MLN${camelize(property.name)}`];
case 'color':
return ['mbgl::Color', objCType];
case 'array':
@@ -685,9 +685,9 @@ global.valueTransformerArguments = function (property) {
case 'translate':
return ['std::array<float, 2>', objCType];
case 'anchor':
return ['std::vector<mbgl::style::SymbolAnchorType>', objCType, 'mbgl::style::SymbolAnchorType', 'MGLTextAnchor'];
return ['std::vector<mbgl::style::SymbolAnchorType>', objCType, 'mbgl::style::SymbolAnchorType', 'MLNTextAnchor'];
case 'mode':
return ['std::vector<mbgl::style::TextWritingModeType>', objCType, 'mbgl::style::TextWritingModeType', 'MGLTextWritingMode'];
return ['std::vector<mbgl::style::TextWritingModeType>', objCType, 'mbgl::style::TextWritingModeType', 'MLNTextWritingMode'];
default:
throw new Error(`unknown array type for ${property.name}`);
}
@@ -774,20 +774,20 @@ const lightProperties = Object.keys(spec['light']).reduce((memo, name) => {
const lightDoc = spec['light-cocoa-doc'];
const lightType = 'light';
const layerH = ejs.compile(fs.readFileSync('platform/darwin/src/MGLStyleLayer.h.ejs', 'utf8'), { strict: true });
const layerPrivateH = ejs.compile(fs.readFileSync('platform/darwin/src/MGLStyleLayer_Private.h.ejs', 'utf8'), { strict: true });
const layerM = ejs.compile(fs.readFileSync('platform/darwin/src/MGLStyleLayer.mm.ejs', 'utf8'), { strict: true});
const testLayers = ejs.compile(fs.readFileSync('platform/darwin/test/MGLStyleLayerTests.mm.ejs', 'utf8'), { strict: true});
const layerH = ejs.compile(fs.readFileSync('platform/darwin/src/MLNStyleLayer.h.ejs', 'utf8'), { strict: true });
const layerPrivateH = ejs.compile(fs.readFileSync('platform/darwin/src/MLNStyleLayer_Private.h.ejs', 'utf8'), { strict: true });
const layerM = ejs.compile(fs.readFileSync('platform/darwin/src/MLNStyleLayer.mm.ejs', 'utf8'), { strict: true});
const testLayers = ejs.compile(fs.readFileSync('platform/darwin/test/MLNStyleLayerTests.mm.ejs', 'utf8'), { strict: true});
const forStyleAuthorsMD = ejs.compile(fs.readFileSync('platform/darwin/docs/guides/For Style Authors.md.ejs', 'utf8'), { strict: true });
const ddsGuideMD = ejs.compile(fs.readFileSync('platform/darwin/docs/guides/Migrating to Expressions.md.ejs', 'utf8'), { strict: true });
const templatesMD = ejs.compile(fs.readFileSync('platform/darwin/docs/guides/Tile URL Templates.md.ejs', 'utf8'), { strict: true });
const lightH = ejs.compile(fs.readFileSync('platform/darwin/src/MGLLight.h.ejs', 'utf8'), {strict: true});
const lightM = ejs.compile(fs.readFileSync('platform/darwin/src/MGLLight.mm.ejs', 'utf8'), {strict: true});
const testLight = ejs.compile(fs.readFileSync('platform/darwin/test/MGLLightTest.mm.ejs', 'utf8'), { strict: true});
writeIfModified(`platform/darwin/src/MGLLight.h`, duplicatePlatformDecls(lightH({ properties: lightProperties, doc: lightDoc, type: lightType })));
writeIfModified(`platform/darwin/src/MGLLight.mm`, lightM({ properties: lightProperties, doc: lightDoc, type: lightType }));
writeIfModified(`platform/darwin/test/MGLLightTest.mm`, testLight({ properties: lightProperties, doc: lightDoc, type: lightType }));
const lightH = ejs.compile(fs.readFileSync('platform/darwin/src/MLNLight.h.ejs', 'utf8'), {strict: true});
const lightM = ejs.compile(fs.readFileSync('platform/darwin/src/MLNLight.mm.ejs', 'utf8'), {strict: true});
const testLight = ejs.compile(fs.readFileSync('platform/darwin/test/MLNLightTest.mm.ejs', 'utf8'), { strict: true});
writeIfModified(`platform/darwin/src/MLNLight.h`, duplicatePlatformDecls(lightH({ properties: lightProperties, doc: lightDoc, type: lightType })));
writeIfModified(`platform/darwin/src/MLNLight.mm`, lightM({ properties: lightProperties, doc: lightDoc, type: lightType }));
writeIfModified(`platform/darwin/test/MLNLightTest.mm`, testLight({ properties: lightProperties, doc: lightDoc, type: lightType }));
const layers = _(spec.layer.type.values).map((value, layerType) => {
@@ -815,16 +815,16 @@ const layers = _(spec.layer.type.values).map((value, layerType) => {
}).sortBy(['type']).value();
function duplicatePlatformDecls(src) {
// Look for a documentation comment that contains “MGLColor” or “UIColor”
// Look for a documentation comment that contains “MLNColor” or “UIColor”
// and the subsequent function, method, or property declaration. Try not to
// match greedily.
return src.replace(/(\/\*\*(?:\*[^\/]|[^*])*?\b(?:MGL|NS|UI)Color\b[\s\S]*?\*\/)(\s*.+?;)/g,
return src.replace(/(\/\*\*(?:\*[^\/]|[^*])*?\b(?:MLN|NS|UI)Color\b[\s\S]*?\*\/)(\s*.+?;)/g,
(match, comment, decl) => {
let macosComment = comment.replace(/\b(?:MGL|UI)Color\b/g, 'NSColor')
let macosComment = comment.replace(/\b(?:MLN|UI)Color\b/g, 'NSColor')
// Use the correct indefinite article.
.replace(/\ba(\s+`?NSColor)\b/gi, 'an$1');
let iosDecl = decl.replace(/\bMGLColor\b/g, 'UIColor');
let macosDecl = decl.replace(/\b(?:MGL|UI)Color\b/g, 'NSColor');
let iosDecl = decl.replace(/\bMLNColor\b/g, 'UIColor');
let macosDecl = decl.replace(/\b(?:MLN|UI)Color\b/g, 'NSColor');
return `\
#if TARGET_OS_IPHONE
${comment}${iosDecl}
@@ -868,7 +868,7 @@ for (var layer of layers) {
}
// Extract examples for guides from unit tests.
let examplesSrc = fs.readFileSync('platform/darwin/test/MGLDocumentationGuideTests.swift', 'utf8');
let examplesSrc = fs.readFileSync('platform/darwin/test/MLNDocumentationGuideTests.swift', 'utf8');
const exampleRegex = /func test([\w$]+)\s*\(\)\s*\{[^]*?\n([ \t]+)\/\/#-example-code\n([^]+?)\n\2\/\/#-end-example-code\n/gm;
let examples = {};
@@ -889,7 +889,7 @@ global.guideExample = function (guide, exampleId, os) {
let testMethodName = `${guide}$${exampleId}`;
let example = examples[testMethodName];
if (!example) {
console.error(`MGLDocumentationExampleTests.test${testMethodName}() not found.`);
console.error(`MLNDocumentationExampleTests.test${testMethodName}() not found.`);
process.exit(1);
}

View File

@@ -1,47 +1,47 @@
{
"light-cocoa-doc": "An `MGLLight` object represents the light source for extruded geometries in `MGLStyle`.\n\n### Example\n```swift\n```\n\n#### Related examples\nSee the <a href=\"https://docs.mapbox.com/ios/maps/examples/light-example/\">Adjust light of 3D buildings</a> to learn how to create and modify the light source for 3D geometries.",
"light-cocoa-doc": "An `MLNLight` object represents the light source for extruded geometries in `MLNStyle`.\n\n### Example\n```swift\n```\n\n#### Related examples\nSee the <a href=\"https://docs.mapbox.com/ios/maps/examples/light-example/\">Adjust light of 3D buildings</a> to learn how to create and modify the light source for 3D geometries.",
"light": {
"position": {
"doc": "Position of the `MGLLight` source relative to lit (extruded) geometries, in a `MGLSphericalPosition` struct [radial coordinate, azimuthal angle, polar angle] where radial indicates the distance from the center of the base of an object to its light, azimuthal indicates the position of the light relative to 0° (0° when `MGLLight.anchor` is set to `MGLLightAnchorViewport` corresponds to the top of the viewport, or 0° when `MGLLight.anchor` is set to `MGLLightAnchorMap` corresponds to due north, and degrees proceed clockwise), and polar indicates the height of the light (from 0°, directly above, to 180°, directly below).",
"examples": "See the <a href=\"https://docs.mapbox.com/ios/maps/examples/light-example/\">Adjust light of 3D buildings</a> example to learn how to create and modify the position of value of an `MGLLight` object for 3D geometries."
"doc": "Position of the `MLNLight` source relative to lit (extruded) geometries, in a `MLNSphericalPosition` struct [radial coordinate, azimuthal angle, polar angle] where radial indicates the distance from the center of the base of an object to its light, azimuthal indicates the position of the light relative to 0° (0° when `MLNLight.anchor` is set to `MLNLightAnchorViewport` corresponds to the top of the viewport, or 0° when `MLNLight.anchor` is set to `MLNLightAnchorMap` corresponds to due north, and degrees proceed clockwise), and polar indicates the height of the light (from 0°, directly above, to 180°, directly below).",
"examples": "See the <a href=\"https://docs.mapbox.com/ios/maps/examples/light-example/\">Adjust light of 3D buildings</a> example to learn how to create and modify the position of value of an `MLNLight` object for 3D geometries."
}
},
"layer": {
"type": {
"values": {
"fill": {
"doc": "An `MGLFillStyleLayer` is a style layer that renders one or more filled (and optionally stroked) polygons on the map.\n\nUse a fill style layer to configure the visual appearance of polygon or multipolygon features. These features can come from vector tiles loaded by an `MGLVectorTileSource` object, or they can be `MGLPolygon`, `MGLPolygonFeature`, `MGLMultiPolygon`, or `MGLMultiPolygonFeature` instances in an `MGLShapeSource` or `MGLComputedShapeSource` object.",
"examples": "See the <a href=\"https://docs.mapbox.com/ios/maps/examples/select-layer/\">Select a feature within a layer</a> example to learn how to use a `TERNARY` expression to modify the `fillOpacity` of an `MGLFillStyleLayer` object. See the <a href=\"https://docs.mapbox.com/ios/maps/examples/fill-pattern/\">Add a pattern to a polygon</a> example to learn how to use an image to add pattern to the features styled by a `MGLFillStyleLayer`."
"doc": "An `MLNFillStyleLayer` is a style layer that renders one or more filled (and optionally stroked) polygons on the map.\n\nUse a fill style layer to configure the visual appearance of polygon or multipolygon features. These features can come from vector tiles loaded by an `MLNVectorTileSource` object, or they can be `MLNPolygon`, `MLNPolygonFeature`, `MLNMultiPolygon`, or `MLNMultiPolygonFeature` instances in an `MLNShapeSource` or `MLNComputedShapeSource` object.",
"examples": "See the <a href=\"https://docs.mapbox.com/ios/maps/examples/select-layer/\">Select a feature within a layer</a> example to learn how to use a `TERNARY` expression to modify the `fillOpacity` of an `MLNFillStyleLayer` object. See the <a href=\"https://docs.mapbox.com/ios/maps/examples/fill-pattern/\">Add a pattern to a polygon</a> example to learn how to use an image to add pattern to the features styled by a `MLNFillStyleLayer`."
},
"fill-extrusion": {
"doc": "An `MGLFillExtrusionStyleLayer` is a style layer that renders one or more 3D extruded polygons on the map.\n\nUse a fill-extrusion style layer to configure the visual appearance of polygon or multipolygon features. These features can come from vector tiles loaded by an `MGLVectorTileSource` object, or they can be `MGLPolygon`, `MGLPolygonFeature`, `MGLMultiPolygon`, or `MGLMultiPolygonFeature` instances in an `MGLShapeSource` or `MGLComputedShapeSource` object.",
"doc": "An `MLNFillExtrusionStyleLayer` is a style layer that renders one or more 3D extruded polygons on the map.\n\nUse a fill-extrusion style layer to configure the visual appearance of polygon or multipolygon features. These features can come from vector tiles loaded by an `MLNVectorTileSource` object, or they can be `MLNPolygon`, `MLNPolygonFeature`, `MLNMultiPolygon`, or `MLNMultiPolygonFeature` instances in an `MLNShapeSource` or `MLNComputedShapeSource` object.",
"examples": "See the <a href=\"https://docs.mapbox.com/ios/maps/examples/extrusions/\">Display 3D buildings</a> example to learn how to add and style 3D layers on a map."
},
"line": {
"doc": "An `MGLLineStyleLayer` is a style layer that renders one or more stroked polylines on the map.\n\nUse a line style layer to configure the visual appearance of polyline or multipolyline features. These features can come from vector tiles loaded by an `MGLVectorTileSource` object, or they can be `MGLPolyline`, `MGLPolylineFeature`, `MGLMultiPolyline`, or `MGLMultiPolylineFeature` instances in an `MGLShapeSource` or `MGLComputedShapeSource` object.",
"examples": "See the <a href=\"https://docs.mapbox.com/ios/maps/examples/shape-collection/\">Add multiple shapes from a single shape source</a> example to learn how to add a line to your map using this style layer. See the <a href=\"https://docs.mapbox.com/ios/maps/examples/runtime-add-line/\">Add a line style layer from GeoJSON</a> example to learn how to add and style line data to an `MGLMapView` object at runtime."
"doc": "An `MLNLineStyleLayer` is a style layer that renders one or more stroked polylines on the map.\n\nUse a line style layer to configure the visual appearance of polyline or multipolyline features. These features can come from vector tiles loaded by an `MLNVectorTileSource` object, or they can be `MLNPolyline`, `MLNPolylineFeature`, `MLNMultiPolyline`, or `MLNMultiPolylineFeature` instances in an `MLNShapeSource` or `MLNComputedShapeSource` object.",
"examples": "See the <a href=\"https://docs.mapbox.com/ios/maps/examples/shape-collection/\">Add multiple shapes from a single shape source</a> example to learn how to add a line to your map using this style layer. See the <a href=\"https://docs.mapbox.com/ios/maps/examples/runtime-add-line/\">Add a line style layer from GeoJSON</a> example to learn how to add and style line data to an `MLNMapView` object at runtime."
},
"symbol": {
"doc": "An `MGLSymbolStyleLayer` is a style layer that renders icon and text labels at points or along lines on the map.\n\nUse a symbol style layer to configure the visual appearance of feature labels. These features can come from vector tiles loaded by an `MGLVectorTileSource` object, or they can be `MGLShape` or `MGLFeature` instances in an `MGLShapeSource` or `MGLComputedShapeSource` object.",
"doc": "An `MLNSymbolStyleLayer` is a style layer that renders icon and text labels at points or along lines on the map.\n\nUse a symbol style layer to configure the visual appearance of feature labels. These features can come from vector tiles loaded by an `MLNVectorTileSource` object, or they can be `MLNShape` or `MLNFeature` instances in an `MLNShapeSource` or `MLNComputedShapeSource` object.",
"examples": "See the <a href=\"https://docs.mapbox.com/ios/maps/examples/runtime-multiple-annotations/\">Dynamically style interactive points</a> and <a href=\"https://docs.mapbox.com/ios/maps/examples/clustering-with-images/\">Use images to cluster point data</a> examples learn how to style data on your map using this layer."
},
"circle": {
"doc": "An `MGLCircleStyleLayer` is a style layer that renders one or more filled circles on the map.\n\nUse a circle style layer to configure the visual appearance of point or point collection features. These features can come from vector tiles loaded by an `MGLVectorTileSource` object, or they can be `MGLPointAnnotation`, `MGLPointFeature`, `MGLPointCollection`, or `MGLPointCollectionFeature` instances in an `MGLShapeSource` or `MGLComputedShapeSource` object.\n\nA circle style layer renders circles whose radii are measured in screen units. To display circles on the map whose radii correspond to real-world distances, use many-sided regular polygons and configure their appearance using an `MGLFillStyleLayer` object.",
"doc": "An `MLNCircleStyleLayer` is a style layer that renders one or more filled circles on the map.\n\nUse a circle style layer to configure the visual appearance of point or point collection features. These features can come from vector tiles loaded by an `MLNVectorTileSource` object, or they can be `MLNPointAnnotation`, `MLNPointFeature`, `MLNPointCollection`, or `MLNPointCollectionFeature` instances in an `MLNShapeSource` or `MLNComputedShapeSource` object.\n\nA circle style layer renders circles whose radii are measured in screen units. To display circles on the map whose radii correspond to real-world distances, use many-sided regular polygons and configure their appearance using an `MLNFillStyleLayer` object.",
"examples": "See the <a href=\"https://docs.mapbox.com/ios/maps/examples/dds-circle-layer/\">Data-driven circles</a>, <a href=\"https://docs.mapbox.com/ios/maps/examples/shape-collection/\">Add multiple shapes from a single shape source</a>, and <a href=\"https://docs.mapbox.com/ios/maps/examples/clustering/\">Cluster point data</a> examples to learn how to add circles to your map using this style layer."
},
"heatmap": {
"doc": "An `MGLHeatmapStyleLayer` is a style layer that renders a <a href=\"https://en.wikipedia.org/wiki/Heat_map\">heatmap</a>.\n\nA heatmap visualizes the spatial distribution of a large, dense set of point data, using color to avoid cluttering the map with individual points at low zoom levels. The points are weighted by an attribute you specify. Use a heatmap style layer in conjunction with point or point collection features. These features can come from vector tiles loaded by an `MGLVectorTileSource` object, or they can be `MGLPointAnnotation`, `MGLPointFeature`, `MGLPointCollection`, or `MGLPointCollectionFeature` instances in an `MGLShapeSource` or `MGLComputedShapeSource` object.\n\nConsider accompanying a heatmap style layer with an `MGLCircleStyleLayer` or `MGLSymbolStyleLayer` at high zoom levels. If you are unsure whether the point data in an `MGLShapeSource` is dense enough to warrant a heatmap, you can alternatively cluster the source using the `MGLShapeSourceOptionClustered` option and render the data using an `MGLCircleStyleLayer` or `MGLSymbolStyleLayer`.",
"doc": "An `MLNHeatmapStyleLayer` is a style layer that renders a <a href=\"https://en.wikipedia.org/wiki/Heat_map\">heatmap</a>.\n\nA heatmap visualizes the spatial distribution of a large, dense set of point data, using color to avoid cluttering the map with individual points at low zoom levels. The points are weighted by an attribute you specify. Use a heatmap style layer in conjunction with point or point collection features. These features can come from vector tiles loaded by an `MLNVectorTileSource` object, or they can be `MLNPointAnnotation`, `MLNPointFeature`, `MLNPointCollection`, or `MLNPointCollectionFeature` instances in an `MLNShapeSource` or `MLNComputedShapeSource` object.\n\nConsider accompanying a heatmap style layer with an `MLNCircleStyleLayer` or `MLNSymbolStyleLayer` at high zoom levels. If you are unsure whether the point data in an `MLNShapeSource` is dense enough to warrant a heatmap, you can alternatively cluster the source using the `MLNShapeSourceOptionClustered` option and render the data using an `MLNCircleStyleLayer` or `MLNSymbolStyleLayer`.",
"examples": "See the <a href=\"https://docs.mapbox.com/ios/maps/examples/heatmap-example/\">Create a heatmap layer</a> example to learn how to add this style layer to your map."
},
"raster": {
"doc": "An `MGLRasterStyleLayer` is a style layer that renders georeferenced raster imagery on the map, especially raster tiles.\n\nUse a raster style layer to configure the color parameters of raster tiles loaded by an `MGLRasterTileSource` object or raster images loaded by an `MGLImageSource` object. For example, you could use a raster style layer to render <a href=\"https://www.mapbox.com/satellite/\">Mapbox Satellite</a> imagery, a <a href=\"https://docs.mapbox.com/help/glossary/tileset/#raster-tilesets\">raster tile set</a> uploaded to Mapbox Studio, or a raster map authored in <a href=\"https://tilemill-project.github.io/tilemill/\">TileMill</a>, the classic Mapbox Editor, or Mapbox Studio Classic.\n\nRaster images may also be used as icons or patterns in a style layer. To register an image for use as an icon or pattern, use the `-[MGLStyle setImage:forName:]` method. To configure a point annotation’s image, use the `MGLAnnotationImage` class.",
"doc": "An `MLNRasterStyleLayer` is a style layer that renders georeferenced raster imagery on the map, especially raster tiles.\n\nUse a raster style layer to configure the color parameters of raster tiles loaded by an `MLNRasterTileSource` object or raster images loaded by an `MLNImageSource` object. For example, you could use a raster style layer to render <a href=\"https://www.mapbox.com/satellite/\">Mapbox Satellite</a> imagery, a <a href=\"https://docs.mapbox.com/help/glossary/tileset/#raster-tilesets\">raster tile set</a> uploaded to Mapbox Studio, or a raster map authored in <a href=\"https://tilemill-project.github.io/tilemill/\">TileMill</a>, the classic Mapbox Editor, or Mapbox Studio Classic.\n\nRaster images may also be used as icons or patterns in a style layer. To register an image for use as an icon or pattern, use the `-[MLNStyle setImage:forName:]` method. To configure a point annotation’s image, use the `MLNAnnotationImage` class.",
"examples": "See the <a href=\"https://docs.mapbox.com/ios/maps/examples/image-source/\">Add an image</a> and <a href=\"https://docs.mapbox.com/ios/maps/examples/source-custom-raster/\">Add raster imagery</a> examples to learn how to add imagery with this style layer."
},
"hillshade": {
"doc": "An `MGLHillshadeStyleLayer` is a style layer that renders raster <a href=\"https://en.wikipedia.org/wiki/Digital_elevation_model\">digital elevation model</a> (DEM) tiles on the map.\n\nUse a hillshade style layer to configure the color parameters of raster tiles loaded by an `MGLRasterDEMSource` object. For example, you could use a hillshade style layer to render <a href=\"https://docs.mapbox.com/help/troubleshooting/access-elevation-data/#mapbox-terrain-rgb\">Mapbox Terrain-RGB</a> data.\n\nTo display posterized hillshading based on vector shapes, as with the <a href=\"https://www.mapbox.com/vector-tiles/mapbox-terrain/\">Mapbox Terrain</a> source, use an `MGLVectorTileSource` object in conjunction with several `MGLFillStyleLayer` objects."
"doc": "An `MLNHillshadeStyleLayer` is a style layer that renders raster <a href=\"https://en.wikipedia.org/wiki/Digital_elevation_model\">digital elevation model</a> (DEM) tiles on the map.\n\nUse a hillshade style layer to configure the color parameters of raster tiles loaded by an `MLNRasterDEMSource` object. For example, you could use a hillshade style layer to render <a href=\"https://docs.mapbox.com/help/troubleshooting/access-elevation-data/#mapbox-terrain-rgb\">Mapbox Terrain-RGB</a> data.\n\nTo display posterized hillshading based on vector shapes, as with the <a href=\"https://www.mapbox.com/vector-tiles/mapbox-terrain/\">Mapbox Terrain</a> source, use an `MLNVectorTileSource` object in conjunction with several `MLNFillStyleLayer` objects."
},
"background": {
"doc": "An `MGLBackgroundStyleLayer` is a style layer that covers the entire map. Use a background style layer to configure a color or pattern to show below all other map content. If the style’s other layers use the Mapbox Streets source, the background style layer is responsible for drawing land, whereas the oceans and other bodies of water are drawn by `MGLFillStyleLayer` objects.\n\nA background style layer is typically the bottommost layer in a style, because it covers the entire map and can occlude any layers below it. You can therefore access it by getting the last item in the `MGLStyle.layers` array.\n\nIf the background style layer is transparent or omitted from the style, any portion of the map view that does not show another style layer is transparent."
"doc": "An `MLNBackgroundStyleLayer` is a style layer that covers the entire map. Use a background style layer to configure a color or pattern to show below all other map content. If the style’s other layers use the Mapbox Streets source, the background style layer is responsible for drawing land, whereas the oceans and other bodies of water are drawn by `MLNFillStyleLayer` objects.\n\nA background style layer is typically the bottommost layer in a style, because it covers the entire map and can occlude any layers below it. You can therefore access it by getting the last item in the `MLNStyle.layers` array.\n\nIf the background style layer is transparent or omitted from the style, any portion of the map view that does not show another style layer is transparent."
}
}
}
@@ -67,11 +67,11 @@
"doc": "Offset distance of icon from its anchor."
},
"icon-image": {
"doc": "Name of a style image to use for drawing an image background.\n\nUse the `+[MGLStyle setImage:forName:]` method to associate an image with a name that you can set this property to.\n\nWithin a constant string value, a feature attribute name enclosed in curly braces (e.g., `{token}`) is replaced with the value of the named attribute. Tokens inside non-constant expressions are ignored; instead, use `mgl_join:` and key path expressions.",
"doc": "Name of a style image to use for drawing an image background.\n\nUse the `+[MLNStyle setImage:forName:]` method to associate an image with a name that you can set this property to.\n\nWithin a constant string value, a feature attribute name enclosed in curly braces (e.g., `{token}`) is replaced with the value of the named attribute. Tokens inside non-constant expressions are ignored; instead, use `mgl_join:` and key path expressions.",
"examples": "See the <a href=\"https://docs.mapbox.com/ios/maps/examples/clustering-with-images/\">Use images to cluster point data</a> example to learn how to dynamically set your icons with an expression."
},
"symbol-avoid-edges": {
"doc": "Whether symbols in this layer avoid colliding with symbols in adjacent tiles.\n\nIf this property is set to `true`, symbols in this layer avoid crossing the edge of a tile. You should set this property to `true` if the backing vector tiles don’t have enough padding to prevent collisions, or if this layer’s `symbolPlacement` property is set to `MGLSymbolPlacementPoint` but this layer is above a symbol layer whose `symbolPlacement` property is set to `MGLSymbolPlacementLine`. You do not need to enable this property to prevent clipped labels at tile boundaries."
"doc": "Whether symbols in this layer avoid colliding with symbols in adjacent tiles.\n\nIf this property is set to `true`, symbols in this layer avoid crossing the edge of a tile. You should set this property to `true` if the backing vector tiles don’t have enough padding to prevent collisions, or if this layer’s `symbolPlacement` property is set to `MLNSymbolPlacementPoint` but this layer is above a symbol layer whose `symbolPlacement` property is set to `MLNSymbolPlacementLine`. You do not need to enable this property to prevent clipped labels at tile boundaries."
},
"text-field": {
"doc": "Value to use for a text label.\n\nWithin a constant string value, a feature attribute name enclosed in curly braces (e.g., `{token}`) is replaced with the value of the named attribute. Tokens inside non-constant expressions are ignored; instead, use `mgl_join:` and key path expressions.",
@@ -115,7 +115,7 @@
},
"paint_line": {
"line-gradient": {
"doc": "The color gradient with which the line will be drawn. This property only has an effect on lines defined by an `MGLShapeSource` whose `MGLShapeSourceOptionLineDistanceMetrics` option is set to `YES`."
"doc": "The color gradient with which the line will be drawn. This property only has an effect on lines defined by an `MLNShapeSource` whose `MLNShapeSourceOptionLineDistanceMetrics` option is set to `YES`."
},
"line-pattern": {
"doc": "Name of image in style images to use for drawing image lines. For seamless patterns, image width must be a factor of two (2, 4, 8, ..., 512)."

View File

@@ -7,11 +7,11 @@ const _ = require('lodash');
require('../../../../../scripts/style-code');
const examplesSrc = fs.readFileSync('platform/darwin/test/MGLDocumentationExampleTests.swift', 'utf8');
const examplesSrc = fs.readFileSync('platform/darwin/test/MLNDocumentationExampleTests.swift', 'utf8');
// Regex extracts the following block
// /** Front matter to describe the example. **/
// func testMGLClass$member() {
// func testMLNClass$member() {
// ...
// // #-example-code
// let sampleCode: String?
@@ -20,7 +20,7 @@ const examplesSrc = fs.readFileSync('platform/darwin/test/MGLDocumentationExampl
// }
//
// into the following regex groups:
// 1 (test method name): "MGLClass" or "MGLClass$member" or "MGLClass$initWithArg_anotherArg_"
// 1 (test method name): "MLNClass" or "MLNClass$member" or "MLNClass$initWithArg_anotherArg_"
// 2 (indentation): " "
// 3 (sample code): "let sampleCode: String?"
const exampleRegex = /func test([\w$]+)\s*\(\)\s*\{[^]*?\n([ \t]+)\/\/#-example-code\n([^]+?)\n\2\/\/#-end-example-code\n/gm;
@@ -106,7 +106,7 @@ function completeExamples(os) {
let testMethodName = symbolPath.join('$').replace(/\$[+-]/, '$').replace(/:/g, '_');
let example = examples[testMethodName];
if (!example) {
console.error(`MGLDocumentationExampleTests.test${testMethodName}() not found.`);
console.error(`MLNDocumentationExampleTests.test${testMethodName}() not found.`);
process.exit(1);
}

View File

@@ -1,5 +0,0 @@
#pragma once
#import <Foundation/Foundation.h>
#define MGL_EXPORT __attribute__((visibility ("default")))

View File

@@ -1,156 +0,0 @@
#import "MGLGeometry.h"
#import <TargetConditionals.h>
#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#endif
#import <mbgl/util/geo.hpp>
#import <mbgl/util/geometry.hpp>
#import <array>
typedef double MGLLocationRadians;
typedef double MGLRadianDistance;
typedef double MGLRadianDirection;
/** Defines the coordinate by a `MGLRadianCoordinate2D`. */
typedef struct MGLRadianCoordinate2D {
MGLLocationRadians latitude;
MGLLocationRadians longitude;
} MGLRadianCoordinate2D;
/**
Creates a new `MGLRadianCoordinate2D` from the given latitudinal and longitudinal.
*/
NS_INLINE MGLRadianCoordinate2D MGLRadianCoordinate2DMake(MGLLocationRadians latitude, MGLLocationRadians longitude) {
MGLRadianCoordinate2D radianCoordinate;
radianCoordinate.latitude = latitude;
radianCoordinate.longitude = longitude;
return radianCoordinate;
}
/// Returns the smallest rectangle that contains both the given rectangle and
/// the given point.
CGRect MGLExtendRect(CGRect rect, CGPoint point);
#if TARGET_OS_IPHONE
NS_INLINE NSString *MGLStringFromSize(CGSize size) {
return NSStringFromCGSize(size);
}
#else
NS_INLINE NSString *MGLStringFromSize(NSSize size) {
return NSStringFromSize(size);
}
#endif
NS_INLINE NSString *MGLStringFromCLLocationCoordinate2D(CLLocationCoordinate2D coordinate) {
return [NSString stringWithFormat:@"(lat: %f, lon: %f)", coordinate.latitude, coordinate.longitude];
}
mbgl::LatLng MGLLatLngFromLocationCoordinate2D(CLLocationCoordinate2D coordinate);
NS_INLINE mbgl::Point<double> MGLPointFromLocationCoordinate2D(CLLocationCoordinate2D coordinate) {
return mbgl::Point<double>(coordinate.longitude, coordinate.latitude);
}
NS_INLINE CLLocationCoordinate2D MGLLocationCoordinate2DFromPoint(mbgl::Point<double> point) {
return CLLocationCoordinate2DMake(point.y, point.x);
}
NS_INLINE CLLocationCoordinate2D MGLLocationCoordinate2DFromLatLng(mbgl::LatLng latLng) {
return CLLocationCoordinate2DMake(latLng.latitude(), latLng.longitude());
}
NS_INLINE MGLCoordinateBounds MGLCoordinateBoundsFromLatLngBounds(mbgl::LatLngBounds latLngBounds) {
return MGLCoordinateBoundsMake(MGLLocationCoordinate2DFromLatLng(latLngBounds.southwest()),
MGLLocationCoordinate2DFromLatLng(latLngBounds.northeast()));
}
NS_INLINE mbgl::LatLngBounds MGLLatLngBoundsFromCoordinateBounds(MGLCoordinateBounds coordinateBounds) {
return mbgl::LatLngBounds::hull(MGLLatLngFromLocationCoordinate2D(coordinateBounds.sw),
MGLLatLngFromLocationCoordinate2D(coordinateBounds.ne));
}
NS_INLINE std::array<mbgl::LatLng, 4> MGLLatLngArrayFromCoordinateQuad(MGLCoordinateQuad quad) {
return { MGLLatLngFromLocationCoordinate2D(quad.topLeft),
MGLLatLngFromLocationCoordinate2D(quad.topRight),
MGLLatLngFromLocationCoordinate2D(quad.bottomRight),
MGLLatLngFromLocationCoordinate2D(quad.bottomLeft) };
}
NS_INLINE MGLCoordinateQuad MGLCoordinateQuadFromLatLngArray(std::array<mbgl::LatLng, 4> quad) {
return { MGLLocationCoordinate2DFromLatLng(quad[0]),
MGLLocationCoordinate2DFromLatLng(quad[3]),
MGLLocationCoordinate2DFromLatLng(quad[2]),
MGLLocationCoordinate2DFromLatLng(quad[1]) };
}
/**
YES if the coordinate is valid or NO if it is not.
Considers extended coordinates.
*/
NS_INLINE BOOL MGLLocationCoordinate2DIsValid(CLLocationCoordinate2D coordinate) {
return (coordinate.latitude <= 90.0 &&
coordinate.latitude >= -90.0 &&
coordinate.longitude <= 360.0 &&
coordinate.longitude >= -360.0);
}
#if TARGET_OS_IPHONE
#define MGLEdgeInsets UIEdgeInsets
#define MGLEdgeInsetsMake UIEdgeInsetsMake
#else
#define MGLEdgeInsets NSEdgeInsets
#define MGLEdgeInsetsMake NSEdgeInsetsMake
#endif
NS_INLINE mbgl::EdgeInsets MGLEdgeInsetsFromNSEdgeInsets(MGLEdgeInsets insets) {
return { insets.top, insets.left, insets.bottom, insets.right };
}
NS_INLINE MGLEdgeInsets NSEdgeInsetsFromMGLEdgeInsets(const mbgl::EdgeInsets& insets) {
return MGLEdgeInsetsMake(insets.top(), insets.left(), insets.bottom(), insets.right());
}
/// Returns the combination of two edge insets.
NS_INLINE MGLEdgeInsets MGLEdgeInsetsInsetEdgeInset(MGLEdgeInsets base, MGLEdgeInsets inset) {
return MGLEdgeInsetsMake(base.top + inset.top,
base.left + inset.left,
base.bottom + inset.bottom,
base.right + inset.right);
}
/** Returns MGLRadianCoordinate2D, converted from CLLocationCoordinate2D. */
NS_INLINE MGLRadianCoordinate2D MGLRadianCoordinateFromLocationCoordinate(CLLocationCoordinate2D locationCoordinate) {
return MGLRadianCoordinate2DMake(MGLRadiansFromDegrees(locationCoordinate.latitude),
MGLRadiansFromDegrees(locationCoordinate.longitude));
}
/**
Returns the distance in radians given two coordinates.
*/
MGLRadianDistance MGLDistanceBetweenRadianCoordinates(MGLRadianCoordinate2D from, MGLRadianCoordinate2D to);
/**
Returns direction in radians given two coordinates.
*/
MGLRadianDirection MGLRadianCoordinatesDirection(MGLRadianCoordinate2D from, MGLRadianCoordinate2D to);
/**
Returns a coordinate at a given distance and direction away from coordinate.
*/
MGLRadianCoordinate2D MGLRadianCoordinateAtDistanceFacingDirection(MGLRadianCoordinate2D coordinate,
MGLRadianDistance distance,
MGLRadianDirection direction);
/**
Returns the direction from one coordinate to another.
*/
CLLocationDirection MGLDirectionBetweenCoordinates(CLLocationCoordinate2D firstCoordinate, CLLocationCoordinate2D secondCoordinate);
/**
Returns a point with coordinates rounded to the nearest logical pixel.
*/
CGPoint MGLPointRounded(CGPoint point);
MGLMatrix4 MGLMatrix4Make(std::array<double, 16> mat);

View File

@@ -1,5 +0,0 @@
#import "MGLLocationManager.h"
@interface MGLCLLocationManager : NSObject<MGLLocationManager>
@end

View File

@@ -1,67 +0,0 @@
#import "MGLLoggingConfiguration.h"
NS_INLINE NSString *MGLStringFromBOOL(BOOL value) {
return value ? @"YES" : @"NO";
}
#if TARGET_OS_OSX
NS_INLINE NSString *MGLStringFromNSEdgeInsets(NSEdgeInsets insets) {
return [NSString stringWithFormat:@"{ top: %f, left: %f, bottom: %f, right: %f", insets.top, insets.left, insets.bottom, insets.right];
}
#endif
#ifdef MGL_LOGGING_DISABLED
#define MGLLogInfo(...)
#define MGLLogDebug(...)
#define MGLLogWarning(...)
#define MGLLogError(...)
#define MGLLogFault(...)
#else
#if MGL_LOGGING_ENABLE_DEBUG
#define MGLLogDebug(message, ...) MGLLogWithType(MGLLoggingLevelDebug, __PRETTY_FUNCTION__, __LINE__, message, ##__VA_ARGS__)
#else
#define MGLLogDebug(...)
#endif
#define MGLLogInfo(message, ...) MGLLogWithType(MGLLoggingLevelInfo, __PRETTY_FUNCTION__, __LINE__, message, ##__VA_ARGS__)
#define MGLLogWarning(message, ...) MGLLogWithType(MGLLoggingLevelWarning, __PRETTY_FUNCTION__, __LINE__, message, ##__VA_ARGS__)
#define MGLLogError(message, ...) MGLLogWithType(MGLLoggingLevelError, __PRETTY_FUNCTION__, __LINE__, message, ##__VA_ARGS__)
#define MGLLogFault(message, ...) MGLLogWithType(MGLLoggingLevelFault, __PRETTY_FUNCTION__, __LINE__, message, ##__VA_ARGS__)
#endif
#define MGLAssert(expression, message, ...) \
__extension__({ \
if (__builtin_expect(!(expression), 0)) { \
MGLLogFault(message, ##__VA_ARGS__); \
} \
NSAssert(expression, message, ##__VA_ARGS__); \
})
#define MGLCAssert(expression, message, ...) \
__extension__({ \
if (__builtin_expect(!(expression), 0)) { \
MGLLogFault(message, ##__VA_ARGS__); \
} \
NSCAssert(expression, message, ##__VA_ARGS__); \
})
#ifndef MGL_LOGGING_DISABLED
#define MGLLogWithType(type, function, line, message, ...) \
{ \
if ([MGLLoggingConfiguration sharedConfiguration].loggingLevel != MGLLoggingLevelNone && type <= [MGLLoggingConfiguration sharedConfiguration].loggingLevel) \
{ \
[[MGLLoggingConfiguration sharedConfiguration] logCallingFunction:function functionLine:line messageType:type format:(message), ##__VA_ARGS__]; \
} \
}
@interface MGLLoggingConfiguration (Private)
- (void)logCallingFunction:(const char *)callingFunction functionLine:(NSUInteger)functionLine messageType:(MGLLoggingLevel)type format:(id)messageFormat, ...;
@end
#endif

View File

@@ -1,56 +0,0 @@
#import <Foundation/Foundation.h>
#import "MGLFoundation.h"
#import "MGLShape.h"
#import "MGLTypes.h"
NS_ASSUME_NONNULL_BEGIN
/**
An `MGLShapeCollection` object represents a shape consisting of zero or more
distinct but related shapes that are instances of `MGLShape`. The constituent
shapes can be a mixture of different kinds of shapes.
`MGLShapeCollection` is most commonly used to add multiple shapes to a single
`MGLShapeSource`. Configure the appearance of an `MGLShapeSource`’s or
`MGLVectorTileSource`’s shape collection collectively using an
`MGLSymbolStyleLayer` object, or use multiple instances of
`MGLCircleStyleLayer`, `MGLFillStyleLayer`, and `MGLLineStyleLayer` to
configure the appearance of each kind of shape inside the collection.
You cannot add an `MGLShapeCollection` object directly to a map view as an
annotation. However, you can create individual `MGLPointAnnotation`,
`MGLPolyline`, and `MGLPolygon` objects from the `shapes` array and add those
annotation objects to the map view using the `-[MGLMapView addAnnotations:]`
method.
To represent a collection of point, polyline, or polygon shapes, it may be more
convenient to use an `MGLPointCollection`, `MGLMultiPolyline`, or
`MGLMultiPolygon` object, respectively. To access a shape collection’s
attributes, use the corresponding `MGLFeature` object.
A shape collection is known as a
<a href="https://tools.ietf.org/html/rfc7946#section-3.1.8">GeometryCollection</a>
geometry in GeoJSON.
*/
MGL_EXPORT
@interface MGLShapeCollection : MGLShape
/**
An array of shapes forming the shape collection.
*/
@property (nonatomic, copy, readonly) NSArray<MGLShape *> *shapes;
/**
Creates and returns a shape collection consisting of the given shapes.
@param shapes The array of shapes defining the shape collection. The data in
this array is copied to the new object.
@return A new shape collection object.
*/
+ (instancetype)shapeCollectionWithShapes:(NSArray<MGLShape *> *)shapes;
@end
NS_ASSUME_NONNULL_END

View File

@@ -1,32 +0,0 @@
#import "MGLFoundation.h"
#import "MGLShapeSource.h"
#include <mbgl/util/immutable.hpp>
NS_ASSUME_NONNULL_BEGIN
namespace mbgl {
namespace style {
struct GeoJSONOptions;
}
}
MGL_EXPORT
mbgl::Immutable<mbgl::style::GeoJSONOptions> MGLGeoJSONOptionsFromDictionary(NSDictionary<MGLShapeSourceOption, id> *options);
@interface MGLShapeSource (Private)
/**
:nodoc:
Debug log showing structure of an `MGLFeature`. This method recurses in the case
that the feature conforms to `MGLCluster`. This method is used for testing and
should be considered experimental, likely to be removed or changed in future
releases.
@param feature An object that conforms to the `MGLFeature` protocol.
@param indent Used during recursion. Specify 0.
*/
- (void)debugRecursiveLogForFeature:(id<MGLFeature>)feature indent:(NSUInteger)indent;
@end
NS_ASSUME_NONNULL_END

View File

@@ -1,40 +0,0 @@
#import "MGLStyle.h"
#import "MGLStyleLayer.h"
#import "MGLFillStyleLayer.h"
NS_ASSUME_NONNULL_BEGIN
namespace mbgl {
namespace style {
class Style;
}
}
@class MGLAttributionInfo;
@class MGLMapView;
@class MGLOpenGLStyleLayer;
@class MGLVectorTileSource;
@class MGLVectorStyleLayer;
@interface MGLStyle (Private)
- (instancetype)initWithRawStyle:(mbgl::style::Style *)rawStyle stylable:(id <MGLStylable>)stylable;
@property (nonatomic, readonly, weak) id <MGLStylable> stylable;
@property (nonatomic, readonly) mbgl::style::Style *rawStyle;
- (nullable NSArray<MGLAttributionInfo *> *)attributionInfosWithFontSize:(CGFloat)fontSize linkColor:(nullable MGLColor *)linkColor;
@property (nonatomic, readonly, strong) NSMutableDictionary<NSString *, MGLOpenGLStyleLayer *> *openGLLayers;
- (void)setStyleClasses:(NSArray<NSString *> *)appliedClasses transitionDuration:(NSTimeInterval)transitionDuration;
@end
@interface MGLStyle (MGLStreetsAdditions)
@property (nonatomic, readonly, copy) NSArray<MGLVectorStyleLayer *> *placeStyleLayers;
@property (nonatomic, readonly, copy) NSArray<MGLVectorStyleLayer *> *roadStyleLayers;
@end
NS_ASSUME_NONNULL_END

View File

@@ -1,5 +0,0 @@
#import "MGLTypes.h"
const MGLExceptionName MGLAbstractClassException = @"MGLAbstractClassException";
NSString * const MGLErrorDomain = @"MGLErrorDomain";

View File

@@ -5,7 +5,7 @@
NS_ASSUME_NONNULL_BEGIN
/**
The `MGLAnnotation` protocol is used to provide annotation-related information
The `MLNAnnotation` protocol is used to provide annotation-related information
to a map view. To use this protocol, you adopt it in any custom objects that
store or represent annotation data. Each object then serves as the source of
information about a single map annotation and provides critical information,
@@ -21,9 +21,9 @@ NS_ASSUME_NONNULL_BEGIN
See the <a href="https://docs.mapbox.com/ios/maps/examples/annotation-models/">
Annotation models</a> and <a href="https://docs.mapbox.com/ios/maps/examples/annotation-views/">
Annotation views</a> examples to learn how to add objects that follow the
`MGLAnnotation` protocol.
`MLNAnnotation` protocol.
*/
@protocol MGLAnnotation <NSObject>
@protocol MLNAnnotation <NSObject>
// MARK: Position Attributes

View File

@@ -1,37 +1,37 @@
#import "MGLFoundation.h"
#import "MLNFoundation.h"
NS_ASSUME_NONNULL_BEGIN
/** Options for `MGLAttributedExpression.attributes`. */
typedef NSString * MGLAttributedExpressionKey NS_TYPED_ENUM;
/** Options for `MLNAttributedExpression.attributes`. */
typedef NSString * MLNAttributedExpressionKey NS_TYPED_ENUM;
/** The font name string array expression used to format the text. */
FOUNDATION_EXTERN MGL_EXPORT MGLAttributedExpressionKey const MGLFontNamesAttribute;
FOUNDATION_EXTERN MLN_EXPORT MLNAttributedExpressionKey const MLNFontNamesAttribute;
/** The font scale number expression relative to `MGLSymbolStyleLayer.textFontSize` used to format the text. */
FOUNDATION_EXTERN MGL_EXPORT MGLAttributedExpressionKey const MGLFontScaleAttribute;
/** The font scale number expression relative to `MLNSymbolStyleLayer.textFontSize` used to format the text. */
FOUNDATION_EXTERN MLN_EXPORT MLNAttributedExpressionKey const MLNFontScaleAttribute;
/** The font color expression used to format the text. */
FOUNDATION_EXTERN MGL_EXPORT MGLAttributedExpressionKey const MGLFontColorAttribute;
FOUNDATION_EXTERN MLN_EXPORT MLNAttributedExpressionKey const MLNFontColorAttribute;
/**
An `MGLAttributedExpression` object associates text formatting attibutes (such as font size or
An `MLNAttributedExpression` object associates text formatting attibutes (such as font size or
font names) to an `NSExpression`.
### Example
```swift
let redColor = UIColor.red
let expression = NSExpression(forConstantValue: "Foo")
let attributes: [MGLAttributedExpressionKey: NSExpression] = [.fontNamesAttribute : NSExpression(forConstantValue: ["DIN Offc Pro Italic",
let attributes: [MLNAttributedExpressionKey: NSExpression] = [.fontNamesAttribute : NSExpression(forConstantValue: ["DIN Offc Pro Italic",
"Arial Unicode MS Regular"]),
.fontScaleAttribute: NSExpression(forConstantValue: 1.2),
.fontColorAttribute: NSExpression(forConstantValue: redColor)]
let attributedExpression = MGLAttributedExpression(expression, attributes:attributes)
let attributedExpression = MLNAttributedExpression(expression, attributes:attributes)
```
*/
MGL_EXPORT
@interface MGLAttributedExpression : NSObject
MLN_EXPORT
@interface MLNAttributedExpression : NSObject
/**
The expression content of the receiver as `NSExpression`.
@@ -43,44 +43,44 @@ MGL_EXPORT
The formatting attributes dictionary.
Key | Value Type
--- | ---
`MGLFontNamesAttribute` | An `NSExpression` evaluating to an `NSString` array.
`MGLFontScaleAttribute` | An `NSExpression` evaluating to an `NSNumber` value.
`MGLFontColorAttribute` | An `NSExpression` evaluating to an `UIColor`.
`MLNFontNamesAttribute` | An `NSExpression` evaluating to an `NSString` array.
`MLNFontScaleAttribute` | An `NSExpression` evaluating to an `NSNumber` value.
`MLNFontColorAttribute` | An `NSExpression` evaluating to an `UIColor`.
*/
@property (strong, nonatomic, readonly) NSDictionary<MGLAttributedExpressionKey, NSExpression *> *attributes;
@property (strong, nonatomic, readonly) NSDictionary<MLNAttributedExpressionKey, NSExpression *> *attributes;
#else
/**
The formatting attributes dictionary.
Key | Value Type
--- | ---
`MGLFontNamesAttribute` | An `NSExpression` evaluating to an `NSString` array.
`MGLFontScaleAttribute` | An `NSExpression` evaluating to an `NSNumber` value.
`MGLFontColorAttribute` | An `NSExpression` evaluating to an `NSColor` on macos.
`MLNFontNamesAttribute` | An `NSExpression` evaluating to an `NSString` array.
`MLNFontScaleAttribute` | An `NSExpression` evaluating to an `NSNumber` value.
`MLNFontColorAttribute` | An `NSExpression` evaluating to an `NSColor` on macos.
*/
@property (strong, nonatomic, readonly) NSDictionary<MGLAttributedExpressionKey, NSExpression *> *attributes;
@property (strong, nonatomic, readonly) NSDictionary<MLNAttributedExpressionKey, NSExpression *> *attributes;
#endif
/**
Returns an `MGLAttributedExpression` object initialized with an expression and no attribute information.
Returns an `MLNAttributedExpression` object initialized with an expression and no attribute information.
*/
- (instancetype)initWithExpression:(NSExpression *)expression;
/**
Returns an `MGLAttributedExpression` object initialized with an expression and text format attributes.
Returns an `MLNAttributedExpression` object initialized with an expression and text format attributes.
*/
- (instancetype)initWithExpression:(NSExpression *)expression attributes:(nonnull NSDictionary <MGLAttributedExpressionKey, NSExpression *> *)attrs;
- (instancetype)initWithExpression:(NSExpression *)expression attributes:(nonnull NSDictionary <MLNAttributedExpressionKey, NSExpression *> *)attrs;
/**
Creates an `MGLAttributedExpression` object initialized with an expression and the format attributes for font names and font size.
Creates an `MLNAttributedExpression` object initialized with an expression and the format attributes for font names and font size.
*/
+ (instancetype)attributedExpression:(NSExpression *)expression fontNames:(nullable NSArray<NSString*> *)fontNames fontScale:(nullable NSNumber *)fontScale;
/**
Creates an `MGLAttributedExpression` object initialized with an expression and the format attributes dictionary.
Creates an `MLNAttributedExpression` object initialized with an expression and the format attributes dictionary.
*/
+ (instancetype)attributedExpression:(NSExpression *)expression attributes:(nonnull NSDictionary <MGLAttributedExpressionKey, NSExpression *> *)attrs;
+ (instancetype)attributedExpression:(NSExpression *)expression attributes:(nonnull NSDictionary <MLNAttributedExpressionKey, NSExpression *> *)attrs;
@end

View File

@@ -1,11 +1,11 @@
#import "MGLAttributedExpression.h"
#import "MGLLoggingConfiguration_Private.h"
#import "MLNAttributedExpression.h"
#import "MLNLoggingConfiguration_Private.h"
const MGLAttributedExpressionKey MGLFontNamesAttribute = @"text-font";
const MGLAttributedExpressionKey MGLFontScaleAttribute = @"font-scale";
const MGLAttributedExpressionKey MGLFontColorAttribute = @"text-color";
const MLNAttributedExpressionKey MLNFontNamesAttribute = @"text-font";
const MLNAttributedExpressionKey MLNFontScaleAttribute = @"font-scale";
const MLNAttributedExpressionKey MLNFontColorAttribute = @"text-color";
@implementation MGLAttributedExpression
@implementation MLNAttributedExpression
- (instancetype)initWithExpression:(NSExpression *)expression {
self = [self initWithExpression:expression attributes:@{}];
@@ -13,38 +13,38 @@ const MGLAttributedExpressionKey MGLFontColorAttribute = @"text-color";
}
+ (instancetype)attributedExpression:(NSExpression *)expression fontNames:(nullable NSArray<NSString *> *)fontNames fontScale:(nullable NSNumber *)fontScale {
MGLAttributedExpression *attributedExpression;
MLNAttributedExpression *attributedExpression;
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
if (fontNames && fontNames.count > 0) {
attrs[MGLFontNamesAttribute] = [NSExpression expressionForConstantValue:fontNames];
attrs[MLNFontNamesAttribute] = [NSExpression expressionForConstantValue:fontNames];
}
if (fontScale) {
attrs[MGLFontScaleAttribute] = [NSExpression expressionForConstantValue:fontScale];
attrs[MLNFontScaleAttribute] = [NSExpression expressionForConstantValue:fontScale];
}
attributedExpression = [[self alloc] initWithExpression:expression attributes:attrs];
return attributedExpression;
}
+ (instancetype)attributedExpression:(NSExpression *)expression attributes:(nonnull NSDictionary<MGLAttributedExpressionKey, NSExpression *> *)attrs {
MGLAttributedExpression *attributedExpression;
+ (instancetype)attributedExpression:(NSExpression *)expression attributes:(nonnull NSDictionary<MLNAttributedExpressionKey, NSExpression *> *)attrs {
MLNAttributedExpression *attributedExpression;
attributedExpression = [[self alloc] initWithExpression:expression attributes:attrs];
return attributedExpression;
}
- (instancetype)initWithExpression:(NSExpression *)expression attributes:(nonnull NSDictionary<MGLAttributedExpressionKey, NSExpression *> *)attrs {
- (instancetype)initWithExpression:(NSExpression *)expression attributes:(nonnull NSDictionary<MLNAttributedExpressionKey, NSExpression *> *)attrs {
if (self = [super init])
{
MGLLogInfo(@"Starting %@ initialization.", NSStringFromClass([self class]));
MLNLogInfo(@"Starting %@ initialization.", NSStringFromClass([self class]));
_expression = expression;
_attributes = attrs;
MGLLogInfo(@"Finalizing %@ initialization.", NSStringFromClass([self class]));
MLNLogInfo(@"Finalizing %@ initialization.", NSStringFromClass([self class]));
}
return self;
}
@@ -53,7 +53,7 @@ const MGLAttributedExpressionKey MGLFontColorAttribute = @"text-color";
BOOL result = NO;
if ([object isKindOfClass:[self class]]) {
MGLAttributedExpression *otherObject = object;
MLNAttributedExpression *otherObject = object;
result = [self.expression isEqual:otherObject.expression] &&
[_attributes isEqual:otherObject.attributes];
}
@@ -62,7 +62,7 @@ const MGLAttributedExpressionKey MGLFontColorAttribute = @"text-color";
}
- (NSString *)description {
return [NSString stringWithFormat:@"MGLAttributedExpression<Expression: %@ Attributes: %@>", self.expression, self.attributes];
return [NSString stringWithFormat:@"MLNAttributedExpression<Expression: %@ Attributes: %@>", self.expression, self.attributes];
}
@end

View File

@@ -2,35 +2,35 @@
#import <CoreGraphics/CoreGraphics.h>
#import <CoreLocation/CoreLocation.h>
#import "MGLFoundation.h"
#import "MGLTypes.h"
#import "MLNFoundation.h"
#import "MLNTypes.h"
NS_ASSUME_NONNULL_BEGIN
/**
The attribution info is represented in the longest format available.
*/
typedef NS_ENUM(NSUInteger, MGLAttributionInfoStyle) {
typedef NS_ENUM(NSUInteger, MLNAttributionInfoStyle) {
/**
Specifies a short attribution info style.
*/
MGLAttributionInfoStyleShort = 1,
MLNAttributionInfoStyleShort = 1,
/**
Specifies a medium attribution info style.
*/
MGLAttributionInfoStyleMedium,
MLNAttributionInfoStyleMedium,
/**
Specifies a long attribution info style.
*/
MGLAttributionInfoStyleLong
MLNAttributionInfoStyleLong
};
/**
Information about an attribution statement, usually a copyright or trademark
statement, associated with a map content source.
*/
MGL_EXPORT
@interface MGLAttributionInfo : NSObject
MLN_EXPORT
@interface MLNAttributionInfo : NSObject
/**
Returns an initialized attribution info object with the given title and URL.
@@ -67,14 +67,14 @@ MGL_EXPORT
/**
Returns a copy of the current `title` formatted accordingly to `style`.
Example: If the `style` property is set to `MGLAttributionInfoStyleShort` and the
Example: If the `style` property is set to `MLNAttributionInfoStyleShort` and the
`title` property is set to `OpenStreetMap`, then this method returns `OSM`.
@param style The attribution info style.
@return The `NSAttributedString` styled title.
*/
- (NSAttributedString *)titleWithStyle:(MGLAttributionInfoStyle)style;
- (NSAttributedString *)titleWithStyle:(MLNAttributionInfoStyle)style;
@end

View File

@@ -1,4 +1,4 @@
#import "MGLAttributionInfo_Private.h"
#import "MLNAttributionInfo_Private.h"
#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
@@ -6,18 +6,18 @@
#import <Cocoa/Cocoa.h>
#endif
#import "MGLSettings.h"
#import "MGLMapCamera.h"
#import "NSArray+MGLAdditions.h"
#import "NSBundle+MGLAdditions.h"
#import "NSString+MGLAdditions.h"
#import "MGLLoggingConfiguration_Private.h"
#import "MLNSettings.h"
#import "MLNMapCamera.h"
#import "NSArray+MLNAdditions.h"
#import "NSBundle+MLNAdditions.h"
#import "NSString+MLNAdditions.h"
#import "MLNLoggingConfiguration_Private.h"
#include <string>
@implementation MGLAttributionInfo
@implementation MLNAttributionInfo
+ (NSArray<MGLAttributionInfo *> *)attributionInfosFromHTMLString:(nullable NSString *)htmlString fontSize:(CGFloat)fontSize linkColor:(nullable MGLColor *)linkColor {
+ (NSArray<MLNAttributionInfo *> *)attributionInfosFromHTMLString:(nullable NSString *)htmlString fontSize:(CGFloat)fontSize linkColor:(nullable MLNColor *)linkColor {
if (!htmlString) {
return @[];
}
@@ -92,7 +92,7 @@
options:0
usingBlock:
^(id _Nullable value, NSRange range, BOOL * _Nonnull stop) {
MGLCAssert(!value || [value isKindOfClass:[NSURL class]], @"If present, URL attribute must be an NSURL.");
MLNCAssert(!value || [value isKindOfClass:[NSURL class]], @"If present, URL attribute must be an NSURL.");
// Detect feedback links by the bogus style rule applied above.
NSNumber *strokeWidth = [attributedString attribute:NSStrokeWidthAttributeName
@@ -116,16 +116,16 @@
NSMutableAttributedString *unlinkedTitle = [title mutableCopy];
[unlinkedTitle removeAttribute:NSLinkAttributeName range:unlinkedTitle.mgl_wholeRange];
MGLAttributionInfo *info = [[MGLAttributionInfo alloc] initWithTitle:unlinkedTitle URL:value];
MLNAttributionInfo *info = [[MLNAttributionInfo alloc] initWithTitle:unlinkedTitle URL:value];
info.feedbackLink = isFeedbackLink;
[infos addObject:info];
}];
return infos;
}
+ (NSAttributedString *)attributedStringForAttributionInfos:(NSArray<MGLAttributionInfo *> *)attributionInfos {
+ (NSAttributedString *)attributedStringForAttributionInfos:(NSArray<MLNAttributionInfo *> *)attributionInfos {
NSMutableArray *titles = [NSMutableArray arrayWithCapacity:attributionInfos.count];
for (MGLAttributionInfo *info in attributionInfos) {
for (MLNAttributionInfo *info in attributionInfos) {
NSMutableAttributedString *title = info.title.mutableCopy;
if (info.URL) {
[title addAttribute:NSLinkAttributeName value:info.URL range:title.mgl_wholeRange];
@@ -145,14 +145,14 @@
- (id)copyWithZone:(nullable NSZone *)zone
{
MGLAttributionInfo *info = [[[self class] allocWithZone:zone] initWithTitle:_title
MLNAttributionInfo *info = [[[self class] allocWithZone:zone] initWithTitle:_title
URL:_URL];
info.feedbackLink = _feedbackLink;
return info;
}
- (NSAttributedString *)titleWithStyle:(MGLAttributionInfoStyle)style
- (NSAttributedString *)titleWithStyle:(MLNAttributionInfoStyle)style
{
NSString *openStreetMap = NSLocalizedStringWithDefaultValue(@"OSM_FULL_NAME", @"Foundation", nil, @"OpenStreetMap", @"OpenStreetMap full name attribution");
NSString *OSM = NSLocalizedStringWithDefaultValue(@"OSM_SHORT_NAME", @"Foundation", nil, @"OSM", @"OpenStreetMap short name attribution");
@@ -160,7 +160,7 @@
NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithAttributedString:self.title];
[title removeAttribute:NSUnderlineStyleAttributeName range:NSMakeRange(0, [title.string length])];
BOOL isAbbreviated = (style == MGLAttributionInfoStyleShort);
BOOL isAbbreviated = (style == MLNAttributionInfoStyleShort);
if ([title.string rangeOfString:@"OpenStreetMap"].location != NSNotFound) {
[title.mutableString replaceOccurrencesOfString:@"OpenStreetMap" withString:isAbbreviated ? OSM : openStreetMap
@@ -187,7 +187,7 @@
`NSOrderedDescending` if it is a subset of the receiver, or `NSOrderedSame`
if there is no overlap.
*/
- (NSComparisonResult)subsetCompare:(MGLAttributionInfo *)otherInfo {
- (NSComparisonResult)subsetCompare:(MLNAttributionInfo *)otherInfo {
NSString *title = self.title.string;
NSString *otherTitle = otherInfo.title.string;
if ([title containsString:otherTitle]) {
@@ -201,12 +201,12 @@
@end
@implementation NSMutableArray (MGLAttributionInfoAdditions)
@implementation NSMutableArray (MLNAttributionInfoAdditions)
- (void)growArrayByAddingAttributionInfo:(MGLAttributionInfo *)info {
- (void)growArrayByAddingAttributionInfo:(MLNAttributionInfo *)info {
__block BOOL didInsertInfo = NO;
__block BOOL shouldAddInfo = YES;
[self enumerateObjectsUsingBlock:^(MGLAttributionInfo * _Nonnull existingInfo, NSUInteger idx, BOOL * _Nonnull stop) {
[self enumerateObjectsUsingBlock:^(MLNAttributionInfo * _Nonnull existingInfo, NSUInteger idx, BOOL * _Nonnull stop) {
switch ([info subsetCompare:existingInfo]) {
case NSOrderedDescending:
// The existing info object is a subset of the one we’re adding.
@@ -237,8 +237,8 @@
}
}
- (void)growArrayByAddingAttributionInfosFromArray:(NSArray<MGLAttributionInfo *> *)infos {
for (MGLAttributionInfo *info in infos) {
- (void)growArrayByAddingAttributionInfosFromArray:(NSArray<MLNAttributionInfo *> *)infos {
for (MLNAttributionInfo *info in infos) {
[self growArrayByAddingAttributionInfo:info];
}
}

View File

@@ -2,11 +2,11 @@
#import <CoreGraphics/CoreGraphics.h>
#import <CoreLocation/CoreLocation.h>
#import "MGLAttributionInfo.h"
#import "MLNAttributionInfo.h"
NS_ASSUME_NONNULL_BEGIN
@interface MGLAttributionInfo (Private)
@interface MLNAttributionInfo (Private)
/**
Parses and returns the attribution infos contained in the given HTML source
@@ -16,13 +16,13 @@ NS_ASSUME_NONNULL_BEGIN
@param fontSize The default text size in points.
@param linkColor The default link color.
*/
+ (NSArray<MGLAttributionInfo *> *)attributionInfosFromHTMLString:(nullable NSString *)htmlString fontSize:(CGFloat)fontSize linkColor:(nullable MGLColor *)linkColor;
+ (NSArray<MLNAttributionInfo *> *)attributionInfosFromHTMLString:(nullable NSString *)htmlString fontSize:(CGFloat)fontSize linkColor:(nullable MLNColor *)linkColor;
+ (NSAttributedString *)attributedStringForAttributionInfos:(NSArray<MGLAttributionInfo *> *)attributionInfos;
+ (NSAttributedString *)attributedStringForAttributionInfos:(NSArray<MLNAttributionInfo *> *)attributionInfos;
@end
@interface NSMutableArray (MGLAttributionInfoAdditions)
@interface NSMutableArray (MLNAttributionInfoAdditions)
/**
Adds the given attribution info object to the receiver as long as it isn’t
@@ -31,7 +31,7 @@ NS_ASSUME_NONNULL_BEGIN
@param info The info object to add to the receiver.
*/
- (void)growArrayByAddingAttributionInfo:(MGLAttributionInfo *)info;
- (void)growArrayByAddingAttributionInfo:(MLNAttributionInfo *)info;
/**
Adds each of the given attribution info objects to the receiver as long as it
@@ -40,7 +40,7 @@ NS_ASSUME_NONNULL_BEGIN
@param infos An array of info objects to add to the receiver.
*/
- (void)growArrayByAddingAttributionInfosFromArray:(NSArray<MGLAttributionInfo *> *)infos;
- (void)growArrayByAddingAttributionInfosFromArray:(NSArray<MLNAttributionInfo *> *)infos;
@end

View File

@@ -1,23 +1,23 @@
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#import "MGLFoundation.h"
#import "MLNFoundation.h"
NS_ASSUME_NONNULL_BEGIN
/**
The `MGLClockDirectionFormatter` class provides properly formatted descriptions
The `MLNClockDirectionFormatter` class provides properly formatted descriptions
of headings relative to the user, known as <i>clock positions</i>. For
example, a value of `90` may be formatted as “3 o’clock”, depending on the
locale.
Use this class to create localized heading strings when displaying directions
relative to the user’s current location and heading. To format a direction
irrespective of the user’s orientation, use `MGLCompassDirectionFormatter`
irrespective of the user’s orientation, use `MLNCompassDirectionFormatter`
instead.
*/
MGL_EXPORT
@interface MGLClockDirectionFormatter : NSFormatter
MLN_EXPORT
@interface MLNClockDirectionFormatter : NSFormatter
/**
The unit style used by this formatter.
@@ -37,7 +37,7 @@ MGL_EXPORT
- (NSString *)stringFromDirection:(CLLocationDirection)direction;
/**
This method is not supported for the `MGLDirectionFormatter` class.
This method is not supported for the `MLNDirectionFormatter` class.
*/
- (BOOL)getObjectValue:(out id __nullable * __nullable)obj forString:(NSString *)string errorDescription:(out NSString * __nullable * __nullable)error;

View File

@@ -1,12 +1,12 @@
#import "MGLClockDirectionFormatter.h"
#import "MLNClockDirectionFormatter.h"
#import "NSBundle+MGLAdditions.h"
#import "MGLLoggingConfiguration_Private.h"
#import "NSBundle+MLNAdditions.h"
#import "MLNLoggingConfiguration_Private.h"
#define wrap(value, min, max) \
(fmod((fmod((value - min), (max - min)) + (max - min)), (max - min)) + min)
@implementation MGLClockDirectionFormatter {
@implementation MLNClockDirectionFormatter {
NSNumberFormatter *_numberFormatter;
}
@@ -53,7 +53,7 @@
}
- (BOOL)getObjectValue:(out id __nullable * __nullable)obj forString:(NSString *)string errorDescription:(out NSString * __nullable * __nullable)error {
MGLAssert(NO, @"-getObjectValue:forString:errorDescription: has not been implemented");
MLNAssert(NO, @"-getObjectValue:forString:errorDescription: has not been implemented");
return NO;
}

View File

@@ -1,6 +1,6 @@
#import "MGLFoundation.h"
#import "MLNFoundation.h"
@protocol MGLFeature;
@protocol MLNFeature;
NS_ASSUME_NONNULL_BEGIN
@@ -8,39 +8,39 @@ NS_ASSUME_NONNULL_BEGIN
An `NSUInteger` constant used to indicate an invalid cluster identifier.
This indicates a missing cluster feature.
*/
FOUNDATION_EXTERN MGL_EXPORT const NSUInteger MGLClusterIdentifierInvalid;
FOUNDATION_EXTERN MLN_EXPORT const NSUInteger MLNClusterIdentifierInvalid;
/**
A protocol that feature subclasses (i.e. those already conforming to
the `MGLFeature` protocol) conform to if they represent clusters.
the `MLNFeature` protocol) conform to if they represent clusters.
Currently the only class that conforms to `MGLCluster` is
`MGLPointFeatureCluster` (a subclass of `MGLPointFeature`).
Currently the only class that conforms to `MLNCluster` is
`MLNPointFeatureCluster` (a subclass of `MLNPointFeature`).
To check if a feature is a cluster, check conformity to `MGLCluster`, for
To check if a feature is a cluster, check conformity to `MLNCluster`, for
example:
```swift
let shape = try! MGLShape(data: clusterShapeData, encoding: String.Encoding.utf8.rawValue)
let shape = try! MLNShape(data: clusterShapeData, encoding: String.Encoding.utf8.rawValue)
guard let pointFeature = shape as? MGLPointFeature else {
guard let pointFeature = shape as? MLNPointFeature else {
throw ExampleError.unexpectedFeatureType
}
// Check for cluster conformance
guard let cluster = pointFeature as? MGLCluster else {
guard let cluster = pointFeature as? MLNCluster else {
throw ExampleError.featureIsNotACluster
}
// Currently the only supported class that conforms to `MGLCluster` is
// `MGLPointFeatureCluster`
guard cluster is MGLPointFeatureCluster else {
// Currently the only supported class that conforms to `MLNCluster` is
// `MLNPointFeatureCluster`
guard cluster is MLNPointFeatureCluster else {
throw ExampleError.unexpectedFeatureType
}
```
*/
MGL_EXPORT
@protocol MGLCluster <MGLFeature>
MLN_EXPORT
@protocol MLNCluster <MLNFeature>
/** The identifier for the cluster. */
@property (nonatomic, readonly) NSUInteger clusterIdentifier;

View File

@@ -1,21 +1,21 @@
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#import "MGLFoundation.h"
#import "MLNFoundation.h"
NS_ASSUME_NONNULL_BEGIN
/**
The `MGLCompassDirectionFormatter` class provides properly formatted
The `MLNCompassDirectionFormatter` class provides properly formatted
descriptions of absolute headings. For example, a value of `90` may be
formatted as “east”, depending on the locale.
Use this class to create localized heading strings when displaying directions
irrespective of the user’s current location. To format a direction relative to
the user’s current location, use `MGLClockDirectionFormatter` instead.
the user’s current location, use `MLNClockDirectionFormatter` instead.
*/
MGL_EXPORT
@interface MGLCompassDirectionFormatter : NSFormatter
MLN_EXPORT
@interface MLNCompassDirectionFormatter : NSFormatter
/**
The unit style used by this formatter.
@@ -34,7 +34,7 @@ MGL_EXPORT
- (NSString *)stringFromDirection:(CLLocationDirection)direction;
/**
This method is not supported for the `MGLDirectionFormatter` class.
This method is not supported for the `MLNDirectionFormatter` class.
*/
- (BOOL)getObjectValue:(out id __nullable * __nullable)obj forString:(NSString *)string errorDescription:(out NSString * __nullable * __nullable)error;

View File

@@ -1,12 +1,12 @@
#import "MGLCompassDirectionFormatter.h"
#import "MLNCompassDirectionFormatter.h"
#import "NSBundle+MGLAdditions.h"
#import "MGLLoggingConfiguration_Private.h"
#import "NSBundle+MLNAdditions.h"
#import "MLNLoggingConfiguration_Private.h"
#define wrap(value, min, max) \
(fmod((fmod((value - min), (max - min)) + (max - min)), (max - min)) + min)
@implementation MGLCompassDirectionFormatter
@implementation MLNCompassDirectionFormatter
- (instancetype)init {
if (self = [super init]) {
@@ -96,7 +96,7 @@
NSLocalizedStringWithDefaultValue(@"COMPASS_NbW_LONG", @"Foundation", nil, @"north by west", @"North by west, long"),
];
MGLAssert(shortStrings.count == longStrings.count, @"Long and short compass direction string arrays must have the same size.");
MLNAssert(shortStrings.count == longStrings.count, @"Long and short compass direction string arrays must have the same size.");
});
NSInteger cardinalPoint = wrap(round(wrap(direction, 0, 360) / 360 * shortStrings.count), 0, shortStrings.count);
@@ -118,7 +118,7 @@
}
- (BOOL)getObjectValue:(out id __nullable * __nullable)obj forString:(NSString *)string errorDescription:(out NSString * __nullable * __nullable)error {
MGLAssert(NO, @"-getObjectValue:forString:errorDescription: has not been implemented");
MLNAssert(NO, @"-getObjectValue:forString:errorDescription: has not been implemented");
return NO;
}

View File

@@ -1,46 +1,46 @@
#import "MGLFoundation.h"
#import "MGLGeometry.h"
#import "MGLTypes.h"
#import "MGLShapeSource.h"
#import "MLNFoundation.h"
#import "MLNGeometry.h"
#import "MLNTypes.h"
#import "MLNShapeSource.h"
NS_ASSUME_NONNULL_BEGIN
@protocol MGLFeature;
@protocol MLNFeature;
/**
An `NSNumber` object containing a Boolean value; specifies whether the shape of
an `MGLComputedShapeSource` should be wrapped to accomodate coordinates with
an `MLNComputedShapeSource` should be wrapped to accomodate coordinates with
longitudes beyond −180 and 180. The default value is `NO`.
Setting this option to `YES` affects rendering performance.
This option is used with the `MGLComputedShapeSource` class; it is ignored when
creating an `MGLShapeSource` object.
This option is used with the `MLNComputedShapeSource` class; it is ignored when
creating an `MLNShapeSource` object.
*/
FOUNDATION_EXTERN MGL_EXPORT const MGLShapeSourceOption MGLShapeSourceOptionWrapsCoordinates;
FOUNDATION_EXTERN MLN_EXPORT const MLNShapeSourceOption MLNShapeSourceOptionWrapsCoordinates;
/**
An `NSNumber` object containing a Boolean value; specifies whether the shape of
an `MGLComputedShapeSource` should be clipped at the edge of each tile. The
an `MLNComputedShapeSource` should be clipped at the edge of each tile. The
default value is `NO`.
Setting this option to `YES` affects rendering performance. Use this option to
clip `MGLPolyline`s and `MGLPolygon`s at tile boundaries without artifacts.
clip `MLNPolyline`s and `MLNPolygon`s at tile boundaries without artifacts.
This option is used with the `MGLComputedShapeSource` class; it is ignored when
creating an `MGLShapeSource` object.
This option is used with the `MLNComputedShapeSource` class; it is ignored when
creating an `MLNShapeSource` object.
*/
FOUNDATION_EXTERN MGL_EXPORT const MGLShapeSourceOption MGLShapeSourceOptionClipsCoordinates;
FOUNDATION_EXTERN MLN_EXPORT const MLNShapeSourceOption MLNShapeSourceOptionClipsCoordinates;
FOUNDATION_EXTERN MGL_EXPORT MGLExceptionName const MGLInvalidDatasourceException;
FOUNDATION_EXTERN MLN_EXPORT MLNExceptionName const MLNInvalidDatasourceException;
/**
Data source for `MGLComputedShapeSource`. This protocol defines two optional methods for fetching
Data source for `MLNComputedShapeSource`. This protocol defines two optional methods for fetching
data, one based on tile coordinates, and one based on a bounding box. Classes that implement this
protocol must implement one, and only one of the methods. Methods on this protocol will not be
called on main thread, they will be called on the caller's `requestQueue`.
*/
@protocol MGLComputedShapeSourceDataSource <NSObject>
@protocol MLNComputedShapeSourceDataSource <NSObject>
@optional
/**
@@ -50,7 +50,7 @@ FOUNDATION_EXTERN MGL_EXPORT MGLExceptionName const MGLInvalidDatasourceExceptio
@param y Tile Y coordinate.
@param zoomLevel Tile zoom level.
*/
- (NSArray<MGLShape <MGLFeature> *>*)featuresInTileAtX:(NSUInteger)x y:(NSUInteger)y zoomLevel:(NSUInteger)zoomLevel;
- (NSArray<MLNShape <MLNFeature> *>*)featuresInTileAtX:(NSUInteger)x y:(NSUInteger)y zoomLevel:(NSUInteger)zoomLevel;
/**
Fetch features for a tile. This method will not be invoked on the main queue, it
@@ -58,33 +58,33 @@ FOUNDATION_EXTERN MGL_EXPORT MGLExceptionName const MGLInvalidDatasourceExceptio
@param bounds The bounds to fetch data for.
@param zoomLevel Tile zoom level.
*/
- (NSArray<MGLShape <MGLFeature> *>*)featuresInCoordinateBounds:(MGLCoordinateBounds)bounds zoomLevel:(NSUInteger)zoomLevel;
- (NSArray<MLNShape <MLNFeature> *>*)featuresInCoordinateBounds:(MLNCoordinateBounds)bounds zoomLevel:(NSUInteger)zoomLevel;
@end
/**
`MGLComputedShapeSource` is a map content source that supplies vector shapes,
`MLNComputedShapeSource` is a map content source that supplies vector shapes,
one tile at a time, to be shown on the map on demand. You implement a class
conforming to the `MGLComputedShapeSourceDataSource` protocol that returns
instances of `MGLShape` or `MGLFeature`, then add a computed shape source to an
`MGLStyle` object along with an `MGLVectorStyleLayer` object. The vector style
conforming to the `MLNComputedShapeSourceDataSource` protocol that returns
instances of `MLNShape` or `MLNFeature`, then add a computed shape source to an
`MLNStyle` object along with an `MLNVectorStyleLayer` object. The vector style
layer defines the appearance of any content supplied by the computed shape
source.
`MGLComputedShapeSource` is similar to `MGLShapeSource` but is optimized for
`MLNComputedShapeSource` is similar to `MLNShapeSource` but is optimized for
data sets that change dynamically or are too large to fit completely in memory.
It is also useful for data that is divided into tiles in a format other than
<a href="https://www.mapbox.com/vector-tiles/">Mapbox Vector Tiles</a>. For
<a href="http://geojson.org/">GeoJSON</a> data, use the `MGLShapeSource` class.
For static tiles or Mapbox Vector Tiles, use the `MGLVectorTileSource` class.
<a href="http://geojson.org/">GeoJSON</a> data, use the `MLNShapeSource` class.
For static tiles or Mapbox Vector Tiles, use the `MLNVectorTileSource` class.
You can add and remove sources dynamically using methods such as
`-[MGLStyle addSource:]` and `-[MGLStyle sourceWithIdentifier:]`. This class
`-[MLNStyle addSource:]` and `-[MLNStyle sourceWithIdentifier:]`. This class
cannot be represented in a style JSON file; you must add it ot the style at
runtime.
*/
MGL_EXPORT
@interface MGLComputedShapeSource : MGLSource
MLN_EXPORT
@interface MLNComputedShapeSource : MLNSource
/**
Returns a custom shape data source initialized with an identifier, and a
@@ -93,17 +93,17 @@ MGL_EXPORT
specification</a>.
This class supports the following options:
`MGLShapeSourceOptionMinimumZoomLevel`, `MGLShapeSourceOptionMaximumZoomLevel`,
`MGLShapeSourceOptionBuffer`,
`MGLShapeSourceOptionSimplificationTolerance`,
`MGLShapeSourceOptionWrapsCoordinates`, and
`MGLShapeSourceOptionClipsCoordinates`. Shapes provided by a computed
`MLNShapeSourceOptionMinimumZoomLevel`, `MLNShapeSourceOptionMaximumZoomLevel`,
`MLNShapeSourceOptionBuffer`,
`MLNShapeSourceOptionSimplificationTolerance`,
`MLNShapeSourceOptionWrapsCoordinates`, and
`MLNShapeSourceOptionClipsCoordinates`. Shapes provided by a computed
shape source cannot be clustered.
@param identifier A string that uniquely identifies the source.
@param options An `NSDictionary` of options for this source.
*/
- (instancetype)initWithIdentifier:(NSString *)identifier options:(nullable NSDictionary<MGLShapeSourceOption, id> *)options NS_DESIGNATED_INITIALIZER;
- (instancetype)initWithIdentifier:(NSString *)identifier options:(nullable NSDictionary<MLNShapeSourceOption, id> *)options NS_DESIGNATED_INITIALIZER;
/**
Returns a custom shape data source initialized with an identifier, data source, and a
@@ -112,29 +112,29 @@ MGL_EXPORT
specification</a>.
This class supports the following options:
`MGLShapeSourceOptionMinimumZoomLevel`, `MGLShapeSourceOptionMaximumZoomLevel`,
`MGLShapeSourceOptionBuffer`,
`MGLShapeSourceOptionSimplificationTolerance`,
`MGLShapeSourceOptionWrapsCoordinates`, and
`MGLShapeSourceOptionClipsCoordinates`. Shapes provided by a computed shape
`MLNShapeSourceOptionMinimumZoomLevel`, `MLNShapeSourceOptionMaximumZoomLevel`,
`MLNShapeSourceOptionBuffer`,
`MLNShapeSourceOptionSimplificationTolerance`,
`MLNShapeSourceOptionWrapsCoordinates`, and
`MLNShapeSourceOptionClipsCoordinates`. Shapes provided by a computed shape
source cannot be clustered.
@param identifier A string that uniquely identifies the source.
@param options An `NSDictionary` of options for this source.
*/
- (instancetype)initWithIdentifier:(NSString *)identifier dataSource:(id<MGLComputedShapeSourceDataSource>)dataSource options:(nullable NSDictionary<MGLShapeSourceOption, id> *)options;
- (instancetype)initWithIdentifier:(NSString *)identifier dataSource:(id<MLNComputedShapeSourceDataSource>)dataSource options:(nullable NSDictionary<MLNShapeSourceOption, id> *)options;
/**
Invalidates all the features and properties intersecting with or contained in
the specified bounds. New fetch requests will immediately be invoked on the
`MGLComputedShapeSourceDataSource`.
`MLNComputedShapeSourceDataSource`.
@param bounds Coordinate bounds to invalidate.
*/
- (void) invalidateBounds:(MGLCoordinateBounds)bounds;
- (void) invalidateBounds:(MLNCoordinateBounds)bounds;
/**
Invalidates all the feautres and properties of a given tile. A new fetch request
will immediately be invoked on the `MGLComputedShapeSourceDataSource`.
will immediately be invoked on the `MLNComputedShapeSourceDataSource`.
@param x Tile X coordinate.
@param y Tile Y coordinate.
@param zoomLevel Tile zoom level.
@@ -144,18 +144,18 @@ MGL_EXPORT
/**
Set a new set of features for a tile. This method can be invkoed from background threads.
For best performance, use this method only to update tiles that have already been requested
through `MGLComputedShapeSourceDataSource.`
through `MLNComputedShapeSourceDataSource.`
@param features Features for the tile.
@param x Tile X coordinate.
@param y Tile Y coordinate.
@param zoomLevel Tile zoom level.
*/
- (void) setFeatures:(NSArray<MGLShape <MGLFeature> *>*)features inTileAtX:(NSUInteger)x y:(NSUInteger)y zoomLevel:(NSUInteger)zoomLevel;
- (void) setFeatures:(NSArray<MLNShape <MLNFeature> *>*)features inTileAtX:(NSUInteger)x y:(NSUInteger)y zoomLevel:(NSUInteger)zoomLevel;
/**
An object that implements the `MGLComputedShapeSourceDataSource` protocol that will be queried for tile data.
An object that implements the `MLNComputedShapeSourceDataSource` protocol that will be queried for tile data.
*/
@property (nonatomic, weak, nullable) id<MGLComputedShapeSourceDataSource> dataSource;
@property (nonatomic, weak, nullable) id<MLNComputedShapeSourceDataSource> dataSource;
/**
A queue that calls to the data source will be made on.

View File

@@ -1,68 +1,68 @@
#import "MGLComputedShapeSource_Private.h"
#import "MLNComputedShapeSource_Private.h"
#import "MGLMapView_Private.h"
#import "MGLSource_Private.h"
#import "MGLShape_Private.h"
#import "MGLGeometry_Private.h"
#import "MGLShapeCollection.h"
#import "MLNMapView_Private.h"
#import "MLNSource_Private.h"
#import "MLNShape_Private.h"
#import "MLNGeometry_Private.h"
#import "MLNShapeCollection.h"
#include <mbgl/map/map.hpp>
#include <mbgl/style/sources/custom_geometry_source.hpp>
#include <mbgl/tile/tile_id.hpp>
#include <mbgl/util/geojson.hpp>
const MGLExceptionName MGLInvalidDatasourceException = @"MGLInvalidDatasourceException";
const MLNExceptionName MLNInvalidDatasourceException = @"MLNInvalidDatasourceException";
const MGLShapeSourceOption MGLShapeSourceOptionWrapsCoordinates = @"MGLShapeSourceOptionWrapsCoordinates";
const MGLShapeSourceOption MGLShapeSourceOptionClipsCoordinates = @"MGLShapeSourceOptionClipsCoordinates";
const MLNShapeSourceOption MLNShapeSourceOptionWrapsCoordinates = @"MLNShapeSourceOptionWrapsCoordinates";
const MLNShapeSourceOption MLNShapeSourceOptionClipsCoordinates = @"MLNShapeSourceOptionClipsCoordinates";
mbgl::style::CustomGeometrySource::Options MBGLCustomGeometrySourceOptionsFromDictionary(NSDictionary<MGLShapeSourceOption, id> *options) {
mbgl::style::CustomGeometrySource::Options MBGLCustomGeometrySourceOptionsFromDictionary(NSDictionary<MLNShapeSourceOption, id> *options) {
mbgl::style::CustomGeometrySource::Options sourceOptions;
if (NSNumber *value = options[MGLShapeSourceOptionMinimumZoomLevel]) {
if (NSNumber *value = options[MLNShapeSourceOptionMinimumZoomLevel]) {
if (![value isKindOfClass:[NSNumber class]]) {
[NSException raise:NSInvalidArgumentException
format:@"MGLShapeSourceOptionMinimumZoomLevel must be an NSNumber."];
format:@"MLNShapeSourceOptionMinimumZoomLevel must be an NSNumber."];
}
sourceOptions.zoomRange.min = value.integerValue;
}
if (NSNumber *value = options[MGLShapeSourceOptionMaximumZoomLevel]) {
if (NSNumber *value = options[MLNShapeSourceOptionMaximumZoomLevel]) {
if (![value isKindOfClass:[NSNumber class]]) {
[NSException raise:NSInvalidArgumentException
format:@"MGLShapeSourceOptionMaximumZoomLevel must be an NSNumber."];
format:@"MLNShapeSourceOptionMaximumZoomLevel must be an NSNumber."];
}
sourceOptions.zoomRange.max = value.integerValue;
}
if (NSNumber *value = options[MGLShapeSourceOptionBuffer]) {
if (NSNumber *value = options[MLNShapeSourceOptionBuffer]) {
if (![value isKindOfClass:[NSNumber class]]) {
[NSException raise:NSInvalidArgumentException
format:@"MGLShapeSourceOptionBuffer must be an NSNumber."];
format:@"MLNShapeSourceOptionBuffer must be an NSNumber."];
}
sourceOptions.tileOptions.buffer = value.integerValue;
}
if (NSNumber *value = options[MGLShapeSourceOptionSimplificationTolerance]) {
if (NSNumber *value = options[MLNShapeSourceOptionSimplificationTolerance]) {
if (![value isKindOfClass:[NSNumber class]]) {
[NSException raise:NSInvalidArgumentException
format:@"MGLShapeSourceOptionSimplificationTolerance must be an NSNumber."];
format:@"MLNShapeSourceOptionSimplificationTolerance must be an NSNumber."];
}
sourceOptions.tileOptions.tolerance = value.doubleValue;
}
if (NSNumber *value = options[MGLShapeSourceOptionWrapsCoordinates]) {
if (NSNumber *value = options[MLNShapeSourceOptionWrapsCoordinates]) {
if (![value isKindOfClass:[NSNumber class]]) {
[NSException raise:NSInvalidArgumentException
format:@"MGLShapeSourceOptionWrapsCoordinates must be an NSNumber."];
format:@"MLNShapeSourceOptionWrapsCoordinates must be an NSNumber."];
}
sourceOptions.tileOptions.wrap = value.boolValue;
}
if (NSNumber *value = options[MGLShapeSourceOptionClipsCoordinates]) {
if (NSNumber *value = options[MLNShapeSourceOptionClipsCoordinates]) {
if (![value isKindOfClass:[NSNumber class]]) {
[NSException raise:NSInvalidArgumentException
format:@"MGLShapeSourceOptionClipsCoordinates must be an NSNumber."];
format:@"MLNShapeSourceOptionClipsCoordinates must be an NSNumber."];
}
sourceOptions.tileOptions.clip = value.boolValue;
}
@@ -70,7 +70,7 @@ mbgl::style::CustomGeometrySource::Options MBGLCustomGeometrySourceOptionsFromDi
return sourceOptions;
}
@interface MGLComputedShapeSource () {
@interface MLNComputedShapeSource () {
std::unique_ptr<mbgl::style::CustomGeometrySource> _pendingSource;
}
@@ -80,23 +80,23 @@ mbgl::style::CustomGeometrySource::Options MBGLCustomGeometrySourceOptionsFromDi
@end
@interface MGLComputedShapeSourceFetchOperation : NSOperation
@interface MLNComputedShapeSourceFetchOperation : NSOperation
@property (nonatomic, readonly) uint8_t z;
@property (nonatomic, readonly) uint32_t x;
@property (nonatomic, readonly) uint32_t y;
@property (nonatomic, assign) BOOL dataSourceImplementsFeaturesForTile;
@property (nonatomic, assign) BOOL dataSourceImplementsFeaturesForBounds;
@property (nonatomic, weak, nullable) id<MGLComputedShapeSourceDataSource> dataSource;
@property (nonatomic, weak, nullable) id<MLNComputedShapeSourceDataSource> dataSource;
@property (nonatomic, nullable) mbgl::style::CustomGeometrySource *rawSource;
- (instancetype)initForSource:(MGLComputedShapeSource*)source tile:(const mbgl::CanonicalTileID&)tileId;
- (instancetype)initForSource:(MLNComputedShapeSource*)source tile:(const mbgl::CanonicalTileID&)tileId;
@end
@implementation MGLComputedShapeSourceFetchOperation
@implementation MLNComputedShapeSourceFetchOperation
- (instancetype)initForSource:(MGLComputedShapeSource*)source tile:(const mbgl::CanonicalTileID&)tileID {
- (instancetype)initForSource:(MLNComputedShapeSource*)source tile:(const mbgl::CanonicalTileID&)tileID {
self = [super init];
_z = tileID.z;
_x = tileID.x;
@@ -114,7 +114,7 @@ mbgl::style::CustomGeometrySource::Options MBGLCustomGeometrySourceOptionsFromDi
return;
}
NSArray<MGLShape <MGLFeature> *> *data;
NSArray<MLNShape <MLNFeature> *> *data;
if(!self.dataSource) {
data = nil;
} else if(self.dataSourceImplementsFeaturesForTile) {
@@ -124,19 +124,19 @@ mbgl::style::CustomGeometrySource::Options MBGLCustomGeometrySourceOptionsFromDi
} else {
mbgl::CanonicalTileID tileID = mbgl::CanonicalTileID(self.z, self.x, self.y);
mbgl::LatLngBounds tileBounds = mbgl::LatLngBounds(tileID);
data = [self.dataSource featuresInCoordinateBounds:MGLCoordinateBoundsFromLatLngBounds(tileBounds)
data = [self.dataSource featuresInCoordinateBounds:MLNCoordinateBoundsFromLatLngBounds(tileBounds)
zoomLevel:self.z];
}
if(![self isCancelled]) {
mbgl::FeatureCollection featureCollection;
featureCollection.reserve(data.count);
for (MGLShape <MGLFeature> * feature in data) {
if ([feature isMemberOfClass:[MGLShapeCollection class]]) {
for (MLNShape <MLNFeature> * feature in data) {
if ([feature isMemberOfClass:[MLNShapeCollection class]]) {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSLog(@"MGLShapeCollection initialized with MGLFeatures will not retain attributes."
@"Use MGLShapeCollectionFeature to retain attributes instead."
NSLog(@"MLNShapeCollection initialized with MLNFeatures will not retain attributes."
@"Use MLNShapeCollectionFeature to retain attributes instead."
@"This will be logged only once.");
});
}
@@ -157,22 +157,22 @@ mbgl::style::CustomGeometrySource::Options MBGLCustomGeometrySourceOptionsFromDi
@end
@implementation MGLComputedShapeSource
@implementation MLNComputedShapeSource
- (instancetype)initWithIdentifier:(NSString *)identifier options:(NSDictionary<MGLShapeSourceOption, id> *)options {
- (instancetype)initWithIdentifier:(NSString *)identifier options:(NSDictionary<MLNShapeSourceOption, id> *)options {
NSOperationQueue *requestQueue = [[NSOperationQueue alloc] init];
requestQueue.name = [NSString stringWithFormat:@"mgl.MGLComputedShapeSource.%@", identifier];
requestQueue.name = [NSString stringWithFormat:@"mgl.MLNComputedShapeSource.%@", identifier];
requestQueue.qualityOfService = NSQualityOfServiceUtility;
requestQueue.maxConcurrentOperationCount = 4;
auto sourceOptions = MBGLCustomGeometrySourceOptionsFromDictionary(options);
sourceOptions.fetchTileFunction = ^void(const mbgl::CanonicalTileID& tileID) {
NSOperation *operation = [[MGLComputedShapeSourceFetchOperation alloc] initForSource:self tile:tileID];
NSOperation *operation = [[MLNComputedShapeSourceFetchOperation alloc] initForSource:self tile:tileID];
[requestQueue addOperation:operation];
};
sourceOptions.cancelTileFunction = ^void(const mbgl::CanonicalTileID& tileID) {
for (MGLComputedShapeSourceFetchOperation *operation in requestQueue.operations) {
for (MLNComputedShapeSourceFetchOperation *operation in requestQueue.operations) {
if (operation.x == tileID.x && operation.y == tileID.y && operation.z == tileID.z) {
[operation cancel];
}
@@ -187,7 +187,7 @@ mbgl::style::CustomGeometrySource::Options MBGLCustomGeometrySourceOptionsFromDi
return self;
}
- (instancetype)initWithIdentifier:(NSString *)identifier dataSource:(id<MGLComputedShapeSourceDataSource>)dataSource options:(NSDictionary<MGLShapeSourceOption, id> *)options {
- (instancetype)initWithIdentifier:(NSString *)identifier dataSource:(id<MLNComputedShapeSourceDataSource>)dataSource options:(NSDictionary<MLNShapeSourceOption, id> *)options {
if (self = [self initWithIdentifier:identifier options:options]) {
[self setDataSource:dataSource];
}
@@ -198,19 +198,19 @@ mbgl::style::CustomGeometrySource::Options MBGLCustomGeometrySourceOptionsFromDi
[self.requestQueue cancelAllOperations];
}
- (void)setFeatures:(NSArray<MGLShape <MGLFeature> *>*)features inTileAtX:(NSUInteger)x y:(NSUInteger)y zoomLevel:(NSUInteger)zoomLevel {
MGLAssertStyleSourceIsValid();
- (void)setFeatures:(NSArray<MLNShape <MLNFeature> *>*)features inTileAtX:(NSUInteger)x y:(NSUInteger)y zoomLevel:(NSUInteger)zoomLevel {
MLNAssertStyleSourceIsValid();
mbgl::CanonicalTileID tileID = mbgl::CanonicalTileID((uint8_t)zoomLevel, (uint32_t)x, (uint32_t)y);
mbgl::FeatureCollection featureCollection;
featureCollection.reserve(features.count);
for (MGLShape <MGLFeature> * feature in features) {
for (MLNShape <MLNFeature> * feature in features) {
mbgl::GeoJSONFeature geoJsonObject = [feature geoJSONObject].get<mbgl::GeoJSONFeature>();
featureCollection.push_back(geoJsonObject);
if ([feature isMemberOfClass:[MGLShapeCollection class]]) {
if ([feature isMemberOfClass:[MLNShapeCollection class]]) {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSLog(@"MGLShapeCollection initialized with MGLFeatures will not retain attributes."
@"Use MGLShapeCollectionFeature to retain attributes instead."
NSLog(@"MLNShapeCollection initialized with MLNFeatures will not retain attributes."
@"Use MLNShapeCollectionFeature to retain attributes instead."
@"This will be logged only once.");
});
}
@@ -219,30 +219,30 @@ mbgl::style::CustomGeometrySource::Options MBGLCustomGeometrySourceOptionsFromDi
static_cast<mbgl::style::CustomGeometrySource *>(self.rawSource)->setTileData(tileID, geojson);
}
- (void)setDataSource:(id<MGLComputedShapeSourceDataSource>)dataSource {
- (void)setDataSource:(id<MLNComputedShapeSourceDataSource>)dataSource {
[self.requestQueue cancelAllOperations];
// Check which method the datasource implements, to avoid having to check for each tile
self.dataSourceImplementsFeaturesForTile = [dataSource respondsToSelector:@selector(featuresInTileAtX:y:zoomLevel:)];
self.dataSourceImplementsFeaturesForBounds = [dataSource respondsToSelector:@selector(featuresInCoordinateBounds:zoomLevel:)];
if (!self.dataSourceImplementsFeaturesForBounds && !self.dataSourceImplementsFeaturesForTile) {
[NSException raise:MGLInvalidDatasourceException
format:@"Datasource does not implement any MGLComputedShapeSourceDataSource methods"];
[NSException raise:MLNInvalidDatasourceException
format:@"Datasource does not implement any MLNComputedShapeSourceDataSource methods"];
} else if (self.dataSourceImplementsFeaturesForBounds && self.dataSourceImplementsFeaturesForTile) {
[NSException raise:MGLInvalidDatasourceException
format:@"Datasource implements multiple MGLComputedShapeSourceDataSource methods"];
[NSException raise:MLNInvalidDatasourceException
format:@"Datasource implements multiple MLNComputedShapeSourceDataSource methods"];
}
_dataSource = dataSource;
}
- (void) invalidateBounds:(MGLCoordinateBounds)bounds {
MGLAssertStyleSourceIsValid();
((mbgl::style::CustomGeometrySource *)self.rawSource)->invalidateRegion(MGLLatLngBoundsFromCoordinateBounds(bounds));
- (void) invalidateBounds:(MLNCoordinateBounds)bounds {
MLNAssertStyleSourceIsValid();
((mbgl::style::CustomGeometrySource *)self.rawSource)->invalidateRegion(MLNLatLngBoundsFromCoordinateBounds(bounds));
}
- (void) invalidateTileAtX:(NSUInteger)x y:(NSUInteger)y zoomLevel:(NSUInteger)z {
MGLAssertStyleSourceIsValid();
MLNAssertStyleSourceIsValid();
((mbgl::style::CustomGeometrySource *)self.rawSource)->invalidateTile(mbgl::CanonicalTileID(z, (unsigned int)x, (unsigned int)y));
}

View File

@@ -1,12 +1,12 @@
#import "MGLFoundation.h"
#import "MGLTypes.h"
#import "MGLComputedShapeSource.h"
#import "MLNFoundation.h"
#import "MLNTypes.h"
#import "MLNComputedShapeSource.h"
#include <mbgl/style/sources/custom_geometry_source.hpp>
NS_ASSUME_NONNULL_BEGIN
MGL_EXPORT
mbgl::style::CustomGeometrySource::Options MBGLCustomGeometrySourceOptionsFromDictionary(NSDictionary<MGLShapeSourceOption, id> *options);
MLN_EXPORT
mbgl::style::CustomGeometrySource::Options MBGLCustomGeometrySourceOptionsFromDictionary(NSDictionary<MLNShapeSourceOption, id> *options);
NS_ASSUME_NONNULL_END

View File

@@ -1,4 +1,4 @@
#import "MGLShape_Private.h"
#import "MLNShape_Private.h"
#include <mbgl/style/conversion_impl.hpp>

View File

@@ -1,17 +1,17 @@
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#import "MGLFoundation.h"
#import "MLNFoundation.h"
NS_ASSUME_NONNULL_BEGIN
/**
The `MGLCoordinateFormatter` class provides properly formatted descriptions of
The `MLNCoordinateFormatter` class provides properly formatted descriptions of
geographic coordinate pairs. Use this class to create localized coordinate
strings when displaying location information to users.
*/
MGL_EXPORT
@interface MGLCoordinateFormatter : NSFormatter
MLN_EXPORT
@interface MLNCoordinateFormatter : NSFormatter
/**
Determines whether the output may contain minutes of arc when nonzero.
@@ -47,7 +47,7 @@ MGL_EXPORT
- (NSString *)stringFromCoordinate:(CLLocationCoordinate2D)coordinate;
/**
This method is not supported for the `MGLCoordinateFormatter` class.
This method is not supported for the `MLNCoordinateFormatter` class.
*/
- (BOOL)getObjectValue:(out id __nullable * __nullable)obj forString:(NSString *)string errorDescription:(out NSString * __nullable * __nullable)error;

View File

@@ -1,10 +1,10 @@
#import "MGLCoordinateFormatter.h"
#import "MLNCoordinateFormatter.h"
#import "NSBundle+MGLAdditions.h"
#import "NSValue+MGLAdditions.h"
#import "MGLLoggingConfiguration_Private.h"
#import "NSBundle+MLNAdditions.h"
#import "NSValue+MLNAdditions.h"
#import "MLNLoggingConfiguration_Private.h"
@implementation MGLCoordinateFormatter
@implementation MLNCoordinateFormatter
- (instancetype)init {
if (self = [super init]) {
@@ -116,11 +116,11 @@
if (![obj isKindOfClass:[NSValue class]]) {
return nil;
}
return [self stringFromCoordinate:[obj MGLCoordinateValue]];
return [self stringFromCoordinate:[obj MLNCoordinateValue]];
}
- (BOOL)getObjectValue:(out id __nullable * __nullable)obj forString:(NSString *)string errorDescription:(out NSString * __nullable * __nullable)error {
MGLAssert(NO, @"-getObjectValue:forString:errorDescription: has not been implemented");
MLNAssert(NO, @"-getObjectValue:forString:errorDescription: has not been implemented");
return NO;
}

View File

@@ -1,14 +1,14 @@
#import <Foundation/Foundation.h>
#import "MGLFoundation.h"
#import "MLNFoundation.h"
NS_ASSUME_NONNULL_BEGIN
/**
The `MGLDefaultStyle` defines the predefined vendor style
The `MLNDefaultStyle` defines the predefined vendor style
*/
MGL_EXPORT
@interface MGLDefaultStyle : NSObject
MLN_EXPORT
@interface MLNDefaultStyle : NSObject
/**
The style URL

View File

@@ -1,6 +1,6 @@
#import "MGLDefaultStyle.h"
#import "MLNDefaultStyle.h"
@implementation MGLDefaultStyle
@implementation MLNDefaultStyle
@synthesize url;
@synthesize name;

View File

@@ -1,17 +1,17 @@
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#import "MGLFoundation.h"
#import "MLNFoundation.h"
NS_ASSUME_NONNULL_BEGIN
/**
`MGLDistanceFormatter` implements a formatter object meant to be used for
`MLNDistanceFormatter` implements a formatter object meant to be used for
geographic distances. The user’s current locale will be used by default
but it can be overriden by changing the locale property of the numberFormatter.
*/
MGL_EXPORT
@interface MGLDistanceFormatter : NSLengthFormatter
MLN_EXPORT
@interface MLNDistanceFormatter : NSLengthFormatter
/**
Returns a localized formatted string for the provided distance.

View File

@@ -1,9 +1,9 @@
#import "MGLDistanceFormatter.h"
#import "MLNDistanceFormatter.h"
@interface MGLDistanceFormatter()
@interface MLNDistanceFormatter()
@end
@implementation MGLDistanceFormatter
@implementation MLNDistanceFormatter
static const CLLocationDistance METERS_PER_MILE = 1609.344;
static const double YARDS_PER_MILE = 1760.0;

View File

@@ -1,54 +1,54 @@
#import <Foundation/Foundation.h>
#import "MGLFoundation.h"
#import "MGLPolyline.h"
#import "MGLPolygon.h"
#import "MGLPointAnnotation.h"
#import "MGLPointCollection.h"
#import "MGLShapeCollection.h"
#import "MGLCluster.h"
#import "MLNFoundation.h"
#import "MLNPolyline.h"
#import "MLNPolygon.h"
#import "MLNPointAnnotation.h"
#import "MLNPointCollection.h"
#import "MLNShapeCollection.h"
#import "MLNCluster.h"
NS_ASSUME_NONNULL_BEGIN
/**
The `MGLFeature` protocol is used to provide details about geographic features
contained in an `MGLShapeSource` or `MGLVectorTileSource` object. Each concrete
subclass of `MGLShape` in turn has a subclass that conforms to this protocol. A
The `MLNFeature` protocol is used to provide details about geographic features
contained in an `MLNShapeSource` or `MLNVectorTileSource` object. Each concrete
subclass of `MLNShape` in turn has a subclass that conforms to this protocol. A
feature object associates a shape with an optional identifier and attributes.
You can add custom data to display on the map by creating feature objects and
adding them to an `MGLShapeSource` using the
`-[MGLShapeSource initWithIdentifier:shape:options:]` method or
`MGLShapeSource.shape` property.
adding them to an `MLNShapeSource` using the
`-[MLNShapeSource initWithIdentifier:shape:options:]` method or
`MLNShapeSource.shape` property.
In addition to adding data to the map, you can also extract data from the map:
`-[MGLMapView visibleFeaturesAtPoint:]` and related methods return feature
`-[MLNMapView visibleFeaturesAtPoint:]` and related methods return feature
objects that correspond to features in the source. This enables you to inspect
the properties of features in vector tiles loaded by `MGLVectorTileSource`
the properties of features in vector tiles loaded by `MLNVectorTileSource`
objects. You also reuse these feature objects as overlay annotations.
While it is possible to add `MGLFeature`-conforming objects to the map as
annotations using `-[MGLMapView addAnnotations:]` and related methods, doing so
While it is possible to add `MLNFeature`-conforming objects to the map as
annotations using `-[MLNMapView addAnnotations:]` and related methods, doing so
has trade-offs:
- Features added as annotations will not have `identifier` or `attributes`
properties when used with feature querying.
- Features added as annotations become interactive. Taps and selection can be
handled in `-[MGLMapViewDelegate mapView:didSelectAnnotation:]`.
handled in `-[MLNMapViewDelegate mapView:didSelectAnnotation:]`.
*/
@protocol MGLFeature <MGLAnnotation>
@protocol MLNFeature <MLNAnnotation>
/**
An object that uniquely identifies the feature in its containing content
source.
You can configure an `MGLVectorStyleLayer` object to include or exclude a
specific feature in an `MGLShapeSource` or `MGLVectorTileSource`. In the
`MGLVectorStyleLayer.predicate` property, compare the special `$id` attribute
You can configure an `MLNVectorStyleLayer` object to include or exclude a
specific feature in an `MLNShapeSource` or `MLNVectorTileSource`. In the
`MLNVectorStyleLayer.predicate` property, compare the special `$id` attribute
to the feature’s identifier.
In vector tiles loaded by `MGLVectorTileSource` objects, the identifier
In vector tiles loaded by `MLNVectorTileSource` objects, the identifier
corresponds to the
<a href="https://github.com/mapbox/vector-tile-spec/tree/master/2.1#42-features">feature identifier</a>
(`id`). If the source does not specify the feature’s identifier, the value of
@@ -72,10 +72,10 @@ NS_ASSUME_NONNULL_BEGIN
<a href="https://www.mapbox.com/vector-tiles/mapbox-streets/">Mapbox Streets</a>
layer reference.
The identifier should be set before adding the feature to an `MGLShapeSource`
The identifier should be set before adding the feature to an `MLNShapeSource`
object; setting it afterwards has no effect on the map’s contents. While it is
possible to change this value on feature instances obtained from
`-[MGLMapView visibleFeaturesAtPoint:]` and related methods, doing so likewise
`-[MLNMapView visibleFeaturesAtPoint:]` and related methods, doing so likewise
has no effect on the map’s contents.
*/
@property (nonatomic, copy, nullable) id identifier;
@@ -83,32 +83,32 @@ NS_ASSUME_NONNULL_BEGIN
/**
A dictionary of attributes for this feature.
You can configure an `MGLVectorStyleLayer` object to include or exclude a
specific feature in an `MGLShapeSource` or `MGLVectorTileSource`. In the
`MGLVectorStyleLayer.predicate` property, compare a key of the attribute
You can configure an `MLNVectorStyleLayer` object to include or exclude a
specific feature in an `MLNShapeSource` or `MLNVectorTileSource`. In the
`MLNVectorStyleLayer.predicate` property, compare a key of the attribute
dictionary to the value you want to include. For example, if you want an
`MGLLineStyleLayer` object to display only important features, you might assign
`MLNLineStyleLayer` object to display only important features, you might assign
a value above 50 to the important features’ `importance` attribute, then set
`MGLVectorStyleLayer.predicate` to an `NSPredicate` with the format
`MLNVectorStyleLayer.predicate` to an `NSPredicate` with the format
`importance > 50`.
You can also configure many layout and paint attributes of an `MGLStyleLayer`
You can also configure many layout and paint attributes of an `MLNStyleLayer`
object to match the value of an attribute in this dictionary whenever it
renders this feature. For example, if you display features in an
`MGLShapeSource` using an `MGLCircleStyleLayer`, you can assign a `halfway`
`MLNShapeSource` using an `MLNCircleStyleLayer`, you can assign a `halfway`
attribute to each of the source’s features, then set
`MGLCircleStyleLayer.circleRadius` to an expression for the key path `halfway`.
`MLNCircleStyleLayer.circleRadius` to an expression for the key path `halfway`.
The `MGLSymbolStyleLayer.text` and `MGLSymbolStyleLayer.iconImageName`
The `MLNSymbolStyleLayer.text` and `MLNSymbolStyleLayer.iconImageName`
properties allow you to use attributes yet another way. For example, to label
features in an `MGLShapeSource` object by their names, you can assign a `name`
features in an `MLNShapeSource` object by their names, you can assign a `name`
attribute to each of the source’s features, then set
`MGLSymbolStyleLayer.text` to an expression for the constant string value
`MLNSymbolStyleLayer.text` to an expression for the constant string value
`{name}`. See the
<a href="../predicates-and-expressions.html">Predicates and Expressions</a>
guide for more information about expressions.
In vector tiles loaded by `MGLVectorTileSource` objects, the keys and values of
In vector tiles loaded by `MLNVectorTileSource` objects, the keys and values of
each feature’s attribute dictionary are determined by the source. Each
attribute name is a string, while each attribute value may be a null value,
Boolean value, integer, floating-point number, or string. These data types are
@@ -134,19 +134,19 @@ NS_ASSUME_NONNULL_BEGIN
<a href="https://www.mapbox.com/vector-tiles/mapbox-terrain/">Mapbox Terrain</a>
layer references.
When adding a feature to an `MGLShapeSource`, use the same Foundation types
When adding a feature to an `MLNShapeSource`, use the same Foundation types
listed above for each attribute value. In addition to the Foundation types, you
may also set an attribute to an `NSColor` (macOS) or `UIColor` (iOS), which
will be converted into its
<a href="https://maplibre.org/maplibre-gl-js-docs/style-spec/#types-color">CSS string representation</a>
when the feature is added to an `MGLShapeSource`. This can be convenient when
when the feature is added to an `MLNShapeSource`. This can be convenient when
using the attribute to supply a value for a color-typed layout or paint
attribute via a key path expression.
Note that while it is possible to change this value on feature
instances obtained from `-[MGLMapView visibleFeaturesAtPoint:]` and related
instances obtained from `-[MLNMapView visibleFeaturesAtPoint:]` and related
methods, there will be no effect on the map. Setting this value can be useful
when the feature instance is used to initialize an `MGLShapeSource` and that
when the feature instance is used to initialize an `MLNShapeSource` and that
source is added to the map and styled.
*/
@property (nonatomic, copy) NSDictionary<NSString *, id> *attributes;
@@ -161,7 +161,7 @@ NS_ASSUME_NONNULL_BEGIN
/**
Returns a dictionary that can be serialized as a GeoJSON Feature representation
of an instance of an `MGLFeature` subclass.
of an instance of an `MLNFeature` subclass.
The dictionary includes a `geometry` key corresponding to the receiver’s
underlying geometry data, a `properties` key corresponding to the receiver’s
@@ -173,43 +173,43 @@ NS_ASSUME_NONNULL_BEGIN
@end
/**
An `MGLEmptyFeature` object associates an empty shape with an optional
An `MLNEmptyFeature` object associates an empty shape with an optional
identifier and attributes.
*/
MGL_EXPORT
@interface MGLEmptyFeature : MGLShape <MGLFeature>
MLN_EXPORT
@interface MLNEmptyFeature : MLNShape <MLNFeature>
@end
/**
An `MGLPointFeature` object associates a point shape with an optional
An `MLNPointFeature` object associates a point shape with an optional
identifier and attributes.
#### Related examples
See the <a href="https://docs.mapbox.com/ios/maps/examples/runtime-multiple-annotations/">
Dynamically style interactive points</a> example to learn how to initialize
`MGLPointFeature` objects and add them to your map.
`MLNPointFeature` objects and add them to your map.
*/
MGL_EXPORT
@interface MGLPointFeature : MGLPointAnnotation <MGLFeature>
MLN_EXPORT
@interface MLNPointFeature : MLNPointAnnotation <MLNFeature>
@end
/**
An `MGLPointFeatureCluster` object associates a point shape (with an optional
An `MLNPointFeatureCluster` object associates a point shape (with an optional
identifier and attributes) and represents a point cluster.
@see `MGLCluster`
@see `MLNCluster`
#### Related examples
See the <a href="https://docs.mapbox.com/ios/maps/examples/clustering/">
Clustering point data</a> example to learn how to initialize
clusters and add them to your map.
*/
MGL_EXPORT
@interface MGLPointFeatureCluster : MGLPointFeature <MGLCluster>
MLN_EXPORT
@interface MLNPointFeatureCluster : MLNPointFeature <MLNCluster>
@end
/**
An `MGLPolylineFeature` object associates a polyline shape with an optional
An `MLNPolylineFeature` object associates a polyline shape with an optional
identifier and attributes.
A polyline feature is known as a
@@ -219,64 +219,64 @@ MGL_EXPORT
#### Related examples
See the <a href="https://docs.mapbox.com/ios/maps/examples/line-geojson/">
Add a line annotation from GeoJSON</a> example to learn how to initialize an
`MGLPolylineFeature` and add it to an `MGLMapView` object.
`MLNPolylineFeature` and add it to an `MLNMapView` object.
*/
MGL_EXPORT
@interface MGLPolylineFeature : MGLPolyline <MGLFeature>
MLN_EXPORT
@interface MLNPolylineFeature : MLNPolyline <MLNFeature>
@end
/**
An `MGLPolygonFeature` object associates a polygon shape with an optional
An `MLNPolygonFeature` object associates a polygon shape with an optional
identifier and attributes.
*/
MGL_EXPORT
@interface MGLPolygonFeature : MGLPolygon <MGLFeature>
MLN_EXPORT
@interface MLNPolygonFeature : MLNPolygon <MLNFeature>
@end
/**
An `MGLPointCollectionFeature` object associates a point collection with an
An `MLNPointCollectionFeature` object associates a point collection with an
optional identifier and attributes.
A point collection feature is known as a
<a href="https://tools.ietf.org/html/rfc7946#section-3.1.3">MultiPoint</a>
feature in GeoJSON.
*/
MGL_EXPORT
@interface MGLPointCollectionFeature : MGLPointCollection <MGLFeature>
MLN_EXPORT
@interface MLNPointCollectionFeature : MLNPointCollection <MLNFeature>
@end
// https://github.com/mapbox/mapbox-gl-native/issues/7473
@compatibility_alias MGLMultiPointFeature MGLPointCollectionFeature;
@compatibility_alias MLNMultiPointFeature MLNPointCollectionFeature;
/**
An `MGLMultiPolylineFeature` object associates a multipolyline shape with an
An `MLNMultiPolylineFeature` object associates a multipolyline shape with an
optional identifier and attributes.
A multipolyline feature is known as a
<a href="https://tools.ietf.org/html/rfc7946#section-3.1.5">MultiLineString</a>
feature in GeoJSON.
*/
MGL_EXPORT
@interface MGLMultiPolylineFeature : MGLMultiPolyline <MGLFeature>
MLN_EXPORT
@interface MLNMultiPolylineFeature : MLNMultiPolyline <MLNFeature>
@end
/**
An `MGLMultiPolygonFeature` object associates a multipolygon shape with an
An `MLNMultiPolygonFeature` object associates a multipolygon shape with an
optional identifier and attributes.
*/
MGL_EXPORT
@interface MGLMultiPolygonFeature : MGLMultiPolygon <MGLFeature>
MLN_EXPORT
@interface MLNMultiPolygonFeature : MLNMultiPolygon <MLNFeature>
@end
/**
An `MGLShapeCollectionFeature` object associates a shape collection with an
An `MLNShapeCollectionFeature` object associates a shape collection with an
optional identifier and attributes.
`MGLShapeCollectionFeature` is most commonly used to add multiple shapes to a
single `MGLShapeSource`. Configure the appearance of an `MGLSource`’s shape
collection collectively using an `MGLSymbolStyleLayer` object, or use multiple
instances of `MGLCircleStyleLayer`, `MGLFillStyleLayer`, and
`MGLLineStyleLayer` to configure the appearance of each kind of shape inside
`MLNShapeCollectionFeature` is most commonly used to add multiple shapes to a
single `MLNShapeSource`. Configure the appearance of an `MLNSource`’s shape
collection collectively using an `MLNSymbolStyleLayer` object, or use multiple
instances of `MLNCircleStyleLayer`, `MLNFillStyleLayer`, and
`MLNLineStyleLayer` to configure the appearance of each kind of shape inside
the collection.
A shape collection feature is known as a
@@ -286,14 +286,14 @@ MGL_EXPORT
#### Related examples
See the <a href="https://docs.mapbox.com/ios/maps/examples/shape-collection/">
Add multiple shapes from a single shape source</a> example to learn how to
add shape data to your map using an `MGLShapeCollectionFeature` object.
add shape data to your map using an `MLNShapeCollectionFeature` object.
*/
MGL_EXPORT
@interface MGLShapeCollectionFeature : MGLShapeCollection <MGLFeature>
MLN_EXPORT
@interface MLNShapeCollectionFeature : MLNShapeCollection <MLNFeature>
@property (nonatomic, copy, readonly) NSArray<MGLShape<MGLFeature> *> *shapes;
@property (nonatomic, copy, readonly) NSArray<MLNShape<MLNFeature> *> *shapes;
+ (instancetype)shapeCollectionWithShapes:(NSArray<MGLShape<MGLFeature> *> *)shapes;
+ (instancetype)shapeCollectionWithShapes:(NSArray<MLNShape<MLNFeature> *> *)shapes;
@end

View File

@@ -1,46 +1,46 @@
#import "MGLFoundation_Private.h"
#import "MGLFeature_Private.h"
#import "MGLCluster.h"
#import "MLNFoundation_Private.h"
#import "MLNFeature_Private.h"
#import "MLNCluster.h"
#import "MGLPointAnnotation.h"
#import "MGLPolyline.h"
#import "MGLPolygon.h"
#import "MGLValueEvaluator.h"
#import "MLNPointAnnotation.h"
#import "MLNPolyline.h"
#import "MLNPolygon.h"
#import "MLNValueEvaluator.h"
#import "MGLShape_Private.h"
#import "MGLPointCollection_Private.h"
#import "MGLPolyline_Private.h"
#import "MGLPolygon_Private.h"
#import "MLNShape_Private.h"
#import "MLNPointCollection_Private.h"
#import "MLNPolyline_Private.h"
#import "MLNPolygon_Private.h"
#import "NSDictionary+MGLAdditions.h"
#import "NSArray+MGLAdditions.h"
#import "NSExpression+MGLPrivateAdditions.h"
#import "MGLLoggingConfiguration_Private.h"
#import "NSDictionary+MLNAdditions.h"
#import "NSArray+MLNAdditions.h"
#import "NSExpression+MLNPrivateAdditions.h"
#import "MLNLoggingConfiguration_Private.h"
#import <mbgl/util/geometry.hpp>
#import <mbgl/style/conversion/geojson.hpp>
#import <mapbox/feature.hpp>
// Cluster constants
static NSString * const MGLClusterIdentifierKey = @"cluster_id";
static NSString * const MGLClusterCountKey = @"point_count";
const NSUInteger MGLClusterIdentifierInvalid = NSUIntegerMax;
static NSString * const MLNClusterIdentifierKey = @"cluster_id";
static NSString * const MLNClusterCountKey = @"point_count";
const NSUInteger MLNClusterIdentifierInvalid = NSUIntegerMax;
@interface MGLEmptyFeature ()
@interface MLNEmptyFeature ()
@end
@implementation MGLEmptyFeature
@implementation MLNEmptyFeature
@synthesize identifier;
@synthesize attributes = _attributes;
MGL_DEFINE_FEATURE_INIT_WITH_CODER();
MGL_DEFINE_FEATURE_ENCODE();
MGL_DEFINE_FEATURE_IS_EQUAL();
MGL_DEFINE_FEATURE_ATTRIBUTES_GETTER();
MLN_DEFINE_FEATURE_INIT_WITH_CODER();
MLN_DEFINE_FEATURE_ENCODE();
MLN_DEFINE_FEATURE_IS_EQUAL();
MLN_DEFINE_FEATURE_ATTRIBUTES_GETTER();
- (id)attributeForKey:(NSString *)key {
MGLLogDebug(@"Retrieving attributeForKey: %@", key);
MLNLogDebug(@"Retrieving attributeForKey: %@", key);
return self.attributes[key];
}
@@ -62,21 +62,21 @@ MGL_DEFINE_FEATURE_ATTRIBUTES_GETTER();
@end
@interface MGLPointFeature ()
@interface MLNPointFeature ()
@end
@implementation MGLPointFeature
@implementation MLNPointFeature
@synthesize identifier;
@synthesize attributes = _attributes;
MGL_DEFINE_FEATURE_INIT_WITH_CODER();
MGL_DEFINE_FEATURE_ENCODE();
MGL_DEFINE_FEATURE_IS_EQUAL();
MGL_DEFINE_FEATURE_ATTRIBUTES_GETTER();
MLN_DEFINE_FEATURE_INIT_WITH_CODER();
MLN_DEFINE_FEATURE_ENCODE();
MLN_DEFINE_FEATURE_IS_EQUAL();
MLN_DEFINE_FEATURE_ATTRIBUTES_GETTER();
- (id)attributeForKey:(NSString *)key {
MGLLogDebug(@"Retrieving attributeForKey: %@", key);
MLNLogDebug(@"Retrieving attributeForKey: %@", key);
return self.attributes[key];
}
@@ -99,46 +99,46 @@ MGL_DEFINE_FEATURE_ATTRIBUTES_GETTER();
@end
@implementation MGLPointFeatureCluster
@implementation MLNPointFeatureCluster
- (NSUInteger)clusterIdentifier {
NSNumber *clusterNumber = MGL_OBJC_DYNAMIC_CAST([self attributeForKey:MGLClusterIdentifierKey], NSNumber);
MGLAssert(clusterNumber, @"Clusters should have a cluster_id");
NSNumber *clusterNumber = MLN_OBJC_DYNAMIC_CAST([self attributeForKey:MLNClusterIdentifierKey], NSNumber);
MLNAssert(clusterNumber, @"Clusters should have a cluster_id");
if (!clusterNumber) {
return MGLClusterIdentifierInvalid;
return MLNClusterIdentifierInvalid;
}
NSUInteger clusterIdentifier = [clusterNumber unsignedIntegerValue];
MGLAssert(clusterIdentifier <= UINT32_MAX, @"Cluster identifiers are 32bit");
MLNAssert(clusterIdentifier <= UINT32_MAX, @"Cluster identifiers are 32bit");
return clusterIdentifier;
}
- (NSUInteger)clusterPointCount {
NSNumber *count = MGL_OBJC_DYNAMIC_CAST([self attributeForKey:MGLClusterCountKey], NSNumber);
MGLAssert(count, @"Clusters should have a point_count");
NSNumber *count = MLN_OBJC_DYNAMIC_CAST([self attributeForKey:MLNClusterCountKey], NSNumber);
MLNAssert(count, @"Clusters should have a point_count");
return [count unsignedIntegerValue];
}
@end
@interface MGLPolylineFeature ()
@interface MLNPolylineFeature ()
@end
@implementation MGLPolylineFeature
@implementation MLNPolylineFeature
@synthesize identifier;
@synthesize attributes = _attributes;
MGL_DEFINE_FEATURE_INIT_WITH_CODER();
MGL_DEFINE_FEATURE_ENCODE();
MGL_DEFINE_FEATURE_IS_EQUAL();
MGL_DEFINE_FEATURE_ATTRIBUTES_GETTER();
MLN_DEFINE_FEATURE_INIT_WITH_CODER();
MLN_DEFINE_FEATURE_ENCODE();
MLN_DEFINE_FEATURE_IS_EQUAL();
MLN_DEFINE_FEATURE_ATTRIBUTES_GETTER();
- (id)attributeForKey:(NSString *)key {
MGLLogDebug(@"Retrieving attributeForKey: %@", key);
MLNLogDebug(@"Retrieving attributeForKey: %@", key);
return self.attributes[key];
}
@@ -156,27 +156,27 @@ MGL_DEFINE_FEATURE_ATTRIBUTES_GETTER();
NSStringFromClass([self class]), (void *)self,
self.identifier ? [NSString stringWithFormat:@"\"%@\"", self.identifier] : self.identifier,
(unsigned long)[self pointCount],
MGLStringFromCoordinateBounds(self.overlayBounds),
MLNStringFromCoordinateBounds(self.overlayBounds),
self.attributes.count ? self.attributes : @"none"];
}
@end
@interface MGLPolygonFeature ()
@interface MLNPolygonFeature ()
@end
@implementation MGLPolygonFeature
@implementation MLNPolygonFeature
@synthesize identifier;
@synthesize attributes = _attributes;
MGL_DEFINE_FEATURE_INIT_WITH_CODER();
MGL_DEFINE_FEATURE_ENCODE();
MGL_DEFINE_FEATURE_IS_EQUAL();
MGL_DEFINE_FEATURE_ATTRIBUTES_GETTER();
MLN_DEFINE_FEATURE_INIT_WITH_CODER();
MLN_DEFINE_FEATURE_ENCODE();
MLN_DEFINE_FEATURE_IS_EQUAL();
MLN_DEFINE_FEATURE_ATTRIBUTES_GETTER();
- (id)attributeForKey:(NSString *)key {
MGLLogDebug(@"Retrieving attributeForKey: %@", key);
MLNLogDebug(@"Retrieving attributeForKey: %@", key);
return self.attributes[key];
}
@@ -194,27 +194,27 @@ MGL_DEFINE_FEATURE_ATTRIBUTES_GETTER();
NSStringFromClass([self class]), (void *)self,
self.identifier ? [NSString stringWithFormat:@"\"%@\"", self.identifier] : self.identifier,
(unsigned long)[self pointCount],
MGLStringFromCoordinateBounds(self.overlayBounds),
MLNStringFromCoordinateBounds(self.overlayBounds),
self.attributes.count ? self.attributes : @"none"];
}
@end
@interface MGLPointCollectionFeature ()
@interface MLNPointCollectionFeature ()
@end
@implementation MGLPointCollectionFeature
@implementation MLNPointCollectionFeature
@synthesize identifier;
@synthesize attributes = _attributes;
MGL_DEFINE_FEATURE_INIT_WITH_CODER();
MGL_DEFINE_FEATURE_ENCODE();
MGL_DEFINE_FEATURE_IS_EQUAL();
MGL_DEFINE_FEATURE_ATTRIBUTES_GETTER();
MLN_DEFINE_FEATURE_INIT_WITH_CODER();
MLN_DEFINE_FEATURE_ENCODE();
MLN_DEFINE_FEATURE_IS_EQUAL();
MLN_DEFINE_FEATURE_ATTRIBUTES_GETTER();
- (id)attributeForKey:(NSString *)key {
MGLLogDebug(@"Retrieving attributeForKey: %@", key);
MLNLogDebug(@"Retrieving attributeForKey: %@", key);
return self.attributes[key];
}
@@ -228,21 +228,21 @@ MGL_DEFINE_FEATURE_ATTRIBUTES_GETTER();
@end
@interface MGLMultiPolylineFeature ()
@interface MLNMultiPolylineFeature ()
@end
@implementation MGLMultiPolylineFeature
@implementation MLNMultiPolylineFeature
@synthesize identifier;
@synthesize attributes = _attributes;
MGL_DEFINE_FEATURE_INIT_WITH_CODER();
MGL_DEFINE_FEATURE_ENCODE();
MGL_DEFINE_FEATURE_IS_EQUAL();
MGL_DEFINE_FEATURE_ATTRIBUTES_GETTER();
MLN_DEFINE_FEATURE_INIT_WITH_CODER();
MLN_DEFINE_FEATURE_ENCODE();
MLN_DEFINE_FEATURE_IS_EQUAL();
MLN_DEFINE_FEATURE_ATTRIBUTES_GETTER();
- (id)attributeForKey:(NSString *)key {
MGLLogDebug(@"Retrieving attributeForKey: %@", key);
MLNLogDebug(@"Retrieving attributeForKey: %@", key);
return self.attributes[key];
}
@@ -260,27 +260,27 @@ MGL_DEFINE_FEATURE_ATTRIBUTES_GETTER();
NSStringFromClass([self class]), (void *)self,
self.identifier ? [NSString stringWithFormat:@"\"%@\"", self.identifier] : self.identifier,
(unsigned long)self.polylines.count,
MGLStringFromCoordinateBounds(self.overlayBounds),
MLNStringFromCoordinateBounds(self.overlayBounds),
self.attributes.count ? self.attributes : @"none"];
}
@end
@interface MGLMultiPolygonFeature ()
@interface MLNMultiPolygonFeature ()
@end
@implementation MGLMultiPolygonFeature
@implementation MLNMultiPolygonFeature
@synthesize identifier;
@synthesize attributes = _attributes;
MGL_DEFINE_FEATURE_INIT_WITH_CODER();
MGL_DEFINE_FEATURE_ENCODE();
MGL_DEFINE_FEATURE_IS_EQUAL();
MGL_DEFINE_FEATURE_ATTRIBUTES_GETTER();
MLN_DEFINE_FEATURE_INIT_WITH_CODER();
MLN_DEFINE_FEATURE_ENCODE();
MLN_DEFINE_FEATURE_IS_EQUAL();
MLN_DEFINE_FEATURE_ATTRIBUTES_GETTER();
- (id)attributeForKey:(NSString *)key {
MGLLogDebug(@"Retrieving attributeForKey: %@", key);
MLNLogDebug(@"Retrieving attributeForKey: %@", key);
return self.attributes[key];
}
@@ -298,30 +298,30 @@ MGL_DEFINE_FEATURE_ATTRIBUTES_GETTER();
NSStringFromClass([self class]), (void *)self,
self.identifier ? [NSString stringWithFormat:@"\"%@\"", self.identifier] : self.identifier,
(unsigned long)self.polygons.count,
MGLStringFromCoordinateBounds(self.overlayBounds),
MLNStringFromCoordinateBounds(self.overlayBounds),
self.attributes.count ? self.attributes : @"none"];
}
@end
@interface MGLShapeCollectionFeature ()
@interface MLNShapeCollectionFeature ()
@end
@implementation MGLShapeCollectionFeature
@implementation MLNShapeCollectionFeature
@synthesize identifier;
@synthesize attributes = _attributes;
@dynamic shapes;
+ (instancetype)shapeCollectionWithShapes:(NSArray<MGLShape<MGLFeature> *> *)shapes {
+ (instancetype)shapeCollectionWithShapes:(NSArray<MLNShape<MLNFeature> *> *)shapes {
return [super shapeCollectionWithShapes:shapes];
}
MGL_DEFINE_FEATURE_INIT_WITH_CODER();
MGL_DEFINE_FEATURE_ENCODE();
MGL_DEFINE_FEATURE_IS_EQUAL();
MGL_DEFINE_FEATURE_ATTRIBUTES_GETTER();
MLN_DEFINE_FEATURE_INIT_WITH_CODER();
MLN_DEFINE_FEATURE_ENCODE();
MLN_DEFINE_FEATURE_IS_EQUAL();
MLN_DEFINE_FEATURE_ATTRIBUTES_GETTER();
- (id)attributeForKey:(NSString *)key {
return self.attributes[key];
@@ -334,9 +334,9 @@ MGL_DEFINE_FEATURE_ATTRIBUTES_GETTER();
- (mbgl::GeoJSON)geoJSONObject {
mbgl::FeatureCollection featureCollection;
featureCollection.reserve(self.shapes.count);
for (MGLShape <MGLFeature> *feature in self.shapes) {
for (MLNShape <MLNFeature> *feature in self.shapes) {
auto geoJSONObject = feature.geoJSONObject;
MGLAssert(geoJSONObject.is<mbgl::GeoJSONFeature>(), @"Feature collection must only contain features.");
MLNAssert(geoJSONObject.is<mbgl::GeoJSONFeature>(), @"Feature collection must only contain features.");
featureCollection.push_back(geoJSONObject.get<mbgl::GeoJSONFeature>());
}
return featureCollection;
@@ -360,12 +360,12 @@ public:
is_in_feature(isInFeature)
{}
MGLShape * operator()(const mbgl::EmptyGeometry &) const {
return is_in_feature ? [[MGLEmptyFeature alloc] init] : [[MGLShape alloc] init];
MLNShape * operator()(const mbgl::EmptyGeometry &) const {
return is_in_feature ? [[MLNEmptyFeature alloc] init] : [[MLNShape alloc] init];
}
MGLShape * operator()(const mbgl::Point<T> &geometry) const {
Class shapeClass = is_in_feature ? [MGLPointFeature class] : [MGLPointAnnotation class];
MLNShape * operator()(const mbgl::Point<T> &geometry) const {
Class shapeClass = is_in_feature ? [MLNPointFeature class] : [MLNPointAnnotation class];
// If we're dealing with a cluster, we should change the class type.
// This could be generic and build the subclass at runtime if it turns
@@ -376,63 +376,63 @@ public:
auto clusterValue = clusterIt->second;
if (clusterValue.template is<bool>()) {
if (clusterValue.template get<bool>()) {
shapeClass = [MGLPointFeatureCluster class];
shapeClass = [MLNPointFeatureCluster class];
}
}
}
}
MGLPointAnnotation *shape = [[shapeClass alloc] init];
MLNPointAnnotation *shape = [[shapeClass alloc] init];
shape.coordinate = toLocationCoordinate2D(geometry);
return shape;
}
MGLShape * operator()(const mbgl::LineString<T> &geometry) const {
MLNShape * operator()(const mbgl::LineString<T> &geometry) const {
std::vector<CLLocationCoordinate2D> coordinates = toLocationCoordinates2D(geometry);
Class shapeClass = is_in_feature ? [MGLPolylineFeature class] : [MGLPolyline class];
Class shapeClass = is_in_feature ? [MLNPolylineFeature class] : [MLNPolyline class];
return [shapeClass polylineWithCoordinates:&coordinates[0] count:coordinates.size()];
}
MGLShape * operator()(const mbgl::Polygon<T> &geometry) const {
return toShape<MGLPolygon, MGLPolygonFeature>(geometry, is_in_feature);
MLNShape * operator()(const mbgl::Polygon<T> &geometry) const {
return toShape<MLNPolygon, MLNPolygonFeature>(geometry, is_in_feature);
}
MGLShape * operator()(const mbgl::MultiPoint<T> &geometry) const {
MLNShape * operator()(const mbgl::MultiPoint<T> &geometry) const {
std::vector<CLLocationCoordinate2D> coordinates = toLocationCoordinates2D(geometry);
Class shapeClass = is_in_feature ? [MGLPointCollectionFeature class] : [MGLPointCollection class];
Class shapeClass = is_in_feature ? [MLNPointCollectionFeature class] : [MLNPointCollection class];
return [[shapeClass alloc] initWithCoordinates:&coordinates[0] count:coordinates.size()];
}
MGLShape * operator()(const mbgl::MultiLineString<T> &geometry) const {
MLNShape * operator()(const mbgl::MultiLineString<T> &geometry) const {
NSMutableArray *polylines = [NSMutableArray arrayWithCapacity:geometry.size()];
for (auto &lineString : geometry) {
std::vector<CLLocationCoordinate2D> coordinates = toLocationCoordinates2D(lineString);
MGLPolyline *polyline = [MGLPolyline polylineWithCoordinates:&coordinates[0] count:coordinates.size()];
MLNPolyline *polyline = [MLNPolyline polylineWithCoordinates:&coordinates[0] count:coordinates.size()];
[polylines addObject:polyline];
}
Class shapeClass = is_in_feature ? [MGLMultiPolylineFeature class] : [MGLMultiPolyline class];
Class shapeClass = is_in_feature ? [MLNMultiPolylineFeature class] : [MLNMultiPolyline class];
return [shapeClass multiPolylineWithPolylines:polylines];
}
MGLShape * operator()(const mbgl::MultiPolygon<T> &geometry) const {
MLNShape * operator()(const mbgl::MultiPolygon<T> &geometry) const {
NSMutableArray *polygons = [NSMutableArray arrayWithCapacity:geometry.size()];
for (auto &polygon : geometry) {
[polygons addObject:toShape(polygon, false)];
}
Class shapeClass = is_in_feature ? [MGLMultiPolygonFeature class] : [MGLMultiPolygon class];
Class shapeClass = is_in_feature ? [MLNMultiPolygonFeature class] : [MLNMultiPolygon class];
return [shapeClass multiPolygonWithPolygons:polygons];
}
MGLShape * operator()(const mapbox::geometry::geometry_collection<T> &collection) const {
MLNShape * operator()(const mapbox::geometry::geometry_collection<T> &collection) const {
NSMutableArray *shapes = [NSMutableArray arrayWithCapacity:collection.size()];
for (auto &geometry : collection) {
// This is very much like the transformation that happens in MGLFeaturesFromMBGLFeatures(), but these are raw geometries with no associated feature IDs or attributes.
MGLShape *shape = mapbox::geometry::geometry<T>::visit(geometry, *this);
// This is very much like the transformation that happens in MLNFeaturesFromMBGLFeatures(), but these are raw geometries with no associated feature IDs or attributes.
MLNShape *shape = mapbox::geometry::geometry<T>::visit(geometry, *this);
[shapes addObject:shape];
}
Class shapeClass = is_in_feature ? [MGLShapeCollectionFeature class] : [MGLShapeCollection class];
Class shapeClass = is_in_feature ? [MLNShapeCollectionFeature class] : [MLNShapeCollection class];
return [shapeClass shapeCollectionWithShapes:shapes];
}
@@ -448,7 +448,7 @@ private:
return coordinates;
}
template<typename U = MGLPolygon, typename V = MGLPolygonFeature>
template<typename U = MLNPolygon, typename V = MLNPolygonFeature>
static U *toShape(const mbgl::Polygon<T> &geometry, const bool isInFeature) {
auto &linearRing = geometry.front();
std::vector<CLLocationCoordinate2D> coordinates = toLocationCoordinates2D(linearRing);
@@ -458,7 +458,7 @@ private:
for (auto iter = geometry.begin() + 1; iter != geometry.end(); iter++) {
auto &innerRing = *iter;
std::vector<CLLocationCoordinate2D> innerCoordinates = toLocationCoordinates2D(innerRing);
MGLPolygon *innerPolygon = [MGLPolygon polygonWithCoordinates:&innerCoordinates[0] count:innerCoordinates.size()];
MLNPolygon *innerPolygon = [MLNPolygon polygonWithCoordinates:&innerCoordinates[0] count:innerCoordinates.size()];
[innerPolygons addObject:innerPolygon];
}
}
@@ -471,43 +471,43 @@ private:
template <typename T>
class GeoJSONEvaluator {
public:
MGLShape * operator()(const mbgl::Geometry<T> &geometry) const {
MLNShape * operator()(const mbgl::Geometry<T> &geometry) const {
GeometryEvaluator<T> evaluator;
MGLShape *shape = mapbox::geometry::geometry<T>::visit(geometry, evaluator);
MLNShape *shape = mapbox::geometry::geometry<T>::visit(geometry, evaluator);
return shape;
}
MGLShape <MGLFeature> * operator()(const mbgl::GeoJSONFeature &feature) const {
MGLShape <MGLFeature> *shape = (MGLShape <MGLFeature> *)MGLFeatureFromMBGLFeature(feature);
MLNShape <MLNFeature> * operator()(const mbgl::GeoJSONFeature &feature) const {
MLNShape <MLNFeature> *shape = (MLNShape <MLNFeature> *)MLNFeatureFromMBGLFeature(feature);
return shape;
}
MGLShape <MGLFeature> * operator()(const mbgl::FeatureCollection &collection) const {
MLNShape <MLNFeature> * operator()(const mbgl::FeatureCollection &collection) const {
NSMutableArray *shapes = [NSMutableArray arrayWithCapacity:collection.size()];
for (const auto &feature : collection) {
[shapes addObject:MGLFeatureFromMBGLFeature(feature)];
[shapes addObject:MLNFeatureFromMBGLFeature(feature)];
}
return [MGLShapeCollectionFeature shapeCollectionWithShapes:shapes];
return [MLNShapeCollectionFeature shapeCollectionWithShapes:shapes];
}
};
NSArray<MGLShape <MGLFeature> *> *MGLFeaturesFromMBGLFeatures(const std::vector<mbgl::Feature> &features) {
NSArray<MLNShape <MLNFeature> *> *MLNFeaturesFromMBGLFeatures(const std::vector<mbgl::Feature> &features) {
NSMutableArray *shapes = [NSMutableArray arrayWithCapacity:features.size()];
for (const auto &feature : features) {
[shapes addObject:MGLFeatureFromMBGLFeature(static_cast<mbgl::GeoJSONFeature>(feature))];
[shapes addObject:MLNFeatureFromMBGLFeature(static_cast<mbgl::GeoJSONFeature>(feature))];
}
return shapes;
}
NSArray<MGLShape <MGLFeature> *> *MGLFeaturesFromMBGLFeatures(const std::vector<mbgl::GeoJSONFeature> &features) {
NSArray<MLNShape <MLNFeature> *> *MLNFeaturesFromMBGLFeatures(const std::vector<mbgl::GeoJSONFeature> &features) {
NSMutableArray *shapes = [NSMutableArray arrayWithCapacity:features.size()];
for (const auto &feature : features) {
[shapes addObject:MGLFeatureFromMBGLFeature(feature)];
[shapes addObject:MLNFeatureFromMBGLFeature(feature)];
}
return shapes;
}
id <MGLFeature> MGLFeatureFromMBGLFeature(const mbgl::GeoJSONFeature &feature) {
id <MLNFeature> MLNFeatureFromMBGLFeature(const mbgl::GeoJSONFeature &feature) {
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithCapacity:feature.properties.size()];
for (auto &pair : feature.properties) {
auto &value = pair.second;
@@ -515,7 +515,7 @@ id <MGLFeature> MGLFeatureFromMBGLFeature(const mbgl::GeoJSONFeature &feature) {
attributes[@(pair.first.c_str())] = mbgl::Value::visit(value, evaluator);
}
GeometryEvaluator<double> evaluator(&feature.properties, true);
MGLShape <MGLFeature> *shape = (MGLShape <MGLFeature> *)mapbox::geometry::geometry<double>::visit(feature.geometry, evaluator);
MLNShape <MLNFeature> *shape = (MLNShape <MLNFeature> *)mapbox::geometry::geometry<double>::visit(feature.geometry, evaluator);
if (!feature.id.is<mapbox::feature::null_value_t>()) {
shape.identifier = mbgl::FeatureIdentifier::visit(feature.id, ValueEvaluator());
}
@@ -524,9 +524,9 @@ id <MGLFeature> MGLFeatureFromMBGLFeature(const mbgl::GeoJSONFeature &feature) {
return shape;
}
MGLShape* MGLShapeFromGeoJSON(const mapbox::geojson::geojson &geojson) {
MLNShape* MLNShapeFromGeoJSON(const mapbox::geojson::geojson &geojson) {
GeoJSONEvaluator<double> evaluator;
MGLShape *shape = mapbox::geojson::geojson::visit(geojson, evaluator);
MLNShape *shape = mapbox::geojson::geojson::visit(geojson, evaluator);
return shape;
}

View File

@@ -1,6 +1,6 @@
#import "MGLFoundation.h"
#import "MGLFeature.h"
#import "MGLShape.h"
#import "MLNFoundation.h"
#import "MLNFeature.h"
#import "MLNShape.h"
#import <mbgl/util/geo.hpp>
#import <mbgl/util/feature.hpp>
@@ -9,30 +9,30 @@
NS_ASSUME_NONNULL_BEGIN
/**
Returns an array of `MGLFeature` objects converted from the given vector of
Returns an array of `MLNFeature` objects converted from the given vector of
vector tile features.
*/
MGL_EXPORT
NSArray<MGLShape <MGLFeature> *> *MGLFeaturesFromMBGLFeatures(const std::vector<mbgl::Feature> &features);
MLN_EXPORT
NSArray<MLNShape <MLNFeature> *> *MLNFeaturesFromMBGLFeatures(const std::vector<mbgl::Feature> &features);
/**
Returns an array of `MGLFeature` objects converted from the given vector of
Returns an array of `MLNFeature` objects converted from the given vector of
vector tile features.
*/
MGL_EXPORT
NSArray<MGLShape <MGLFeature> *> *MGLFeaturesFromMBGLFeatures(const std::vector<mbgl::GeoJSONFeature> &features);
MLN_EXPORT
NSArray<MLNShape <MLNFeature> *> *MLNFeaturesFromMBGLFeatures(const std::vector<mbgl::GeoJSONFeature> &features);
/**
Returns an `MGLFeature` object converted from the given mbgl::GeoJSONFeature
Returns an `MLNFeature` object converted from the given mbgl::GeoJSONFeature
*/
MGL_EXPORT
id <MGLFeature> MGLFeatureFromMBGLFeature(const mbgl::GeoJSONFeature &feature);
MLN_EXPORT
id <MLNFeature> MLNFeatureFromMBGLFeature(const mbgl::GeoJSONFeature &feature);
/**
Returns an `MGLShape` representing the given geojson. The shape can be
Returns an `MLNShape` representing the given geojson. The shape can be
a feature, a collection of features, or a geometry.
*/
MGLShape* MGLShapeFromGeoJSON(const mapbox::geojson::geojson &geojson);
MLNShape* MLNShapeFromGeoJSON(const mapbox::geojson::geojson &geojson);
/**
Takes an `mbgl::GeoJSONFeature` object, an identifer, and attributes dictionary and
@@ -42,13 +42,13 @@ MGLShape* MGLShapeFromGeoJSON(const mapbox::geojson::geojson &geojson);
mbgl::GeoJSONFeature mbglFeature(mbgl::GeoJSONFeature feature, id identifier, NSDictionary * attributes);
/**
Returns an `NSDictionary` representation of an `MGLFeature`.
Returns an `NSDictionary` representation of an `MLNFeature`.
*/
NSDictionary<NSString *, id> *NSDictionaryFeatureForGeometry(NSDictionary *geometry, NSDictionary *attributes, id identifier);
NS_ASSUME_NONNULL_END
#define MGL_DEFINE_FEATURE_INIT_WITH_CODER() \
#define MLN_DEFINE_FEATURE_INIT_WITH_CODER() \
- (instancetype)initWithCoder:(NSCoder *)decoder { \
if (self = [super initWithCoder:decoder]) { \
NSSet<Class> *identifierClasses = [NSSet setWithArray:@[[NSString class], [NSNumber class]]]; \
@@ -58,14 +58,14 @@ NS_ASSUME_NONNULL_END
return self; \
}
#define MGL_DEFINE_FEATURE_ENCODE() \
#define MLN_DEFINE_FEATURE_ENCODE() \
- (void)encodeWithCoder:(NSCoder *)coder { \
[super encodeWithCoder:coder]; \
[coder encodeObject:identifier forKey:@"identifier"]; \
[coder encodeObject:_attributes forKey:@"attributes"]; \
}
#define MGL_DEFINE_FEATURE_IS_EQUAL() \
#define MLN_DEFINE_FEATURE_IS_EQUAL() \
- (BOOL)isEqual:(id)other { \
if (other == self) return YES; \
if (![other isKindOfClass:[self class]]) return NO; \
@@ -76,7 +76,7 @@ NS_ASSUME_NONNULL_END
return [super hash] + [[self geoJSONDictionary] hash]; \
}
#define MGL_DEFINE_FEATURE_ATTRIBUTES_GETTER() \
#define MLN_DEFINE_FEATURE_ATTRIBUTES_GETTER() \
- (NSDictionary *) attributes { \
if (!_attributes) { \
return @{}; \

View File

@@ -1,24 +1,24 @@
#import <Foundation/Foundation.h>
#import "MGLFoundation.h"
#import "MGLStyleLayer.h"
#import "MLNFoundation.h"
#import "MLNStyleLayer.h"
NS_ASSUME_NONNULL_BEGIN
@class MGLSource;
@class MLNSource;
/**
`MGLForegroundStyleLayer` is an abstract superclass for style layers whose
content is defined by an `MGLSource` object.
`MLNForegroundStyleLayer` is an abstract superclass for style layers whose
content is defined by an `MLNSource` object.
Create instances of `MGLRasterStyleLayer`, `MGLHillshadeStyleLayer`, and the
concrete subclasses of `MGLVectorStyleLayer` in order to use
`MGLForegroundStyleLayer`'s methods. Do not create instances of
`MGLForegroundStyleLayer` directly, and do not create your own subclasses of
Create instances of `MLNRasterStyleLayer`, `MLNHillshadeStyleLayer`, and the
concrete subclasses of `MLNVectorStyleLayer` in order to use
`MLNForegroundStyleLayer`'s methods. Do not create instances of
`MLNForegroundStyleLayer` directly, and do not create your own subclasses of
this class.
*/
MGL_EXPORT
@interface MGLForegroundStyleLayer : MGLStyleLayer
MLN_EXPORT
@interface MLNForegroundStyleLayer : MLNStyleLayer
// MARK: Initializing a Style Layer

View File

@@ -1,11 +1,11 @@
#import "MGLForegroundStyleLayer.h"
#import "MGLStyleLayer_Private.h"
#import "MLNForegroundStyleLayer.h"
#import "MLNStyleLayer_Private.h"
@implementation MGLForegroundStyleLayer
@implementation MLNForegroundStyleLayer
- (NSString *)sourceIdentifier {
[NSException raise:MGLAbstractClassException
format:@"MGLForegroundStyleLayer is an abstract class"];
[NSException raise:MLNAbstractClassException
format:@"MLNForegroundStyleLayer is an abstract class"];
return nil;
}

View File

@@ -0,0 +1,5 @@
#pragma once
#import <Foundation/Foundation.h>
#define MLN_EXPORT __attribute__((visibility ("default")))

View File

@@ -1,6 +1,6 @@
#import "MGLFoundation_Private.h"
#import "MLNFoundation_Private.h"
/// Initializes the run loop shim that lives on the main thread.
void MGLInitializeRunLoop() {
void MLNInitializeRunLoop() {
static mbgl::util::RunLoop runLoop;
}

View File

@@ -1,17 +1,17 @@
#import "MGLFoundation.h"
#import "MLNFoundation.h"
#include <mbgl/util/run_loop.hpp>
void MGLInitializeRunLoop();
void MLNInitializeRunLoop();
/* Using a compound statement (GNU Extension, supported by clang) */
#define MGL_OBJC_DYNAMIC_CAST(object, type) \
#define MLN_OBJC_DYNAMIC_CAST(object, type) \
({ \
__typeof__( object ) temp##__LINE__ = (object); \
(type *)([temp##__LINE__ isKindOfClass:[type class]] ? temp##__LINE__ : nil); \
})
#define MGL_OBJC_DYNAMIC_CAST_AS_PROTOCOL(object, proto) \
#define MLN_OBJC_DYNAMIC_CAST_AS_PROTOCOL(object, proto) \
({ \
__typeof__( object ) temp##__LINE__ = (object); \
(id< proto >)([temp##__LINE__ conformsToProtocol:@protocol( proto )] ? temp##__LINE__ : nil); \

View File

@@ -2,52 +2,52 @@
#import <CoreLocation/CoreLocation.h>
#import <CoreGraphics/CoreGraphics.h>
#import "MGLFoundation.h"
#import "MLNFoundation.h"
NS_ASSUME_NONNULL_BEGIN
/** Defines the area spanned by an `MGLCoordinateBounds`. */
typedef struct __attribute__((objc_boxable)) MGLCoordinateSpan {
/** Latitudes spanned by an `MGLCoordinateBounds`. */
/** Defines the area spanned by an `MLNCoordinateBounds`. */
typedef struct __attribute__((objc_boxable)) MLNCoordinateSpan {
/** Latitudes spanned by an `MLNCoordinateBounds`. */
CLLocationDegrees latitudeDelta;
/** Longitudes spanned by an `MGLCoordinateBounds`. */
/** Longitudes spanned by an `MLNCoordinateBounds`. */
CLLocationDegrees longitudeDelta;
} MGLCoordinateSpan;
} MLNCoordinateSpan;
/* Defines a point on the map in Mercator projection for a specific zoom level. */
typedef struct __attribute__((objc_boxable)) MGLMapPoint {
typedef struct __attribute__((objc_boxable)) MLNMapPoint {
/** X coordinate representing a longitude in Mercator projection. */
CGFloat x;
/** Y coordinate representing a latitide in Mercator projection. */
CGFloat y;
/** Zoom level at which the X and Y coordinates are valid. */
CGFloat zoomLevel;
} MGLMapPoint;
} MLNMapPoint;
/* Defines a 4x4 matrix. */
typedef struct MGLMatrix4 {
typedef struct MLNMatrix4 {
double m00, m01, m02, m03;
double m10, m11, m12, m13;
double m20, m21, m22, m23;
double m30, m31, m32, m33;
} MGLMatrix4;
} MLNMatrix4;
/**
Creates a new `MGLCoordinateSpan` from the given latitudinal and longitudinal
Creates a new `MLNCoordinateSpan` from the given latitudinal and longitudinal
deltas.
*/
NS_INLINE MGLCoordinateSpan MGLCoordinateSpanMake(CLLocationDegrees latitudeDelta, CLLocationDegrees longitudeDelta) {
MGLCoordinateSpan span;
NS_INLINE MLNCoordinateSpan MLNCoordinateSpanMake(CLLocationDegrees latitudeDelta, CLLocationDegrees longitudeDelta) {
MLNCoordinateSpan span;
span.latitudeDelta = latitudeDelta;
span.longitudeDelta = longitudeDelta;
return span;
}
/**
Creates a new `MGLMapPoint` from the given X and Y coordinates, and zoom level.
Creates a new `MLNMapPoint` from the given X and Y coordinates, and zoom level.
*/
NS_INLINE MGLMapPoint MGLMapPointMake(CGFloat x, CGFloat y, CGFloat zoomLevel) {
MGLMapPoint point;
NS_INLINE MLNMapPoint MLNMapPointMake(CGFloat x, CGFloat y, CGFloat zoomLevel) {
MLNMapPoint point;
point.x = x;
point.y = y;
point.zoomLevel = zoomLevel;
@@ -58,29 +58,29 @@ NS_INLINE MGLMapPoint MGLMapPointMake(CGFloat x, CGFloat y, CGFloat zoomLevel) {
Returns `YES` if the two coordinate spans represent the same latitudinal change
and the same longitudinal change.
*/
NS_INLINE BOOL MGLCoordinateSpanEqualToCoordinateSpan(MGLCoordinateSpan span1, MGLCoordinateSpan span2) {
NS_INLINE BOOL MLNCoordinateSpanEqualToCoordinateSpan(MLNCoordinateSpan span1, MLNCoordinateSpan span2) {
return (span1.latitudeDelta == span2.latitudeDelta &&
span1.longitudeDelta == span2.longitudeDelta);
}
/** An area of zero width and zero height. */
FOUNDATION_EXTERN MGL_EXPORT const MGLCoordinateSpan MGLCoordinateSpanZero;
FOUNDATION_EXTERN MLN_EXPORT const MLNCoordinateSpan MLNCoordinateSpanZero;
/** A rectangular area as measured on a two-dimensional map projection. */
typedef struct __attribute__((objc_boxable)) MGLCoordinateBounds {
typedef struct __attribute__((objc_boxable)) MLNCoordinateBounds {
/** Coordinate at the southwest corner. */
CLLocationCoordinate2D sw;
/** Coordinate at the northeast corner. */
CLLocationCoordinate2D ne;
} MGLCoordinateBounds;
} MLNCoordinateBounds;
/**
A quadrilateral area as measured on a two-dimensional map projection.
`MGLCoordinateQuad` differs from `MGLCoordinateBounds` in that it allows
`MLNCoordinateQuad` differs from `MLNCoordinateBounds` in that it allows
representation of non-axis aligned bounds and non-rectangular quadrilaterals.
The coordinates are described in counter clockwise order from top left.
*/
typedef struct MGLCoordinateQuad {
typedef struct MLNCoordinateQuad {
/** Coordinate at the top left corner. */
CLLocationCoordinate2D topLeft;
/** Coordinate at the bottom left corner. */
@@ -89,26 +89,26 @@ typedef struct MGLCoordinateQuad {
CLLocationCoordinate2D bottomRight;
/** Coordinate at the top right corner. */
CLLocationCoordinate2D topRight;
} MGLCoordinateQuad;
} MLNCoordinateQuad;
/**
Creates a new `MGLCoordinateBounds` structure from the given southwest and
Creates a new `MLNCoordinateBounds` structure from the given southwest and
northeast coordinates.
*/
NS_INLINE MGLCoordinateBounds MGLCoordinateBoundsMake(CLLocationCoordinate2D sw, CLLocationCoordinate2D ne) {
MGLCoordinateBounds bounds;
NS_INLINE MLNCoordinateBounds MLNCoordinateBoundsMake(CLLocationCoordinate2D sw, CLLocationCoordinate2D ne) {
MLNCoordinateBounds bounds;
bounds.sw = sw;
bounds.ne = ne;
return bounds;
}
/**
Creates a new `MGLCoordinateQuad` structure from the given top left,
Creates a new `MLNCoordinateQuad` structure from the given top left,
bottom left, bottom right, and top right coordinates.
*/
NS_INLINE MGLCoordinateQuad MGLCoordinateQuadMake(CLLocationCoordinate2D topLeft, CLLocationCoordinate2D bottomLeft, CLLocationCoordinate2D bottomRight, CLLocationCoordinate2D topRight) {
MGLCoordinateQuad quad;
NS_INLINE MLNCoordinateQuad MLNCoordinateQuadMake(CLLocationCoordinate2D topLeft, CLLocationCoordinate2D bottomLeft, CLLocationCoordinate2D bottomRight, CLLocationCoordinate2D topRight) {
MLNCoordinateQuad quad;
quad.topLeft = topLeft;
quad.bottomLeft = bottomLeft;
quad.bottomRight = bottomRight;
@@ -117,12 +117,12 @@ NS_INLINE MGLCoordinateQuad MGLCoordinateQuadMake(CLLocationCoordinate2D topLeft
}
/**
Creates a new `MGLCoordinateQuad` structure from the given `MGLCoordinateBounds`.
Creates a new `MLNCoordinateQuad` structure from the given `MLNCoordinateBounds`.
The returned quad uses the bounds' northeast coordinate as the top right, and the
southwest coordinate at the bottom left.
*/
NS_INLINE MGLCoordinateQuad MGLCoordinateQuadFromCoordinateBounds(MGLCoordinateBounds bounds) {
MGLCoordinateQuad quad;
NS_INLINE MLNCoordinateQuad MLNCoordinateQuadFromCoordinateBounds(MLNCoordinateBounds bounds) {
MLNCoordinateQuad quad;
quad.topLeft = CLLocationCoordinate2DMake(bounds.ne.latitude, bounds.sw.longitude);
quad.bottomLeft = bounds.sw;
quad.bottomRight = CLLocationCoordinate2DMake(bounds.sw.latitude, bounds.ne.longitude);
@@ -131,7 +131,7 @@ NS_INLINE MGLCoordinateQuad MGLCoordinateQuadFromCoordinateBounds(MGLCoordinateB
}
/** Returns `YES` if the two coordinate bounds are equal to each other. */
NS_INLINE BOOL MGLCoordinateBoundsEqualToCoordinateBounds(MGLCoordinateBounds bounds1, MGLCoordinateBounds bounds2) {
NS_INLINE BOOL MLNCoordinateBoundsEqualToCoordinateBounds(MLNCoordinateBounds bounds1, MLNCoordinateBounds bounds2) {
return (bounds1.sw.latitude == bounds2.sw.latitude &&
bounds1.sw.longitude == bounds2.sw.longitude &&
bounds1.ne.latitude == bounds2.ne.latitude &&
@@ -139,7 +139,7 @@ NS_INLINE BOOL MGLCoordinateBoundsEqualToCoordinateBounds(MGLCoordinateBounds bo
}
/** Returns `YES` if the two coordinate bounds intersect. */
NS_INLINE BOOL MGLCoordinateBoundsIntersectsCoordinateBounds(MGLCoordinateBounds bounds1, MGLCoordinateBounds bounds2) {
NS_INLINE BOOL MLNCoordinateBoundsIntersectsCoordinateBounds(MLNCoordinateBounds bounds1, MLNCoordinateBounds bounds2) {
return (bounds1.ne.latitude > bounds2.sw.latitude &&
bounds1.sw.latitude < bounds2.ne.latitude &&
bounds1.ne.longitude > bounds2.sw.longitude &&
@@ -152,10 +152,10 @@ NS_INLINE BOOL MGLCoordinateBoundsIntersectsCoordinateBounds(MGLCoordinateBounds
#### Related examples
See the <a href="https://docs.mapbox.com/ios/maps/examples/constraining-gestures/">
Restrict map panning to an area</a> example to learn how to use
`MGLCoordinateInCoordinateBounds` to determine if a point is within, or
`MLNCoordinateInCoordinateBounds` to determine if a point is within, or
intersects, a given bounding box.
*/
NS_INLINE BOOL MGLCoordinateInCoordinateBounds(CLLocationCoordinate2D coordinate, MGLCoordinateBounds bounds) {
NS_INLINE BOOL MLNCoordinateInCoordinateBounds(CLLocationCoordinate2D coordinate, MLNCoordinateBounds bounds) {
return (coordinate.latitude >= bounds.sw.latitude &&
coordinate.latitude <= bounds.ne.latitude &&
coordinate.longitude >= bounds.sw.longitude &&
@@ -163,8 +163,8 @@ NS_INLINE BOOL MGLCoordinateInCoordinateBounds(CLLocationCoordinate2D coordinate
}
/** Returns the area spanned by the coordinate bounds. */
NS_INLINE MGLCoordinateSpan MGLCoordinateBoundsGetCoordinateSpan(MGLCoordinateBounds bounds) {
return MGLCoordinateSpanMake(bounds.ne.latitude - bounds.sw.latitude,
NS_INLINE MLNCoordinateSpan MLNCoordinateBoundsGetCoordinateSpan(MLNCoordinateBounds bounds) {
return MLNCoordinateSpanMake(bounds.ne.latitude - bounds.sw.latitude,
bounds.ne.longitude - bounds.sw.longitude);
}
@@ -172,8 +172,8 @@ NS_INLINE MGLCoordinateSpan MGLCoordinateBoundsGetCoordinateSpan(MGLCoordinateBo
Returns a coordinate bounds with southwest and northeast coordinates that are
offset from those of the source bounds.
*/
NS_INLINE MGLCoordinateBounds MGLCoordinateBoundsOffset(MGLCoordinateBounds bounds, MGLCoordinateSpan offset) {
MGLCoordinateBounds offsetBounds = bounds;
NS_INLINE MLNCoordinateBounds MLNCoordinateBoundsOffset(MLNCoordinateBounds bounds, MLNCoordinateSpan offset) {
MLNCoordinateBounds offsetBounds = bounds;
offsetBounds.sw.latitude += offset.latitudeDelta;
offsetBounds.sw.longitude += offset.longitudeDelta;
offsetBounds.ne.latitude += offset.latitudeDelta;
@@ -187,20 +187,20 @@ NS_INLINE MGLCoordinateBounds MGLCoordinateBoundsOffset(MGLCoordinateBounds boun
@note A bounds may be empty but have a non-zero coordinate span (e.g., when its
northeast point lies due north of its southwest point).
*/
NS_INLINE BOOL MGLCoordinateBoundsIsEmpty(MGLCoordinateBounds bounds) {
MGLCoordinateSpan span = MGLCoordinateBoundsGetCoordinateSpan(bounds);
NS_INLINE BOOL MLNCoordinateBoundsIsEmpty(MLNCoordinateBounds bounds) {
MLNCoordinateSpan span = MLNCoordinateBoundsGetCoordinateSpan(bounds);
return span.latitudeDelta == 0 || span.longitudeDelta == 0;
}
/** Returns a formatted string for the given coordinate bounds. */
NS_INLINE NSString *MGLStringFromCoordinateBounds(MGLCoordinateBounds bounds) {
NS_INLINE NSString *MLNStringFromCoordinateBounds(MLNCoordinateBounds bounds) {
return [NSString stringWithFormat:@"{ sw = {%.1f, %.1f}, ne = {%.1f, %.1f}}",
bounds.sw.latitude, bounds.sw.longitude,
bounds.ne.latitude, bounds.ne.longitude];
}
/** Returns a formatted string for the given coordinate quad. */
NS_INLINE NSString *MGLStringFromCoordinateQuad(MGLCoordinateQuad quad) {
NS_INLINE NSString *MLNStringFromCoordinateQuad(MLNCoordinateQuad quad) {
return [NSString stringWithFormat:@"{ topleft = {%.1f, %.1f}, bottomleft = {%.1f, %.1f}}, bottomright = {%.1f, %.1f}, topright = {%.1f, %.1f}",
quad.topLeft.latitude, quad.topLeft.longitude,
quad.bottomLeft.latitude, quad.bottomLeft.longitude,
@@ -209,17 +209,17 @@ NS_INLINE NSString *MGLStringFromCoordinateQuad(MGLCoordinateQuad quad) {
}
/** Returns radians, converted from degrees. */
NS_INLINE CGFloat MGLRadiansFromDegrees(CLLocationDegrees degrees) {
NS_INLINE CGFloat MLNRadiansFromDegrees(CLLocationDegrees degrees) {
return (CGFloat)(degrees * M_PI) / 180;
}
/** Returns degrees, converted from radians. */
NS_INLINE CLLocationDegrees MGLDegreesFromRadians(CGFloat radians) {
NS_INLINE CLLocationDegrees MLNDegreesFromRadians(CGFloat radians) {
return radians * 180 / M_PI;
}
/** Returns Mercator projection of a WGS84 coordinate at the specified zoom level. */
FOUNDATION_EXTERN MGL_EXPORT MGLMapPoint MGLMapPointForCoordinate(CLLocationCoordinate2D coordinate, double zoomLevel);
FOUNDATION_EXTERN MLN_EXPORT MLNMapPoint MLNMapPointForCoordinate(CLLocationCoordinate2D coordinate, double zoomLevel);
/** Converts a map zoom level to a camera altitude.
@@ -229,7 +229,7 @@ FOUNDATION_EXTERN MGL_EXPORT MGLMapPoint MGLMapPointForCoordinate(CLLocationCoor
@param latitude The latitude of the point at the center of the viewport.
@param size The size of the viewport.
@return An altitude measured in meters. */
FOUNDATION_EXTERN MGL_EXPORT CLLocationDistance MGLAltitudeForZoomLevel(double zoomLevel, CGFloat pitch, CLLocationDegrees latitude, CGSize size);
FOUNDATION_EXTERN MLN_EXPORT CLLocationDistance MLNAltitudeForZoomLevel(double zoomLevel, CGFloat pitch, CLLocationDegrees latitude, CGSize size);
/** Converts a camera altitude to a map zoom level.
@@ -238,6 +238,6 @@ FOUNDATION_EXTERN MGL_EXPORT CLLocationDistance MGLAltitudeForZoomLevel(double z
@param latitude The latitude of the point at the center of the viewport.
@param size The size of the viewport.
@return A zero-based zoom level. */
FOUNDATION_EXTERN MGL_EXPORT double MGLZoomLevelForAltitude(CLLocationDistance altitude, CGFloat pitch, CLLocationDegrees latitude, CGSize size);
FOUNDATION_EXTERN MLN_EXPORT double MLNZoomLevelForAltitude(CLLocationDistance altitude, CGFloat pitch, CLLocationDegrees latitude, CGSize size);
NS_ASSUME_NONNULL_END

View File

@@ -1,6 +1,6 @@
#import "MGLGeometry_Private.h"
#import "MLNGeometry_Private.h"
#import "MGLFoundation.h"
#import "MLNFoundation.h"
#import <mbgl/util/projection.hpp>
@@ -14,11 +14,11 @@
TransformState::getProjMatrix() has a variable vertical field of view that
defaults to 2 arctan ⅓ rad ≈ 36.9° but MapKit uses a vertical field of view of 30°.
flyTo() assumes a field of view of 2 arctan ½ rad. */
const CLLocationDegrees MGLAngularFieldOfView = 30;
const CLLocationDegrees MLNAngularFieldOfView = 30;
const MGLCoordinateSpan MGLCoordinateSpanZero = {0, 0};
const MLNCoordinateSpan MLNCoordinateSpanZero = {0, 0};
CGRect MGLExtendRect(CGRect rect, CGPoint point) {
CGRect MLNExtendRect(CGRect rect, CGPoint point) {
if (point.x < rect.origin.x) {
rect.size.width += rect.origin.x - point.x;
rect.origin.x = point.x;
@@ -36,7 +36,7 @@ CGRect MGLExtendRect(CGRect rect, CGPoint point) {
return rect;
}
mbgl::LatLng MGLLatLngFromLocationCoordinate2D(CLLocationCoordinate2D coordinate) {
mbgl::LatLng MLNLatLngFromLocationCoordinate2D(CLLocationCoordinate2D coordinate) {
try {
return mbgl::LatLng(coordinate.latitude, coordinate.longitude);
} catch (std::domain_error &error) {
@@ -45,58 +45,58 @@ mbgl::LatLng MGLLatLngFromLocationCoordinate2D(CLLocationCoordinate2D coordinate
}
}
CLLocationDistance MGLAltitudeForZoomLevel(double zoomLevel, CGFloat pitch, CLLocationDegrees latitude, CGSize size) {
CLLocationDistance MLNAltitudeForZoomLevel(double zoomLevel, CGFloat pitch, CLLocationDegrees latitude, CGSize size) {
CLLocationDistance metersPerPixel = mbgl::Projection::getMetersPerPixelAtLatitude(latitude, zoomLevel);
CLLocationDistance metersTall = metersPerPixel * size.height;
CLLocationDistance altitude = metersTall / 2 / std::tan(MGLRadiansFromDegrees(MGLAngularFieldOfView) / 2.);
return altitude * std::sin(M_PI_2 - MGLRadiansFromDegrees(pitch)) / std::sin(M_PI_2);
CLLocationDistance altitude = metersTall / 2 / std::tan(MLNRadiansFromDegrees(MLNAngularFieldOfView) / 2.);
return altitude * std::sin(M_PI_2 - MLNRadiansFromDegrees(pitch)) / std::sin(M_PI_2);
}
double MGLZoomLevelForAltitude(CLLocationDistance altitude, CGFloat pitch, CLLocationDegrees latitude, CGSize size) {
CLLocationDistance eyeAltitude = altitude / std::sin(M_PI_2 - MGLRadiansFromDegrees(pitch)) * std::sin(M_PI_2);
CLLocationDistance metersTall = eyeAltitude * 2 * std::tan(MGLRadiansFromDegrees(MGLAngularFieldOfView) / 2.);
double MLNZoomLevelForAltitude(CLLocationDistance altitude, CGFloat pitch, CLLocationDegrees latitude, CGSize size) {
CLLocationDistance eyeAltitude = altitude / std::sin(M_PI_2 - MLNRadiansFromDegrees(pitch)) * std::sin(M_PI_2);
CLLocationDistance metersTall = eyeAltitude * 2 * std::tan(MLNRadiansFromDegrees(MLNAngularFieldOfView) / 2.);
CLLocationDistance metersPerPixel = metersTall / size.height;
CGFloat mapPixelWidthAtZoom = std::cos(MGLRadiansFromDegrees(latitude)) * mbgl::util::M2PI * mbgl::util::EARTH_RADIUS_M / metersPerPixel;
CGFloat mapPixelWidthAtZoom = std::cos(MLNRadiansFromDegrees(latitude)) * mbgl::util::M2PI * mbgl::util::EARTH_RADIUS_M / metersPerPixel;
return ::log2(mapPixelWidthAtZoom / mbgl::util::tileSize_D);
}
MGLRadianDistance MGLDistanceBetweenRadianCoordinates(MGLRadianCoordinate2D from, MGLRadianCoordinate2D to) {
MLNRadianDistance MLNDistanceBetweenRadianCoordinates(MLNRadianCoordinate2D from, MLNRadianCoordinate2D to) {
double a = pow(sin((to.latitude - from.latitude) / 2), 2)
+ pow(sin((to.longitude - from.longitude) / 2), 2) * cos(from.latitude) * cos(to.latitude);
return 2 * atan2(sqrt(a), sqrt(1 - a));
}
MGLRadianDirection MGLRadianCoordinatesDirection(MGLRadianCoordinate2D from, MGLRadianCoordinate2D to) {
MLNRadianDirection MLNRadianCoordinatesDirection(MLNRadianCoordinate2D from, MLNRadianCoordinate2D to) {
double a = sin(to.longitude - from.longitude) * cos(to.latitude);
double b = cos(from.latitude) * sin(to.latitude)
- sin(from.latitude) * cos(to.latitude) * cos(to.longitude - from.longitude);
return atan2(a, b);
}
MGLRadianCoordinate2D MGLRadianCoordinateAtDistanceFacingDirection(MGLRadianCoordinate2D coordinate,
MGLRadianDistance distance,
MGLRadianDirection direction) {
MLNRadianCoordinate2D MLNRadianCoordinateAtDistanceFacingDirection(MLNRadianCoordinate2D coordinate,
MLNRadianDistance distance,
MLNRadianDirection direction) {
double otherLatitude = asin(sin(coordinate.latitude) * cos(distance)
+ cos(coordinate.latitude) * sin(distance) * cos(direction));
double otherLongitude = coordinate.longitude + atan2(sin(direction) * sin(distance) * cos(coordinate.latitude),
cos(distance) - sin(coordinate.latitude) * sin(otherLatitude));
return MGLRadianCoordinate2DMake(otherLatitude, otherLongitude);
return MLNRadianCoordinate2DMake(otherLatitude, otherLongitude);
}
CLLocationDirection MGLDirectionBetweenCoordinates(CLLocationCoordinate2D firstCoordinate, CLLocationCoordinate2D secondCoordinate) {
CLLocationDirection MLNDirectionBetweenCoordinates(CLLocationCoordinate2D firstCoordinate, CLLocationCoordinate2D secondCoordinate) {
// Ported from https://github.com/mapbox/turf-swift/blob/857e2e8060678ef4a7a9169d4971b0788fdffc37/Turf/Turf.swift#L23-L31
MGLRadianCoordinate2D firstRadianCoordinate = MGLRadianCoordinateFromLocationCoordinate(firstCoordinate);
MGLRadianCoordinate2D secondRadianCoordinate = MGLRadianCoordinateFromLocationCoordinate(secondCoordinate);
MLNRadianCoordinate2D firstRadianCoordinate = MLNRadianCoordinateFromLocationCoordinate(firstCoordinate);
MLNRadianCoordinate2D secondRadianCoordinate = MLNRadianCoordinateFromLocationCoordinate(secondCoordinate);
CGFloat a = sin(secondRadianCoordinate.longitude - firstRadianCoordinate.longitude) * cos(secondRadianCoordinate.latitude);
CGFloat b = (cos(firstRadianCoordinate.latitude) * sin(secondRadianCoordinate.latitude)
- sin(firstRadianCoordinate.latitude) * cos(secondRadianCoordinate.latitude) * cos(secondRadianCoordinate.longitude - firstRadianCoordinate.longitude));
MGLRadianDirection radianDirection = atan2(a, b);
MLNRadianDirection radianDirection = atan2(a, b);
return radianDirection * 180 / M_PI;
}
CGPoint MGLPointRounded(CGPoint point) {
CGPoint MLNPointRounded(CGPoint point) {
#if TARGET_OS_IPHONE || TARGET_OS_SIMULATOR
CGFloat scaleFactor = [UIScreen mainScreen].nativeScale;
#elif TARGET_OS_MAC
@@ -105,13 +105,13 @@ CGPoint MGLPointRounded(CGPoint point) {
return CGPointMake(round(point.x * scaleFactor) / scaleFactor, round(point.y * scaleFactor) / scaleFactor);
}
MGLMapPoint MGLMapPointForCoordinate(CLLocationCoordinate2D coordinate, double zoomLevel) {
mbgl::Point<double> projectedCoordinate = mbgl::Projection::project(MGLLatLngFromLocationCoordinate2D(coordinate), std::pow(2.0, zoomLevel));
return MGLMapPointMake(projectedCoordinate.x, projectedCoordinate.y, zoomLevel);
MLNMapPoint MLNMapPointForCoordinate(CLLocationCoordinate2D coordinate, double zoomLevel) {
mbgl::Point<double> projectedCoordinate = mbgl::Projection::project(MLNLatLngFromLocationCoordinate2D(coordinate), std::pow(2.0, zoomLevel));
return MLNMapPointMake(projectedCoordinate.x, projectedCoordinate.y, zoomLevel);
}
MGLMatrix4 MGLMatrix4Make(std::array<double, 16> array) {
MGLMatrix4 mat4 = {
MLNMatrix4 MLNMatrix4Make(std::array<double, 16> array) {
MLNMatrix4 mat4 = {
.m00 = array[0], .m01 = array[1], .m02 = array[2], .m03 = array[3],
.m10 = array[4], .m11 = array[5], .m12 = array[6], .m13 = array[7],
.m20 = array[8], .m21 = array[9], .m22 = array[10], .m23 = array[11],

View File

@@ -0,0 +1,156 @@
#import "MLNGeometry.h"
#import <TargetConditionals.h>
#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#endif
#import <mbgl/util/geo.hpp>
#import <mbgl/util/geometry.hpp>
#import <array>
typedef double MLNLocationRadians;
typedef double MLNRadianDistance;
typedef double MLNRadianDirection;
/** Defines the coordinate by a `MLNRadianCoordinate2D`. */
typedef struct MLNRadianCoordinate2D {
MLNLocationRadians latitude;
MLNLocationRadians longitude;
} MLNRadianCoordinate2D;
/**
Creates a new `MLNRadianCoordinate2D` from the given latitudinal and longitudinal.
*/
NS_INLINE MLNRadianCoordinate2D MLNRadianCoordinate2DMake(MLNLocationRadians latitude, MLNLocationRadians longitude) {
MLNRadianCoordinate2D radianCoordinate;
radianCoordinate.latitude = latitude;
radianCoordinate.longitude = longitude;
return radianCoordinate;
}
/// Returns the smallest rectangle that contains both the given rectangle and
/// the given point.
CGRect MLNExtendRect(CGRect rect, CGPoint point);
#if TARGET_OS_IPHONE
NS_INLINE NSString *MLNStringFromSize(CGSize size) {
return NSStringFromCGSize(size);
}
#else
NS_INLINE NSString *MLNStringFromSize(NSSize size) {
return NSStringFromSize(size);
}
#endif
NS_INLINE NSString *MLNStringFromCLLocationCoordinate2D(CLLocationCoordinate2D coordinate) {
return [NSString stringWithFormat:@"(lat: %f, lon: %f)", coordinate.latitude, coordinate.longitude];
}
mbgl::LatLng MLNLatLngFromLocationCoordinate2D(CLLocationCoordinate2D coordinate);
NS_INLINE mbgl::Point<double> MLNPointFromLocationCoordinate2D(CLLocationCoordinate2D coordinate) {
return mbgl::Point<double>(coordinate.longitude, coordinate.latitude);
}
NS_INLINE CLLocationCoordinate2D MLNLocationCoordinate2DFromPoint(mbgl::Point<double> point) {
return CLLocationCoordinate2DMake(point.y, point.x);
}
NS_INLINE CLLocationCoordinate2D MLNLocationCoordinate2DFromLatLng(mbgl::LatLng latLng) {
return CLLocationCoordinate2DMake(latLng.latitude(), latLng.longitude());
}
NS_INLINE MLNCoordinateBounds MLNCoordinateBoundsFromLatLngBounds(mbgl::LatLngBounds latLngBounds) {
return MLNCoordinateBoundsMake(MLNLocationCoordinate2DFromLatLng(latLngBounds.southwest()),
MLNLocationCoordinate2DFromLatLng(latLngBounds.northeast()));
}
NS_INLINE mbgl::LatLngBounds MLNLatLngBoundsFromCoordinateBounds(MLNCoordinateBounds coordinateBounds) {
return mbgl::LatLngBounds::hull(MLNLatLngFromLocationCoordinate2D(coordinateBounds.sw),
MLNLatLngFromLocationCoordinate2D(coordinateBounds.ne));
}
NS_INLINE std::array<mbgl::LatLng, 4> MLNLatLngArrayFromCoordinateQuad(MLNCoordinateQuad quad) {
return { MLNLatLngFromLocationCoordinate2D(quad.topLeft),
MLNLatLngFromLocationCoordinate2D(quad.topRight),
MLNLatLngFromLocationCoordinate2D(quad.bottomRight),
MLNLatLngFromLocationCoordinate2D(quad.bottomLeft) };
}
NS_INLINE MLNCoordinateQuad MLNCoordinateQuadFromLatLngArray(std::array<mbgl::LatLng, 4> quad) {
return { MLNLocationCoordinate2DFromLatLng(quad[0]),
MLNLocationCoordinate2DFromLatLng(quad[3]),
MLNLocationCoordinate2DFromLatLng(quad[2]),
MLNLocationCoordinate2DFromLatLng(quad[1]) };
}
/**
YES if the coordinate is valid or NO if it is not.
Considers extended coordinates.
*/
NS_INLINE BOOL MLNLocationCoordinate2DIsValid(CLLocationCoordinate2D coordinate) {
return (coordinate.latitude <= 90.0 &&
coordinate.latitude >= -90.0 &&
coordinate.longitude <= 360.0 &&
coordinate.longitude >= -360.0);
}
#if TARGET_OS_IPHONE
#define MLNEdgeInsets UIEdgeInsets
#define MLNEdgeInsetsMake UIEdgeInsetsMake
#else
#define MLNEdgeInsets NSEdgeInsets
#define MLNEdgeInsetsMake NSEdgeInsetsMake
#endif
NS_INLINE mbgl::EdgeInsets MLNEdgeInsetsFromNSEdgeInsets(MLNEdgeInsets insets) {
return { insets.top, insets.left, insets.bottom, insets.right };
}
NS_INLINE MLNEdgeInsets NSEdgeInsetsFromMLNEdgeInsets(const mbgl::EdgeInsets& insets) {
return MLNEdgeInsetsMake(insets.top(), insets.left(), insets.bottom(), insets.right());
}
/// Returns the combination of two edge insets.
NS_INLINE MLNEdgeInsets MLNEdgeInsetsInsetEdgeInset(MLNEdgeInsets base, MLNEdgeInsets inset) {
return MLNEdgeInsetsMake(base.top + inset.top,
base.left + inset.left,
base.bottom + inset.bottom,
base.right + inset.right);
}
/** Returns MLNRadianCoordinate2D, converted from CLLocationCoordinate2D. */
NS_INLINE MLNRadianCoordinate2D MLNRadianCoordinateFromLocationCoordinate(CLLocationCoordinate2D locationCoordinate) {
return MLNRadianCoordinate2DMake(MLNRadiansFromDegrees(locationCoordinate.latitude),
MLNRadiansFromDegrees(locationCoordinate.longitude));
}
/**
Returns the distance in radians given two coordinates.
*/
MLNRadianDistance MLNDistanceBetweenRadianCoordinates(MLNRadianCoordinate2D from, MLNRadianCoordinate2D to);
/**
Returns direction in radians given two coordinates.
*/
MLNRadianDirection MLNRadianCoordinatesDirection(MLNRadianCoordinate2D from, MLNRadianCoordinate2D to);
/**
Returns a coordinate at a given distance and direction away from coordinate.
*/
MLNRadianCoordinate2D MLNRadianCoordinateAtDistanceFacingDirection(MLNRadianCoordinate2D coordinate,
MLNRadianDistance distance,
MLNRadianDirection direction);
/**
Returns the direction from one coordinate to another.
*/
CLLocationDirection MLNDirectionBetweenCoordinates(CLLocationCoordinate2D firstCoordinate, CLLocationCoordinate2D secondCoordinate);
/**
Returns a point with coordinates rounded to the nearest logical pixel.
*/
CGPoint MLNPointRounded(CGPoint point);
MLNMatrix4 MLNMatrix4Make(std::array<double, 16> mat);

View File

@@ -1,54 +1,54 @@
#import "MGLSource.h"
#import "MLNSource.h"
#import "MGLFoundation.h"
#import "MGLTypes.h"
#import "MGLGeometry.h"
#import "MLNFoundation.h"
#import "MLNTypes.h"
#import "MLNGeometry.h"
NS_ASSUME_NONNULL_BEGIN
MGL_EXPORT
MLN_EXPORT
/**
`MGLImageSource` is a content source that is used for a georeferenced raster
`MLNImageSource` is a content source that is used for a georeferenced raster
image to be shown on the map. The georeferenced image scales and rotates as the
user zooms and rotates the map. Images may also be used as icons or patterns
in a style layer. To register an image for use as an icon or pattern,
use the `-[MGLStyle setImage:forName:]` method. To configure a point
annotation’s image, use the `MGLAnnotationImage` class.
use the `-[MLNStyle setImage:forName:]` method. To configure a point
annotation’s image, use the `MLNAnnotationImage` class.
The geographic location of the raster image content, supplied with
`MGLCoordinateQuad`, can be non-axis aligned.
`MGLImageSource` supports raster content from `NSURL`, `NSImage` (macOS), or
`MLNCoordinateQuad`, can be non-axis aligned.
`MLNImageSource` supports raster content from `NSURL`, `NSImage` (macOS), or
`UIImage` (iOS).
An image source is added to an `MGLStyle` object along with one or more
`MGLRasterStyleLayer` objects. Use a raster style layer to control the
An image source is added to an `MLNStyle` object along with one or more
`MLNRasterStyleLayer` objects. Use a raster style layer to control the
appearance of content supplied by the image source.
Each
<a href="https://www.mapbox.com/mapbox-gl-style-spec/#sources-image"><code>image</code></a>
source defined by the style JSON file is represented at runtime by an
`MGLImageSource` object that you can use to initialize new style layers. You
`MLNImageSource` object that you can use to initialize new style layers. You
can also add and remove sources dynamically using methods such as
`-[MGLStyle addSource:]` and `-[MGLStyle sourceWithIdentifier:]`.
`-[MLNStyle addSource:]` and `-[MLNStyle sourceWithIdentifier:]`.
### Example
```swift
let coordinates = MGLCoordinateQuad(
let coordinates = MLNCoordinateQuad(
topLeft: CLLocationCoordinate2D(latitude: 46.437, longitude: -80.425),
bottomLeft: CLLocationCoordinate2D(latitude: 37.936, longitude: -80.425),
bottomRight: CLLocationCoordinate2D(latitude: 37.936, longitude: -71.516),
topRight: CLLocationCoordinate2D(latitude: 46.437, longitude: -71.516))
let source = MGLImageSource(identifier: "radar", coordinateQuad: coordinates, url: URL(string: "https://maplibre.org/maplibre-gl-js-docs/assets/radar.gif")!)
let source = MLNImageSource(identifier: "radar", coordinateQuad: coordinates, url: URL(string: "https://maplibre.org/maplibre-gl-js-docs/assets/radar.gif")!)
mapView.style?.addSource(source)
```
#### Related examples
See the <a href="https://docs.mapbox.com/ios/maps/examples/image-source/">
Add an image</a> example to learn how to add an image to your map using
`MGLImageSource`.
`MLNImageSource`.
*/
MGL_EXPORT
@interface MGLImageSource : MGLSource
MLN_EXPORT
@interface MLNImageSource : MLNSource
// MARK: Initializing a Source
@@ -61,7 +61,7 @@ MGL_EXPORT
current application’s resource bundle.
@return An initialized shape source.
*/
- (instancetype)initWithIdentifier:(NSString *)identifier coordinateQuad:(MGLCoordinateQuad)coordinateQuad URL:(NSURL *)url;
- (instancetype)initWithIdentifier:(NSString *)identifier coordinateQuad:(MLNCoordinateQuad)coordinateQuad URL:(NSURL *)url;
/**
Returns a georeferenced image source with an identifier, coordinates and an image.
@@ -71,7 +71,7 @@ MGL_EXPORT
@param image The image to display for the source.
@return An initialized shape source.
*/
- (instancetype)initWithIdentifier:(NSString *)identifier coordinateQuad:(MGLCoordinateQuad)coordinateQuad image:(MGLImage *)image;
- (instancetype)initWithIdentifier:(NSString *)identifier coordinateQuad:(MLNCoordinateQuad)coordinateQuad image:(MLNImage *)image;
// MARK: Accessing a Source’s Content
@@ -88,12 +88,12 @@ MGL_EXPORT
If the receiver was initialized using `-initWithIdentifier:coordinateQuad:URL:` or if the `URL` property is set, this property is set to `nil`.
*/
@property (nonatomic, retain, nullable)MGLImage *image;
@property (nonatomic, retain, nullable)MLNImage *image;
/**
The coordinates at which the corners of the source image will be placed.
*/
@property (nonatomic) MGLCoordinateQuad coordinates;
@property (nonatomic) MLNCoordinateQuad coordinates;
@end
NS_ASSUME_NONNULL_END

View File

@@ -1,44 +1,44 @@
#import "MGLImageSource.h"
#import "MLNImageSource.h"
#import "MGLGeometry_Private.h"
#import "MGLLoggingConfiguration_Private.h"
#import "MGLSource_Private.h"
#import "MGLTileSource_Private.h"
#import "NSURL+MGLAdditions.h"
#import "MLNGeometry_Private.h"
#import "MLNLoggingConfiguration_Private.h"
#import "MLNSource_Private.h"
#import "MLNTileSource_Private.h"
#import "NSURL+MLNAdditions.h"
#if TARGET_OS_IPHONE
#import "UIImage+MGLAdditions.h"
#import "UIImage+MLNAdditions.h"
#else
#import "NSImage+MGLAdditions.h"
#import "NSImage+MLNAdditions.h"
#endif
#include <mbgl/style/sources/image_source.hpp>
#include <mbgl/util/premultiply.hpp>
@interface MGLImageSource ()
- (instancetype)initWithIdentifier:(NSString *)identifier coordinateQuad:(MGLCoordinateQuad)coordinateQuad NS_DESIGNATED_INITIALIZER;
@interface MLNImageSource ()
- (instancetype)initWithIdentifier:(NSString *)identifier coordinateQuad:(MLNCoordinateQuad)coordinateQuad NS_DESIGNATED_INITIALIZER;
@property (nonatomic, readonly) mbgl::style::ImageSource *rawSource;
@end
@implementation MGLImageSource
@implementation MLNImageSource
- (instancetype)initWithIdentifier:(NSString *)identifier coordinateQuad:(MGLCoordinateQuad)coordinateQuad {
- (instancetype)initWithIdentifier:(NSString *)identifier coordinateQuad:(MLNCoordinateQuad)coordinateQuad {
const auto coordsArray = MGLLatLngArrayFromCoordinateQuad(coordinateQuad);
const auto coordsArray = MLNLatLngArrayFromCoordinateQuad(coordinateQuad);
auto source = std::make_unique<mbgl::style::ImageSource>(identifier.UTF8String, coordsArray);
return self = [super initWithPendingSource:std::move(source)];
}
- (instancetype)initWithIdentifier:(NSString *)identifier coordinateQuad:(MGLCoordinateQuad)coordinateQuad URL:(NSURL *)url {
- (instancetype)initWithIdentifier:(NSString *)identifier coordinateQuad:(MLNCoordinateQuad)coordinateQuad URL:(NSURL *)url {
self = [self initWithIdentifier:identifier coordinateQuad: coordinateQuad];
self.URL = url;
return self;
}
- (instancetype)initWithIdentifier:(NSString *)identifier coordinateQuad:(MGLCoordinateQuad)coordinateQuad image:(MGLImage *)image {
- (instancetype)initWithIdentifier:(NSString *)identifier coordinateQuad:(MLNCoordinateQuad)coordinateQuad image:(MLNImage *)image {
self = [self initWithIdentifier:identifier coordinateQuad: coordinateQuad];
self.image = image;
@@ -46,13 +46,13 @@
}
- (NSURL *)URL {
MGLAssertStyleSourceIsValid();
MLNAssertStyleSourceIsValid();
auto url = self.rawSource->getURL();
return url ? [NSURL URLWithString:@(url->c_str())] : nil;
}
- (void)setURL:(NSURL *)url {
MGLAssertStyleSourceIsValid();
MLNAssertStyleSourceIsValid();
if (url) {
self.rawSource->setURL(url.mgl_URLByStandardizingScheme.absoluteString.UTF8String);
_image = nil;
@@ -61,8 +61,8 @@
}
}
- (void)setImage:(MGLImage *)image {
MGLAssertStyleSourceIsValid();
- (void)setImage:(MLNImage *)image {
MLNAssertStyleSourceIsValid();
if (image != nullptr) {
self.rawSource->setImage(image.mgl_premultipliedImage);
} else {
@@ -71,21 +71,21 @@
_image = image;
}
- (MGLCoordinateQuad)coordinates {
MGLAssertStyleSourceIsValid();
return MGLCoordinateQuadFromLatLngArray(self.rawSource->getCoordinates());
- (MLNCoordinateQuad)coordinates {
MLNAssertStyleSourceIsValid();
return MLNCoordinateQuadFromLatLngArray(self.rawSource->getCoordinates());
}
- (void)setCoordinates: (MGLCoordinateQuad)coordinateQuad {
MGLAssertStyleSourceIsValid();
self.rawSource->setCoordinates(MGLLatLngArrayFromCoordinateQuad(coordinateQuad));
- (void)setCoordinates: (MLNCoordinateQuad)coordinateQuad {
MLNAssertStyleSourceIsValid();
self.rawSource->setCoordinates(MLNLatLngArrayFromCoordinateQuad(coordinateQuad));
}
- (NSString *)description {
if (self.rawSource) {
return [NSString stringWithFormat:@"<%@: %p; identifier = %@; coordinates = %@; URL = %@; image = %@>",
NSStringFromClass([self class]), (void *)self, self.identifier,
MGLStringFromCoordinateQuad(self.coordinates),
MLNStringFromCoordinateQuad(self.coordinates),
self.URL,
self.image];
}
@@ -101,7 +101,7 @@
- (NSString *)attributionHTMLString {
if (!self.rawSource) {
MGLAssert(0, @"Source with identifier `%@` was invalidated after a style change", self.identifier);
MLNAssert(0, @"Source with identifier `%@` was invalidated after a style change", self.identifier);
return nil;
}

View File

@@ -8,8 +8,8 @@
#import <CoreLocation/CoreLocation.h>
#import "MGLFoundation.h"
#import "MGLStyleValue.h"
#import "MLNFoundation.h"
#import "MLNStyleValue.h"
NS_ASSUME_NONNULL_BEGIN
@@ -18,12 +18,12 @@ NS_ASSUME_NONNULL_BEGIN
/**
<%- propertyDoc(property.name, property, type, 'enum').wrap(80, 1) %>
*/
typedef NS_ENUM(NSUInteger, MGLLight<%- camelize(property.name) %>) {
typedef NS_ENUM(NSUInteger, MLNLight<%- camelize(property.name) %>) {
<% for (const value in property.values) { -%>
/**
<%- propertyDoc(property.name, property.values[value], type, 'enum').wrap(80, 4+1) %>
*/
MGLLightAnchor<%- camelize(value) %>,
MLNLightAnchor<%- camelize(value) %>,
<% } -%>
};
<% } -%>
@@ -33,28 +33,28 @@ typedef NS_ENUM(NSUInteger, MGLLight<%- camelize(property.name) %>) {
A structure containing information about the position of the light source
relative to lit geometries.
*/
typedef struct __attribute__((objc_boxable)) MGLSphericalPosition {
typedef struct __attribute__((objc_boxable)) MLNSphericalPosition {
/** Distance from the center of the base of an object to its light. */
CGFloat radial;
/** Position of the light relative to 0° (0° when `MGLLight.anchor` is set to viewport corresponds
to the top of the viewport, or 0° when `MGLLight.anchor` is set to map corresponds to due north,
/** Position of the light relative to 0° (0° when `MLNLight.anchor` is set to viewport corresponds
to the top of the viewport, or 0° when `MLNLight.anchor` is set to map corresponds to due north,
and degrees proceed clockwise). */
CLLocationDirection azimuthal;
/** Indicates the height of the light (from 0°, directly above, to 180°, directly below). */
CLLocationDirection polar;
} MGLSphericalPosition;
} MLNSphericalPosition;
/**
Creates a new `MGLSphericalPosition` from the given radial, azimuthal, polar.
Creates a new `MLNSphericalPosition` from the given radial, azimuthal, polar.
@param radial The radial coordinate.
@param azimuthal The azimuthal angle.
@param polar The polar angle.
@return Returns a `MGLSphericalPosition` struct containing the position attributes.
@return Returns a `MLNSphericalPosition` struct containing the position attributes.
*/
NS_INLINE MGLSphericalPosition MGLSphericalPositionMake(CGFloat radial, CLLocationDirection azimuthal, CLLocationDirection polar) {
MGLSphericalPosition position;
NS_INLINE MLNSphericalPosition MLNSphericalPositionMake(CGFloat radial, CLLocationDirection azimuthal, CLLocationDirection polar) {
MLNSphericalPosition position;
position.radial = radial;
position.azimuthal = azimuthal;
position.polar = polar;
@@ -65,8 +65,8 @@ NS_INLINE MGLSphericalPosition MGLSphericalPositionMake(CGFloat radial, CLLocati
/**
<%- doc.wrap(80, 1) %>
*/
MGL_EXPORT
@interface MGLLight : NSObject
MLN_EXPORT
@interface MLNLight : NSObject
<% if (properties.length) { -%>
<% for (const property of properties) { -%>
@@ -90,7 +90,7 @@ MGL_EXPORT
This property corresponds to the `<%- originalPropertyName(property) %>-transition` property in the style JSON file format.
*/
@property (nonatomic) MGLTransition <%- camelizeWithLeadingLowercase(property.name) %>Transition;
@property (nonatomic) MLNTransition <%- camelizeWithLeadingLowercase(property.name) %>Transition;
<% } -%>
<% if (property.original) { -%>

View File

@@ -5,23 +5,23 @@
// Edit platform/darwin/scripts/generate-style-code.js, then run `make darwin-style-code`.
// test
#import "MGLLight.h"
#import "MLNLight.h"
#import "MGLTypes.h"
#import "MGLStyleValue_Private.h"
#import "NSValue+MGLAdditions.h"
#import "MGLLoggingConfiguration_Private.h"
#import "MLNTypes.h"
#import "MLNStyleValue_Private.h"
#import "NSValue+MLNAdditions.h"
#import "MLNLoggingConfiguration_Private.h"
#import <mbgl/style/light.hpp>
#import <mbgl/style/types.hpp>
namespace mbgl {
MBGL_DEFINE_ENUM(MGLLightAnchor, {
MBGL_DEFINE_ENUM(MLNLightAnchor, {
<% for (const property of properties) { -%>
<% if (property.type == "enum") { -%>
<% for (const value in property.values) { -%>
{ MGLLightAnchor<%- camelize(value) %>, "<%- value %>" },
{ MLNLightAnchor<%- camelize(value) %>, "<%- value %>" },
<% } -%>
<% } -%>
<% } -%>
@@ -29,16 +29,16 @@ namespace mbgl {
}
@interface MGLLight()
@interface MLNLight()
@end
@implementation MGLLight
@implementation MLNLight
- (instancetype)initWithMBGLLight:(const mbgl::style::Light *)mbglLight
{
if (self = [super init]) {
MGLLogInfo(@"Initializing %@.", NSStringFromClass([self class]));
MLNLogInfo(@"Initializing %@.", NSStringFromClass([self class]));
<% if (properties.length) { -%>
<% for (const property of properties) { -%>
<% if (property.type == "enum") { -%>
@@ -46,26 +46,26 @@ namespace mbgl {
NSExpression *<%- camelizeWithLeadingLowercase(property.name) -%>Expression;
if (<%- camelizeWithLeadingLowercase(property.name) -%>.isUndefined()) {
mbgl::style::PropertyValue<mbgl::style::Light<%- camelize(property.name) -%>Type> default<%- camelize(property.name) -%> = mbglLight->getDefault<%- camelize(property.name) -%>();
<%- camelizeWithLeadingLowercase(property.name) -%>Expression = MGLStyleValueTransformer<mbgl::style::LightAnchorType, NSValue *, mbgl::style::Light<%- camelize(property.name) -%>Type, MGLLight<%- camelize(property.name) -%>>().toExpression(default<%- camelize(property.name) -%>);
<%- camelizeWithLeadingLowercase(property.name) -%>Expression = MLNStyleValueTransformer<mbgl::style::LightAnchorType, NSValue *, mbgl::style::Light<%- camelize(property.name) -%>Type, MLNLight<%- camelize(property.name) -%>>().toExpression(default<%- camelize(property.name) -%>);
} else {
<%- camelizeWithLeadingLowercase(property.name) -%>Expression = MGLStyleValueTransformer<mbgl::style::Light<%- camelize(property.name) -%>Type, NSValue *, mbgl::style::Light<%- camelize(property.name) -%>Type, MGLLight<%- camelize(property.name) -%>>().toExpression(<%- camelizeWithLeadingLowercase(property.name) -%>);
<%- camelizeWithLeadingLowercase(property.name) -%>Expression = MLNStyleValueTransformer<mbgl::style::Light<%- camelize(property.name) -%>Type, NSValue *, mbgl::style::Light<%- camelize(property.name) -%>Type, MLNLight<%- camelize(property.name) -%>>().toExpression(<%- camelizeWithLeadingLowercase(property.name) -%>);
}
_<%- camelizeWithLeadingLowercase(property.name) -%> = <%- camelizeWithLeadingLowercase(property.name) -%>Expression;
<% if (property.transition) { -%>
_<%- camelizeWithLeadingLowercase(property.name) -%>Transition = MGLTransitionFromOptions(mbglLight->get<%- camelize(property.name) -%>Transition());
_<%- camelizeWithLeadingLowercase(property.name) -%>Transition = MLNTransitionFromOptions(mbglLight->get<%- camelize(property.name) -%>Transition());
<% } -%>
<% } else {-%>
auto <%- camelizeWithLeadingLowercase(property.name) -%>Value = mbglLight->get<%- camelize(property.name) -%>();
if (<%- camelizeWithLeadingLowercase(property.name) -%>Value.isUndefined()) {
_<%- camelizeWithLeadingLowercase(property.name) -%> = MGLStyleValueTransformer<<%- valueTransformerArguments(property).join(', ') %>>().toExpression(mbglLight->getDefault<%- camelize(property.name) -%>());
_<%- camelizeWithLeadingLowercase(property.name) -%> = MLNStyleValueTransformer<<%- valueTransformerArguments(property).join(', ') %>>().toExpression(mbglLight->getDefault<%- camelize(property.name) -%>());
} else {
_<%- camelizeWithLeadingLowercase(property.name) -%> = MGLStyleValueTransformer<<%- valueTransformerArguments(property).join(', ') %>>().toExpression(<%- camelizeWithLeadingLowercase(property.name) -%>Value);
_<%- camelizeWithLeadingLowercase(property.name) -%> = MLNStyleValueTransformer<<%- valueTransformerArguments(property).join(', ') %>>().toExpression(<%- camelizeWithLeadingLowercase(property.name) -%>Value);
}
<% if (property.transition) { -%>
_<%- camelizeWithLeadingLowercase(property.name) -%>Transition = MGLTransitionFromOptions(mbglLight->get<%- camelize(property.name) -%>Transition());
_<%- camelizeWithLeadingLowercase(property.name) -%>Transition = MLNTransitionFromOptions(mbglLight->get<%- camelize(property.name) -%>Transition());
<% } -%>
<% } -%>
<% } -%>
@@ -81,16 +81,16 @@ namespace mbgl {
<% if (properties.length) { -%>
<% for (const property of properties) { -%>
<% if (property.type == "enum") { -%>
auto <%- camelizeWithLeadingLowercase(property.name) -%> = MGLStyleValueTransformer<mbgl::style::Light<%- camelize(property.name) -%>Type, NSValue *, mbgl::style::Light<%- camelize(property.name) -%>Type, MGLLight<%- camelize(property.name) -%>>().toPropertyValue<mbgl::style::PropertyValue<<%- valueTransformerArguments(property)[0] %>>>(self.<%- camelizeWithLeadingLowercase(property.name) -%>, false);
auto <%- camelizeWithLeadingLowercase(property.name) -%> = MLNStyleValueTransformer<mbgl::style::Light<%- camelize(property.name) -%>Type, NSValue *, mbgl::style::Light<%- camelize(property.name) -%>Type, MLNLight<%- camelize(property.name) -%>>().toPropertyValue<mbgl::style::PropertyValue<<%- valueTransformerArguments(property)[0] %>>>(self.<%- camelizeWithLeadingLowercase(property.name) -%>, false);
mbglLight.set<%- camelize(property.name) -%>(<%- camelizeWithLeadingLowercase(property.name) -%>);
<% } else {-%>
auto <%- camelizeWithLeadingLowercase(property.name) -%> = MGLStyleValueTransformer<<%- valueTransformerArguments(property).join(', ') %>>().toPropertyValue<mbgl::style::PropertyValue<<%- valueTransformerArguments(property)[0] %>>>(self.<%- camelizeWithLeadingLowercase(property.name) -%>, false);
auto <%- camelizeWithLeadingLowercase(property.name) -%> = MLNStyleValueTransformer<<%- valueTransformerArguments(property).join(', ') %>>().toPropertyValue<mbgl::style::PropertyValue<<%- valueTransformerArguments(property)[0] %>>>(self.<%- camelizeWithLeadingLowercase(property.name) -%>, false);
mbglLight.set<%- camelize(property.name) -%>(<%- camelizeWithLeadingLowercase(property.name) -%>);
<% } -%>
<% if (property.transition) { -%>
mbglLight.set<%- camelize(property.name) -%>Transition(MGLOptionsFromTransition(self.<%- camelizeWithLeadingLowercase(property.name) -%>Transition));
mbglLight.set<%- camelize(property.name) -%>Transition(MLNOptionsFromTransition(self.<%- camelizeWithLeadingLowercase(property.name) -%>Transition));
<% } -%>
<% } -%>
@@ -104,13 +104,13 @@ namespace mbgl {
<% for (const property of properties) { -%>
- (void)set<%- camelize(property.name) %>:(NSExpression *)<%- objCName(property) %> {
MGLLogDebug(@"Setting <%- objCName(property) %>: %@", <%- objCName(property) %>);
MLNLogDebug(@"Setting <%- objCName(property) %>: %@", <%- objCName(property) %>);
_<%- objCName(property) %> = <%- objCName(property) %>;
}
<% if (property["transition"]) { -%>
- (void)set<%- camelize(property.name) %>Transition:(MGLTransition)transition {
MGLLogDebug(@"Setting <%- objCName(property) %>Transition: %@", MGLStringFromMGLTransition(transition));
- (void)set<%- camelize(property.name) %>Transition:(MLNTransition)transition {
MLNLogDebug(@"Setting <%- objCName(property) %>Transition: %@", MLNStringFromMLNTransition(transition));
_<%- objCName(property) %>Transition = transition;
}
<% } -%>

View File

@@ -1,6 +1,6 @@
#import <Foundation/Foundation.h>
#import "MGLLight.h"
#import "MLNLight.h"
namespace mbgl {
namespace style {
@@ -8,15 +8,15 @@ namespace mbgl {
}
}
@interface MGLLight (Private)
@interface MLNLight (Private)
/**
Initializes and returns a `MGLLight` associated with a style's light.
Initializes and returns a `MLNLight` associated with a style's light.
*/
- (instancetype)initWithMBGLLight:(const mbgl::style::Light *)mbglLight;
/**
Returns an `mbgl::style::Light` representation of the `MGLLight`.
Returns an `mbgl::style::Light` representation of the `MLNLight`.
*/
- (mbgl::style::Light)mbglLight;

View File

@@ -3,20 +3,20 @@
NS_ASSUME_NONNULL_BEGIN
@protocol MGLLocationManagerDelegate;
@protocol MLNLocationManagerDelegate;
/**
The `MGLLocationManager` protocol defines a set of methods that a class must
implement in order to serve as the location manager of an `MGLMapView`. A location
The `MLNLocationManager` protocol defines a set of methods that a class must
implement in order to serve as the location manager of an `MLNMapView`. A location
manager is responsible for notifying the map view about location-related events,
such as a change in the user’s location. This protocol is similar to the
Core Location framework’s `CLLocationManager` class, but your implementation
does not need to be based on `CLLocationManager`.
To receive location updates from an object that conforms to the `MGLLocationManager`
protocol, use the optional methods available in the `MGLLocationManagerDelegate` protocol.
To receive location updates from an object that conforms to the `MLNLocationManager`
protocol, use the optional methods available in the `MLNLocationManagerDelegate` protocol.
*/
@protocol MGLLocationManager <NSObject>
@protocol MLNLocationManager <NSObject>
@optional
@@ -26,7 +26,7 @@ NS_ASSUME_NONNULL_BEGIN
Specifies the minimum distance (measured in meters) a device must move horizontally
before a location update is generated.
The default value of this property is `kCLDistanceFilterNone` when `MGLMapView` uses its
The default value of this property is `kCLDistanceFilterNone` when `MLNMapView` uses its
default location manager.
@see `CLLocationManager.distanceFilter`
@@ -42,7 +42,7 @@ NS_ASSUME_NONNULL_BEGIN
/**
Specifies the accuracy of the location data.
The default value is `kCLLocationAccuracyBest` when `MGLMapView` uses its
The default value is `kCLLocationAccuracyBest` when `MLNMapView` uses its
default location manager.
@note Determining a location with greater accuracy requires more time and more power.
@@ -63,8 +63,8 @@ NS_ASSUME_NONNULL_BEGIN
Specifies the level of location accuracy the Maps SDK has permission to use.
@note If the value of this property is `CLAccuracyAuthorizationFullAccuracy`, you can set the
`MGLLocationManager.desiredAccuracy` property to any value. If the value is `CLAccuracyAuthorizationReducedAccuracy`,
setting `MGLLocationManager.desiredAccuracy` to a value other than` kCLLocationAccuracyReduced` has no effect on
`MLNLocationManager.desiredAccuracy` property to any value. If the value is `CLAccuracyAuthorizationReducedAccuracy`,
setting `MLNLocationManager.desiredAccuracy` to a value other than` kCLLocationAccuracyReduced` has no effect on
the location information.
*/
- (CLAccuracyAuthorization)accuracyAuthorization API_AVAILABLE(ios(14));
@@ -76,7 +76,7 @@ NS_ASSUME_NONNULL_BEGIN
The location manager uses this property as a cue to determine when location updates
may be automatically paused.
The default value is `CLActivityTypeOther` when `MGLMapView` uses its
The default value is `CLActivityTypeOther` when `MLNMapView` uses its
default location manager.
@see `CLLocationManager.activityType`
@@ -106,10 +106,10 @@ NS_ASSUME_NONNULL_BEGIN
/**
The delegate to receive location updates.
Do not set the location manager’s delegate yourself. `MGLMapView` sets this property
after the location manager becomes `MGLMapView`’s location manager.
Do not set the location manager’s delegate yourself. `MLNMapView` sets this property
after the location manager becomes `MLNMapView`’s location manager.
*/
@property (nonatomic, weak) id<MGLLocationManagerDelegate> delegate;
@property (nonatomic, weak) id<MLNLocationManagerDelegate> delegate;
// MARK: Requesting Authorization for Location Services
@@ -168,11 +168,11 @@ NS_ASSUME_NONNULL_BEGIN
@end
/**
The `MGLLocationManagerDelegate` protocol defines a set of methods that respond
to location updates from an `MGLLocationManager` object that is serving as the
location manager of an `MGLMapView`.
The `MLNLocationManagerDelegate` protocol defines a set of methods that respond
to location updates from an `MLNLocationManager` object that is serving as the
location manager of an `MLNMapView`.
*/
@protocol MGLLocationManagerDelegate <NSObject>
@protocol MLNLocationManagerDelegate <NSObject>
// MARK: Responding to Location Updates
@@ -182,10 +182,10 @@ NS_ASSUME_NONNULL_BEGIN
@param manager The location manager reporting the update.
@param locations An array of `CLLocation` objects in chronological order,
with the last object representing the most recent location. This array
contains multiple `CLLocation` objects when `MGLMapView` uses its
contains multiple `CLLocation` objects when `MLNMapView` uses its
default location manager.
*/
- (void)locationManager:(id<MGLLocationManager>)manager
- (void)locationManager:(id<MLNLocationManager>)manager
didUpdateLocations:(NSArray<CLLocation *> *)locations;
// MARK: Responding to Heading Updates
@@ -196,7 +196,7 @@ NS_ASSUME_NONNULL_BEGIN
@param manager The location manager reporting the update.
@param newHeading The new heading update.
*/
- (void)locationManager:(id<MGLLocationManager>)manager
- (void)locationManager:(id<MLNLocationManager>)manager
didUpdateHeading:(CLHeading *)newHeading;
/**
@@ -204,7 +204,7 @@ NS_ASSUME_NONNULL_BEGIN
@param manager The location manager reporting the calibration.
*/
- (BOOL)locationManagerShouldDisplayHeadingCalibration:(id<MGLLocationManager>)manager;
- (BOOL)locationManagerShouldDisplayHeadingCalibration:(id<MLNLocationManager>)manager;
// MARK: Responding to Location Updates Errors
@@ -216,7 +216,7 @@ NS_ASSUME_NONNULL_BEGIN
@param error An error object containing the error code that indicates
why the location manager failed.
*/
- (void)locationManager:(id<MGLLocationManager>)manager
- (void)locationManager:(id<MLNLocationManager>)manager
didFailWithError:(nonnull NSError *)error;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 140000
/**
@@ -224,7 +224,7 @@ NS_ASSUME_NONNULL_BEGIN
@param manager The location manager reporting the change.
*/
- (void)locationManagerDidChangeAuthorization:(id<MGLLocationManager>)manager;
- (void)locationManagerDidChangeAuthorization:(id<MLNLocationManager>)manager;
#endif
@optional

View File

@@ -1,12 +1,12 @@
#import "MGLLocationManager_Private.h"
#import "MLNLocationManager_Private.h"
@interface MGLCLLocationManager()<CLLocationManagerDelegate>
@interface MLNCLLocationManager()<CLLocationManagerDelegate>
@property (nonatomic) CLLocationManager *locationManager;
@end
@implementation MGLCLLocationManager
@implementation MLNCLLocationManager
- (instancetype)init
{

View File

@@ -0,0 +1,5 @@
#import "MLNLocationManager.h"
@interface MLNCLLocationManager : NSObject<MLNLocationManager>
@end

View File

@@ -1,11 +1,11 @@
#import <Foundation/Foundation.h>
#import "MGLFoundation.h"
#import "MLNFoundation.h"
#ifndef MGL_LOGGING_DISABLED
#ifndef MGL_LOGGING_ENABLE_DEBUG
#ifndef MLN_LOGGING_DISABLED
#ifndef MLN_LOGGING_ENABLE_DEBUG
#ifndef NDEBUG
#define MGL_LOGGING_ENABLE_DEBUG 1
#define MLN_LOGGING_ENABLE_DEBUG 1
#endif
#endif
@@ -14,58 +14,58 @@ NS_ASSUME_NONNULL_BEGIN
/**
Constants indicating the message's logging level.
*/
typedef NS_ENUM(NSInteger, MGLLoggingLevel) {
typedef NS_ENUM(NSInteger, MLNLoggingLevel) {
/**
None-level won't print any messages.
*/
MGLLoggingLevelNone = 0,
MLNLoggingLevelNone = 0,
/**
Fault-level messages contain system-level error information.
*/
MGLLoggingLevelFault,
MLNLoggingLevelFault,
/**
Error-level messages contain information that is intended to aid in process-level
errors.
*/
MGLLoggingLevelError,
MLNLoggingLevelError,
/**
Warning-level messages contain warning information for potential risks.
*/
MGLLoggingLevelWarning,
MLNLoggingLevelWarning,
/**
Info-level messages contain information that may be helpful for flow tracing
but is not essential.
*/
MGLLoggingLevelInfo,
MLNLoggingLevelInfo,
/**
Debug-level messages contain information that may be helpful for troubleshooting
specific problems.
*/
#if MGL_LOGGING_ENABLE_DEBUG
MGLLoggingLevelDebug,
#if MLN_LOGGING_ENABLE_DEBUG
MLNLoggingLevelDebug,
#endif
/**
Verbose-level will print all messages.
*/
MGLLoggingLevelVerbose,
MLNLoggingLevelVerbose,
};
/**
A block to be called once `loggingLevel` is set to a higher value than `MGLLoggingLevelNone`.
A block to be called once `loggingLevel` is set to a higher value than `MLNLoggingLevelNone`.
@param loggingLevel The message logging level.
@param filePath The description of the file and method for the calling message.
@param line The line where the message is logged.
@param message The logging message.
*/
typedef void (^MGLLoggingBlockHandler)(MGLLoggingLevel loggingLevel, NSString *filePath, NSUInteger line, NSString *message);
typedef void (^MLNLoggingBlockHandler)(MLNLoggingLevel loggingLevel, NSString *filePath, NSUInteger line, NSString *message);
/**
The `MGLLoggingConfiguration` object provides a global way to set this SDK logging levels
The `MLNLoggingConfiguration` object provides a global way to set this SDK logging levels
and logging handler.
*/
MGL_EXPORT
@interface MGLLoggingConfiguration : NSObject
MLN_EXPORT
@interface MLNLoggingConfiguration : NSObject
/**
The handler this SDK uses to log messages.
@@ -75,23 +75,23 @@ MGL_EXPORT
The default handler uses `os_log` and `NSLog` for iOS 10+ and iOS < 10 respectively.
*/
@property (nonatomic, copy, null_resettable) MGLLoggingBlockHandler handler;
@property (nonatomic, copy, null_resettable) MLNLoggingBlockHandler handler;
/**
The logging level.
The default value is `MGLLoggingLevelNone`.
The default value is `MLNLoggingLevelNone`.
Setting this property includes logging levels less than or equal to the setted value.
*/
@property (assign, nonatomic) MGLLoggingLevel loggingLevel;
@property (assign, nonatomic) MLNLoggingLevel loggingLevel;
/**
Returns the shared logging object.
*/
@property (class, nonatomic, readonly) MGLLoggingConfiguration *sharedConfiguration;
@property (class, nonatomic, readonly) MLNLoggingConfiguration *sharedConfiguration;
- (MGLLoggingBlockHandler)handler UNAVAILABLE_ATTRIBUTE;
- (MLNLoggingBlockHandler)handler UNAVAILABLE_ATTRIBUTE;
@end

View File

@@ -1,16 +1,16 @@
#include <mbgl/util/logging.hpp>
#include <mbgl/util/enum.hpp>
#import "MGLLoggingConfiguration_Private.h"
#import "MLNLoggingConfiguration_Private.h"
#ifndef MGL_LOGGING_DISABLED
#ifndef MLN_LOGGING_DISABLED
#if __has_builtin(__builtin_os_log_format)
#import <os/log.h>
#endif
namespace mbgl {
class MGLCoreLoggingObserver : public Log :: Observer {
class MLNCoreLoggingObserver : public Log :: Observer {
public:
//Return true not print messages at core level, and filter at platform level.
bool onRecord(EventSeverity severity, Event event, int64_t code, const std::string& msg) override{
@@ -18,16 +18,16 @@ public:
NSString *message = [NSString stringWithFormat:@"[event]:%s [code]:%lld [message]:%@", Enum<Event>::toString(event), code, [NSString stringWithCString:msg.c_str() encoding:NSUTF8StringEncoding]];
switch (severity) {
case EventSeverity::Debug:
MGLLogDebug(message);
MLNLogDebug(message);
break;
case EventSeverity::Info:
MGLLogInfo(message);
MLNLogInfo(message);
break;
case EventSeverity::Warning:
MGLLogWarning(message);
MLNLogWarning(message);
break;
case EventSeverity::Error:
MGLLogError(message);
MLNLogError(message);
break;
}
return true;
@@ -35,9 +35,9 @@ public:
};
}
@implementation MGLLoggingConfiguration
@implementation MLNLoggingConfiguration
{
std::unique_ptr<mbgl::MGLCoreLoggingObserver> _coreLoggingObserver;
std::unique_ptr<mbgl::MLNCoreLoggingObserver> _coreLoggingObserver;
}
+ (instancetype)sharedConfiguration {
@@ -45,19 +45,19 @@ public:
static id sharedConfiguration;
dispatch_once(&once, ^{
sharedConfiguration = [[self alloc] init];
((MGLLoggingConfiguration *)sharedConfiguration).handler = nil;
((MLNLoggingConfiguration *)sharedConfiguration).handler = nil;
});
return sharedConfiguration;
}
- (id)init{
if(self = [super init]){
mbgl::Log::setObserver(std::make_unique<mbgl::MGLCoreLoggingObserver>());
mbgl::Log::setObserver(std::make_unique<mbgl::MLNCoreLoggingObserver>());
}
return self;
}
- (void)setHandler:(void (^)(MGLLoggingLevel, NSString *, NSUInteger, NSString *))handler {
- (void)setHandler:(void (^)(MLNLoggingLevel, NSString *, NSUInteger, NSString *))handler {
if (!handler) {
_handler = [self defaultBlockHandler];
@@ -66,7 +66,7 @@ public:
}
}
- (void)logCallingFunction:(const char *)callingFunction functionLine:(NSUInteger)functionLine messageType:(MGLLoggingLevel)type format:(id)messageFormat, ... {
- (void)logCallingFunction:(const char *)callingFunction functionLine:(NSUInteger)functionLine messageType:(MLNLoggingLevel)type format:(id)messageFormat, ... {
va_list formatList;
va_start(formatList, messageFormat);
NSString *formattedMessage = [[NSString alloc] initWithFormat:messageFormat arguments:formatList];
@@ -76,27 +76,27 @@ public:
}
- (MGLLoggingBlockHandler)defaultBlockHandler {
MGLLoggingBlockHandler mapboxHandler = ^(MGLLoggingLevel level, NSString *fileName, NSUInteger line, NSString *message) {
- (MLNLoggingBlockHandler)defaultBlockHandler {
MLNLoggingBlockHandler mapboxHandler = ^(MLNLoggingLevel level, NSString *fileName, NSUInteger line, NSString *message) {
if (@available(iOS 10.0, macOS 10.12.0, *)) {
static dispatch_once_t once;
static os_log_t info_log;
#if MGL_LOGGING_ENABLE_DEBUG
#if MLN_LOGGING_ENABLE_DEBUG
static os_log_t debug_log;
#endif
static os_log_t error_log;
static os_log_t fault_log;
static os_log_type_t log_types[] = { OS_LOG_TYPE_DEFAULT,
OS_LOG_TYPE_INFO,
#if MGL_LOGGING_ENABLE_DEBUG
#if MLN_LOGGING_ENABLE_DEBUG
OS_LOG_TYPE_DEBUG,
#endif
OS_LOG_TYPE_ERROR,
OS_LOG_TYPE_FAULT };
dispatch_once(&once, ^ {
info_log = os_log_create("com.mapbox.Mapbox", "INFO");
#if MGL_LOGGING_ENABLE_DEBUG
#if MLN_LOGGING_ENABLE_DEBUG
debug_log = os_log_create("com.mapbox.Mapbox", "DEBUG");
#endif
error_log = os_log_create("com.mapbox.Mapbox", "ERROR");
@@ -105,22 +105,22 @@ public:
os_log_t mapbox_log;
switch (level) {
case MGLLoggingLevelInfo:
case MGLLoggingLevelWarning:
case MLNLoggingLevelInfo:
case MLNLoggingLevelWarning:
mapbox_log = info_log;
break;
#if MGL_LOGGING_ENABLE_DEBUG
case MGLLoggingLevelDebug:
#if MLN_LOGGING_ENABLE_DEBUG
case MLNLoggingLevelDebug:
mapbox_log = debug_log;
break;
#endif
case MGLLoggingLevelError:
case MLNLoggingLevelError:
mapbox_log = error_log;
break;
case MGLLoggingLevelFault:
case MLNLoggingLevelFault:
mapbox_log = fault_log;
break;
case MGLLoggingLevelNone:
case MLNLoggingLevelNone:
default:
break;
}
@@ -130,22 +130,22 @@ public:
} else {
NSString *category;
switch (level) {
case MGLLoggingLevelInfo:
case MGLLoggingLevelWarning:
case MLNLoggingLevelInfo:
case MLNLoggingLevelWarning:
category = @"INFO";
break;
#if MGL_LOGGING_ENABLE_DEBUG
case MGLLoggingLevelDebug:
#if MLN_LOGGING_ENABLE_DEBUG
case MLNLoggingLevelDebug:
category = @"DEBUG";
break;
#endif
case MGLLoggingLevelError:
case MLNLoggingLevelError:
category = @"ERROR";
break;
case MGLLoggingLevelFault:
case MLNLoggingLevelFault:
category = @"FAULT";
break;
case MGLLoggingLevelNone:
case MLNLoggingLevelNone:
default:
break;
}

View File

@@ -0,0 +1,67 @@
#import "MLNLoggingConfiguration.h"
NS_INLINE NSString *MLNStringFromBOOL(BOOL value) {
return value ? @"YES" : @"NO";
}
#if TARGET_OS_OSX
NS_INLINE NSString *MLNStringFromNSEdgeInsets(NSEdgeInsets insets) {
return [NSString stringWithFormat:@"{ top: %f, left: %f, bottom: %f, right: %f", insets.top, insets.left, insets.bottom, insets.right];
}
#endif
#ifdef MLN_LOGGING_DISABLED
#define MLNLogInfo(...)
#define MLNLogDebug(...)
#define MLNLogWarning(...)
#define MLNLogError(...)
#define MLNLogFault(...)
#else
#if MLN_LOGGING_ENABLE_DEBUG
#define MLNLogDebug(message, ...) MLNLogWithType(MLNLoggingLevelDebug, __PRETTY_FUNCTION__, __LINE__, message, ##__VA_ARGS__)
#else
#define MLNLogDebug(...)
#endif
#define MLNLogInfo(message, ...) MLNLogWithType(MLNLoggingLevelInfo, __PRETTY_FUNCTION__, __LINE__, message, ##__VA_ARGS__)
#define MLNLogWarning(message, ...) MLNLogWithType(MLNLoggingLevelWarning, __PRETTY_FUNCTION__, __LINE__, message, ##__VA_ARGS__)
#define MLNLogError(message, ...) MLNLogWithType(MLNLoggingLevelError, __PRETTY_FUNCTION__, __LINE__, message, ##__VA_ARGS__)
#define MLNLogFault(message, ...) MLNLogWithType(MLNLoggingLevelFault, __PRETTY_FUNCTION__, __LINE__, message, ##__VA_ARGS__)
#endif
#define MLNAssert(expression, message, ...) \
__extension__({ \
if (__builtin_expect(!(expression), 0)) { \
MLNLogFault(message, ##__VA_ARGS__); \
} \
NSAssert(expression, message, ##__VA_ARGS__); \
})
#define MLNCAssert(expression, message, ...) \
__extension__({ \
if (__builtin_expect(!(expression), 0)) { \
MLNLogFault(message, ##__VA_ARGS__); \
} \
NSCAssert(expression, message, ##__VA_ARGS__); \
})
#ifndef MLN_LOGGING_DISABLED
#define MLNLogWithType(type, function, line, message, ...) \
{ \
if ([MLNLoggingConfiguration sharedConfiguration].loggingLevel != MLNLoggingLevelNone && type <= [MLNLoggingConfiguration sharedConfiguration].loggingLevel) \
{ \
[[MLNLoggingConfiguration sharedConfiguration] logCallingFunction:function functionLine:line messageType:type format:(message), ##__VA_ARGS__]; \
} \
}
@interface MLNLoggingConfiguration (Private)
- (void)logCallingFunction:(const char *)callingFunction functionLine:(NSUInteger)functionLine messageType:(MLNLoggingLevel)type format:(id)messageFormat, ...;
@end
#endif

View File

@@ -2,24 +2,24 @@
#import <CoreGraphics/CoreGraphics.h>
#import <CoreLocation/CoreLocation.h>
#import "MGLFoundation.h"
#import "MLNFoundation.h"
NS_ASSUME_NONNULL_BEGIN
/**
An `MGLMapCamera` object represents a viewpoint from which the user observes
some point on an `MGLMapView`.
An `MLNMapCamera` object represents a viewpoint from which the user observes
some point on an `MLNMapView`.
#### Related examples
See the <a href="https://docs.mapbox.com/ios/maps/examples/camera-animation/">
Camera animation</a> example to learn how to create a camera that rotates
around a central point. See the <a href="https://docs.mapbox.com/ios/maps/examples/constraining-gestures/">
Restrict map panning to an area</a> example to learn how to restrict map
panning using `MGLMapViewDelegate`'s
panning using `MLNMapViewDelegate`'s
`-mapView:shouldChangeFromCamera:toCamera:` method.
*/
MGL_EXPORT
@interface MGLMapCamera : NSObject <NSSecureCoding, NSCopying>
MLN_EXPORT
@interface MLNMapCamera : NSObject <NSSecureCoding, NSCopying>
/** Coordinate at the center of the map view. */
@property (nonatomic) CLLocationCoordinate2D centerCoordinate;
@@ -145,7 +145,7 @@ __attribute__((deprecated("Use -cameraLookingAtCenterCoordinate:acrossDistance:p
@return A Boolean value indicating whether the two cameras are functionally
equivalent.
*/
- (BOOL)isEqualToMapCamera:(MGLMapCamera *)otherCamera;
- (BOOL)isEqualToMapCamera:(MLNMapCamera *)otherCamera;
@end

View File

@@ -1,17 +1,17 @@
#import "MGLMapCamera.h"
#import "MGLGeometry_Private.h"
#import "MGLLoggingConfiguration_Private.h"
#import "MLNMapCamera.h"
#import "MLNGeometry_Private.h"
#import "MLNLoggingConfiguration_Private.h"
#import <CoreLocation/CoreLocation.h>
#include <mbgl/math/wrap.hpp>
BOOL MGLEqualFloatWithAccuracy(CGFloat left, CGFloat right, CGFloat accuracy)
BOOL MLNEqualFloatWithAccuracy(CGFloat left, CGFloat right, CGFloat accuracy)
{
return MAX(left, right) - MIN(left, right) <= accuracy;
}
@implementation MGLMapCamera
@implementation MLNMapCamera
+ (BOOL)supportsSecureCoding
{
@@ -30,7 +30,7 @@ BOOL MGLEqualFloatWithAccuracy(CGFloat left, CGFloat right, CGFloat accuracy)
CLLocationDirection heading = -1;
CGFloat pitch = -1;
if (CLLocationCoordinate2DIsValid(centerCoordinate) && CLLocationCoordinate2DIsValid(eyeCoordinate)) {
heading = MGLDirectionBetweenCoordinates(eyeCoordinate, centerCoordinate);
heading = MLNDirectionBetweenCoordinates(eyeCoordinate, centerCoordinate);
CLLocation *centerLocation = [[CLLocation alloc] initWithLatitude:centerCoordinate.latitude
longitude:centerCoordinate.longitude];
@@ -38,7 +38,7 @@ BOOL MGLEqualFloatWithAccuracy(CGFloat left, CGFloat right, CGFloat accuracy)
longitude:eyeCoordinate.longitude];
CLLocationDistance groundDistance = [eyeLocation distanceFromLocation:centerLocation];
CGFloat radianPitch = atan2(eyeAltitude, groundDistance);
pitch = mbgl::util::wrap(90 - MGLDegreesFromRadians(radianPitch), 0.0, 360.0);
pitch = mbgl::util::wrap(90 - MLNDegreesFromRadians(radianPitch), 0.0, 360.0);
}
return [[self alloc] initWithCenterCoordinate:centerCoordinate
@@ -55,7 +55,7 @@ BOOL MGLEqualFloatWithAccuracy(CGFloat left, CGFloat right, CGFloat accuracy)
// Angle at the viewpoint formed by the straight lines running perpendicular
// to the ground and toward the center coordinate.
CLLocationDirection eyeAngle = 90 - pitch;
CLLocationDistance altitude = distance * sin(MGLRadiansFromDegrees(eyeAngle));
CLLocationDistance altitude = distance * sin(MLNRadiansFromDegrees(eyeAngle));
return [[self alloc] initWithCenterCoordinate:centerCoordinate
altitude:altitude
@@ -81,7 +81,7 @@ BOOL MGLEqualFloatWithAccuracy(CGFloat left, CGFloat right, CGFloat accuracy)
{
// TODO: Remove this compatibility shim in favor of `-cameraLookingAtCenterCoordinate:acrossDistance:pitch:heading:.
// https://github.com/mapbox/mapbox-gl-native/issues/12943
return [MGLMapCamera cameraLookingAtCenterCoordinate:centerCoordinate
return [MLNMapCamera cameraLookingAtCenterCoordinate:centerCoordinate
altitude:distance
pitch:pitch
heading:heading];
@@ -92,7 +92,7 @@ BOOL MGLEqualFloatWithAccuracy(CGFloat left, CGFloat right, CGFloat accuracy)
pitch:(CGFloat)pitch
heading:(CLLocationDirection)heading
{
MGLLogDebug(@"Initializing withCenterCoordinate: %@ altitude: %.0fm pitch: %f° heading: %f°", MGLStringFromCLLocationCoordinate2D(centerCoordinate), altitude, pitch, heading);
MLNLogDebug(@"Initializing withCenterCoordinate: %@ altitude: %.0fm pitch: %f° heading: %f°", MLNStringFromCLLocationCoordinate2D(centerCoordinate), altitude, pitch, heading);
if (self = [super init])
{
_centerCoordinate = centerCoordinate;
@@ -105,7 +105,7 @@ BOOL MGLEqualFloatWithAccuracy(CGFloat left, CGFloat right, CGFloat accuracy)
- (nullable instancetype)initWithCoder:(NSCoder *)coder
{
MGLLogInfo(@"Initialiazing with coder.");
MLNLogInfo(@"Initialiazing with coder.");
if (self = [super init])
{
_centerCoordinate = CLLocationCoordinate2DMake([coder decodeDoubleForKey:@"centerLatitude"],
@@ -140,13 +140,13 @@ BOOL MGLEqualFloatWithAccuracy(CGFloat left, CGFloat right, CGFloat accuracy)
- (CLLocationDistance)viewingDistance {
CLLocationDirection eyeAngle = 90 - self.pitch;
return self.altitude / sin(MGLRadiansFromDegrees(eyeAngle));
return self.altitude / sin(MLNRadiansFromDegrees(eyeAngle));
}
- (void)setViewingDistance:(CLLocationDistance)distance {
MGLLogDebug(@"Setting viewingDistance: %f", distance);
MLNLogDebug(@"Setting viewingDistance: %f", distance);
CLLocationDirection eyeAngle = 90 - self.pitch;
self.altitude = distance * sin(MGLRadiansFromDegrees(eyeAngle));
self.altitude = distance * sin(MLNRadiansFromDegrees(eyeAngle));
}
- (NSString *)description
@@ -166,25 +166,25 @@ BOOL MGLEqualFloatWithAccuracy(CGFloat left, CGFloat right, CGFloat accuracy)
return YES;
}
MGLMapCamera *otherCamera = other;
MLNMapCamera *otherCamera = other;
return (_centerCoordinate.latitude == otherCamera.centerCoordinate.latitude
&& _centerCoordinate.longitude == otherCamera.centerCoordinate.longitude
&& _altitude == otherCamera.altitude
&& _pitch == otherCamera.pitch && _heading == otherCamera.heading);
}
- (BOOL)isEqualToMapCamera:(MGLMapCamera *)otherCamera
- (BOOL)isEqualToMapCamera:(MLNMapCamera *)otherCamera
{
if (otherCamera == self)
{
return YES;
}
return (MGLEqualFloatWithAccuracy(_centerCoordinate.latitude, otherCamera.centerCoordinate.latitude, 1e-6)
&& MGLEqualFloatWithAccuracy(_centerCoordinate.longitude, otherCamera.centerCoordinate.longitude, 1e-6)
&& MGLEqualFloatWithAccuracy(_altitude, otherCamera.altitude, 1e-6)
&& MGLEqualFloatWithAccuracy(_pitch, otherCamera.pitch, 1)
&& MGLEqualFloatWithAccuracy(_heading, otherCamera.heading, 1));
return (MLNEqualFloatWithAccuracy(_centerCoordinate.latitude, otherCamera.centerCoordinate.latitude, 1e-6)
&& MLNEqualFloatWithAccuracy(_centerCoordinate.longitude, otherCamera.centerCoordinate.longitude, 1e-6)
&& MLNEqualFloatWithAccuracy(_altitude, otherCamera.altitude, 1e-6)
&& MLNEqualFloatWithAccuracy(_pitch, otherCamera.pitch, 1)
&& MLNEqualFloatWithAccuracy(_heading, otherCamera.heading, 1));
}
- (NSUInteger)hash

View File

@@ -1,20 +1,20 @@
#import <Foundation/Foundation.h>
#import "MGLTypes.h"
#import "MGLGeometry.h"
#import "MGLMapCamera.h"
#import "MGLStyle.h"
#import "MLNTypes.h"
#import "MLNGeometry.h"
#import "MLNMapCamera.h"
#import "MLNStyle.h"
NS_ASSUME_NONNULL_BEGIN
@protocol MGLMapSnapshotterDelegate;
@protocol MLNMapSnapshotterDelegate;
/**
An overlay that is placed within a `MGLMapSnapshot`.
To access this object, use `-[MGLMapSnapshotter startWithOverlayHandler:completionHandler:]`.
An overlay that is placed within a `MLNMapSnapshot`.
To access this object, use `-[MLNMapSnapshotter startWithOverlayHandler:completionHandler:]`.
*/
MGL_EXPORT
@interface MGLMapSnapshotOverlay : NSObject
MLN_EXPORT
@interface MLNMapSnapshotOverlay : NSObject
/**
The current `CGContext` that snapshot is drawing within. You may use this context
@@ -53,15 +53,15 @@ MGL_EXPORT
A block provided during the snapshot drawing process, enabling the ability to
draw custom overlays rendered with Core Graphics.
@param snapshotOverlay The `MGLMapSnapshotOverlay` provided during snapshot drawing.
@param snapshotOverlay The `MLNMapSnapshotOverlay` provided during snapshot drawing.
*/
typedef void (^MGLMapSnapshotOverlayHandler)(MGLMapSnapshotOverlay * snapshotOverlay);
typedef void (^MLNMapSnapshotOverlayHandler)(MLNMapSnapshotOverlay * snapshotOverlay);
/**
The options to use when creating images with the `MGLMapSnapshotter`.
The options to use when creating images with the `MLNMapSnapshotter`.
*/
MGL_EXPORT
@interface MGLMapSnapshotOptions : NSObject <NSCopying>
MLN_EXPORT
@interface MLNMapSnapshotOptions : NSObject <NSCopying>
/**
Creates a set of options with the minimum required information.
@@ -71,7 +71,7 @@ MGL_EXPORT
the application’s resource path. Specify `nil` for the default style.
@param size The image size.
*/
- (instancetype)initWithStyleURL:(nullable NSURL *)styleURL camera:(MGLMapCamera *)camera size:(CGSize)size;
- (instancetype)initWithStyleURL:(nullable NSURL *)styleURL camera:(MLNMapCamera *)camera size:(CGSize)size;
// MARK: - Configuring the Map
@@ -96,7 +96,7 @@ MGL_EXPORT
non-empty coordinate bounds, the camera’s center coordinate and altitude are
ignored in favor of the `coordinateBounds` property.
*/
@property (nonatomic) MGLMapCamera *camera;
@property (nonatomic) MLNMapCamera *camera;
/**
The coordinate rectangle that encompasses the bounds to capture.
@@ -104,7 +104,7 @@ MGL_EXPORT
If this property is non-empty and the camera property is non-nil, the camera’s
center coordinate and altitude are ignored in favor of this property’s value.
*/
@property (nonatomic) MGLCoordinateBounds coordinateBounds;
@property (nonatomic) MLNCoordinateBounds coordinateBounds;
// MARK: - Configuring the Image
@@ -126,8 +126,8 @@ MGL_EXPORT
/**
An image generated by a snapshotter object.
*/
MGL_EXPORT
@interface MGLMapSnapshot : NSObject
MLN_EXPORT
@interface MLNMapSnapshot : NSObject
#if TARGET_OS_IPHONE
/**
@@ -169,17 +169,17 @@ MGL_EXPORT
/**
A block to processes the result or error of a snapshot request.
@param snapshot The `MGLMapSnapshot` that was generated or `nil` if an error
@param snapshot The `MLNMapSnapshot` that was generated or `nil` if an error
occurred.
@param error The error that occured or `nil` when successful.
*/
typedef void (^MGLMapSnapshotCompletionHandler)(MGLMapSnapshot* _Nullable snapshot, NSError* _Nullable error);
typedef void (^MLNMapSnapshotCompletionHandler)(MLNMapSnapshot* _Nullable snapshot, NSError* _Nullable error);
/**
An `MGLMapSnapshotter` generates static raster images of the map. Each snapshot
image depicts a portion of a map defined by an `MGLMapSnapshotOptions` object
you provide. The snapshotter generates an `MGLMapSnapshot` object
asynchronously, calling `MGLMapSnapshotterDelegate` methods if defined, then
An `MLNMapSnapshotter` generates static raster images of the map. Each snapshot
image depicts a portion of a map defined by an `MLNMapSnapshotOptions` object
you provide. The snapshotter generates an `MLNMapSnapshot` object
asynchronously, calling `MLNMapSnapshotterDelegate` methods if defined, then
passing it into a completion handler once tiles and other resources needed for
the snapshot are finished loading.
@@ -188,9 +188,9 @@ typedef void (^MGLMapSnapshotCompletionHandler)(MGLMapSnapshot* _Nullable snapsh
snapshot at a time. If you need to generate multiple snapshots concurrently,
create multiple snapshotter objects.
For an interactive map, use the `MGLMapView` class. Both `MGLMapSnapshotter`
and `MGLMapView` are compatible with offline packs managed by the
`MGLOfflineStorage` class.
For an interactive map, use the `MLNMapView` class. Both `MLNMapSnapshotter`
and `MLNMapView` are compatible with offline packs managed by the
`MLNOfflineStorage` class.
From a snapshot, you can obtain an image and convert geographic coordinates to
the image’s coordinate space in order to superimpose markers and overlays. If
@@ -201,12 +201,12 @@ typedef void (^MGLMapSnapshotCompletionHandler)(MGLMapSnapshot* _Nullable snapsh
### Example
```swift
let camera = MGLMapCamera(lookingAtCenter: CLLocationCoordinate2D(latitude: 37.7184, longitude: -122.4365), altitude: 100, pitch: 20, heading: 0)
let camera = MLNMapCamera(lookingAtCenter: CLLocationCoordinate2D(latitude: 37.7184, longitude: -122.4365), altitude: 100, pitch: 20, heading: 0)
let options = MGLMapSnapshotOptions(styleURL: MGLStyle.satelliteStreetsStyleURL, camera: camera, size: CGSize(width: 320, height: 480))
let options = MLNMapSnapshotOptions(styleURL: MLNStyle.satelliteStreetsStyleURL, camera: camera, size: CGSize(width: 320, height: 480))
options.zoomLevel = 10
let snapshotter = MGLMapSnapshotter(options: options)
let snapshotter = MLNMapSnapshotter(options: options)
snapshotter.start { (snapshot, error) in
if let error = error {
fatalError(error.localizedDescription)
@@ -219,11 +219,11 @@ typedef void (^MGLMapSnapshotCompletionHandler)(MGLMapSnapshot* _Nullable snapsh
#### Related examples
See the <a href="https://docs.mapbox.com/ios/maps/examples/map-snapshotter/">
Create a static map snapshot</a> example to learn how to use the
`MGLMapSnapshotter` to generate a static image based on an `MGLMapView`
`MLNMapSnapshotter` to generate a static image based on an `MLNMapView`
object's style, camera, and view bounds.
*/
MGL_EXPORT
@interface MGLMapSnapshotter : NSObject <MGLStylable>
MLN_EXPORT
@interface MLNMapSnapshotter : NSObject <MLNStylable>
- (instancetype)init NS_UNAVAILABLE;
@@ -234,7 +234,7 @@ MGL_EXPORT
@param options The options to use when generating a map snapshot.
@return An initialized map snapshotter.
*/
- (instancetype)initWithOptions:(MGLMapSnapshotOptions *)options NS_DESIGNATED_INITIALIZER;
- (instancetype)initWithOptions:(MLNMapSnapshotOptions *)options NS_DESIGNATED_INITIALIZER;
/**
Starts the snapshot creation and executes the specified block with the result.
@@ -242,7 +242,7 @@ MGL_EXPORT
@param completionHandler The block to call with a finished snapshot. The block
is executed on the main queue.
*/
- (void)startWithCompletionHandler:(MGLMapSnapshotCompletionHandler)completionHandler;
- (void)startWithCompletionHandler:(MLNMapSnapshotCompletionHandler)completionHandler;
/**
Starts the snapshot creation and executes the specified block with the result
@@ -253,12 +253,12 @@ MGL_EXPORT
@param completionHandler The block to call with a finished snapshot. The block
is executed on the queue specified in the `queue` parameter.
*/
- (void)startWithQueue:(dispatch_queue_t)queue completionHandler:(MGLMapSnapshotCompletionHandler)completionHandler;
- (void)startWithQueue:(dispatch_queue_t)queue completionHandler:(MLNMapSnapshotCompletionHandler)completionHandler;
/**
Starts the snapshot creation and executes the specified blocks with the result
on the specified queue. Use this option if you want to add custom drawing on
top of the resulting `MGLMapSnapshot`.
top of the resulting `MLNMapSnapshot`.
@param overlayHandler The block to call after the base map finishes drawing but
before certain built-in overlays draw. The block can use Core Graphics to
@@ -267,20 +267,20 @@ MGL_EXPORT
@param completionHandler The block to call with a finished snapshot. The block
is executed on the main queue.
*/
- (void)startWithOverlayHandler:(MGLMapSnapshotOverlayHandler)overlayHandler completionHandler:(MGLMapSnapshotCompletionHandler)completionHandler;
- (void)startWithOverlayHandler:(MLNMapSnapshotOverlayHandler)overlayHandler completionHandler:(MLNMapSnapshotCompletionHandler)completionHandler;
/**
Cancels the snapshot creation request, if any.
Once you call this method, you cannot resume the snapshot. In order to obtain
the snapshot, create a new `MGLMapSnapshotter` object.
the snapshot, create a new `MLNMapSnapshotter` object.
*/
- (void)cancel;
/**
The options to use when generating a map snapshot.
*/
@property (nonatomic) MGLMapSnapshotOptions *options;
@property (nonatomic) MLNMapSnapshotOptions *options;
/**
Indicates whether a snapshot is currently being generated.
@@ -299,36 +299,36 @@ MGL_EXPORT
weak reference to its delegate, so you must keep a strong reference to it to
ensure that your style customizations apply.
*/
@property (nonatomic, weak) id <MGLMapSnapshotterDelegate> delegate;
@property (nonatomic, weak) id <MLNMapSnapshotterDelegate> delegate;
/**
The style displayed in the resulting snapshot.
Unlike the `MGLMapSnapshotOptions.styleURL` property, this property is set to
Unlike the `MLNMapSnapshotOptions.styleURL` property, this property is set to
an object that allows you to manipulate every aspect of the style locally.
This property is set to `nil` until the style finishes loading. If the style
has failed to load, this property is set to `nil`. Because the style loads
asynchronously, you should manipulate it in the
`-[MGLMapSnapshotterDelegate mapSnapshotter:didFinishLoadingStyle:]` method. It
`-[MLNMapSnapshotterDelegate mapSnapshotter:didFinishLoadingStyle:]` method. It
is not possible to manipulate the style before it has finished loading.
@note The default styles provided by Mapbox contain sources and layers with
identifiers that will change over time. Applications that use APIs that
manipulate a style’s sources and layers must first set the style URL to an
explicitly versioned style using a convenience method like
`+[MGLStyle outdoorsStyleURLWithVersion:]` or a manually constructed
`+[MLNStyle outdoorsStyleURLWithVersion:]` or a manually constructed
`NSURL`.
*/
@property (nonatomic, readonly, nullable) MGLStyle *style;
@property (nonatomic, readonly, nullable) MLNStyle *style;
@end
/**
Optional methods about significant events when creating a snapshot using an
`MGLMapSnapshotter` object.
`MLNMapSnapshotter` object.
*/
@protocol MGLMapSnapshotterDelegate <NSObject>
@protocol MLNMapSnapshotterDelegate <NSObject>
@optional
/**
@@ -342,22 +342,22 @@ MGL_EXPORT
@param snapshotter The snapshotter that is unable to load the data.
@param error The reason the data could not be loaded.
*/
- (void)mapSnapshotterDidFail:(MGLMapSnapshotter *)snapshotter withError:(NSError *)error;
- (void)mapSnapshotterDidFail:(MLNMapSnapshotter *)snapshotter withError:(NSError *)error;
/**
Tells the delegate that the snapshotter has just finished loading a style.
This method is called in response to
`-[MGLMapSnapshotter startWithQueue:completionHandler:]` as long as the
`MGLMapSnapshotter.delegate` property is set. Changes to sources or layers of
`-[MLNMapSnapshotter startWithQueue:completionHandler:]` as long as the
`MLNMapSnapshotter.delegate` property is set. Changes to sources or layers of
the style being snapshotted do not cause this method to be called.
@param snapshotter The snapshotter that has just loaded a style.
@param style The style that was loaded.
*/
- (void)mapSnapshotter:(MGLMapSnapshotter *)snapshotter didFinishLoadingStyle:(MGLStyle *)style;
- (void)mapSnapshotter:(MLNMapSnapshotter *)snapshotter didFinishLoadingStyle:(MLNStyle *)style;
- (void)mapSnapshotter:(MGLMapSnapshotter *)snapshotter didFailLoadingImageNamed:(NSString *)name;
- (void)mapSnapshotter:(MLNMapSnapshotter *)snapshotter didFailLoadingImageNamed:(NSString *)name;
@end

View File

@@ -1,4 +1,4 @@
#import "MGLMapSnapshotter.h"
#import "MLNMapSnapshotter.h"
#import <mbgl/actor/actor.hpp>
#import <mbgl/actor/scheduler.hpp>
@@ -10,76 +10,76 @@
#import <mbgl/util/client_options.hpp>
#import <mbgl/util/string.hpp>
#import "MGLOfflineStorage_Private.h"
#import "MGLGeometry_Private.h"
#import "MGLStyle_Private.h"
#import "MGLAttributionInfo_Private.h"
#import "MGLLoggingConfiguration_Private.h"
#import "MGLRendererConfiguration.h"
#import "MGLMapSnapshotter_Private.h"
#import "MGLSettings_Private.h"
#import "MLNOfflineStorage_Private.h"
#import "MLNGeometry_Private.h"
#import "MLNStyle_Private.h"
#import "MLNAttributionInfo_Private.h"
#import "MLNLoggingConfiguration_Private.h"
#import "MLNRendererConfiguration.h"
#import "MLNMapSnapshotter_Private.h"
#import "MLNSettings_Private.h"
#if TARGET_OS_IPHONE
#import "UIImage+MGLAdditions.h"
#import "UIImage+MLNAdditions.h"
#else
#import "NSImage+MGLAdditions.h"
#import "NSImage+MLNAdditions.h"
#import <CoreGraphics/CoreGraphics.h>
#import <CoreImage/CIContext.h>
#import <CoreImage/CIFilter.h>
#import <QuartzCore/QuartzCore.h>
#endif
#import "NSBundle+MGLAdditions.h"
#import "NSBundle+MLNAdditions.h"
const CGPoint MGLLogoImagePosition = CGPointMake(8, 8);
const CGFloat MGLSnapshotterMinimumPixelSize = 64;
const CGPoint MLNLogoImagePosition = CGPointMake(8, 8);
const CGFloat MLNSnapshotterMinimumPixelSize = 64;
MGLImage *MGLAttributedSnapshot(mbgl::MapSnapshotter::Attributions attributions, MGLImage *mglImage, mbgl::MapSnapshotter::PointForFn pointForFn, mbgl::MapSnapshotter::LatLngForFn latLngForFn, MGLMapSnapshotOptions *options, MGLMapSnapshotOverlayHandler overlayHandler);
MGLMapSnapshot *MGLSnapshotWithDecoratedImage(MGLImage *mglImage, MGLMapSnapshotOptions *options, mbgl::MapSnapshotter::Attributions attributions, mbgl::MapSnapshotter::PointForFn pointForFn, mbgl::MapSnapshotter::LatLngForFn latLngForFn, MGLMapSnapshotOverlayHandler overlayHandler, NSError * _Nullable *outError);
NSArray<MGLAttributionInfo *> *MGLAttributionInfosFromAttributions(mbgl::MapSnapshotter::Attributions attributions);
MLNImage *MLNAttributedSnapshot(mbgl::MapSnapshotter::Attributions attributions, MLNImage *mglImage, mbgl::MapSnapshotter::PointForFn pointForFn, mbgl::MapSnapshotter::LatLngForFn latLngForFn, MLNMapSnapshotOptions *options, MLNMapSnapshotOverlayHandler overlayHandler);
MLNMapSnapshot *MLNSnapshotWithDecoratedImage(MLNImage *mglImage, MLNMapSnapshotOptions *options, mbgl::MapSnapshotter::Attributions attributions, mbgl::MapSnapshotter::PointForFn pointForFn, mbgl::MapSnapshotter::LatLngForFn latLngForFn, MLNMapSnapshotOverlayHandler overlayHandler, NSError * _Nullable *outError);
NSArray<MLNAttributionInfo *> *MLNAttributionInfosFromAttributions(mbgl::MapSnapshotter::Attributions attributions);
class MGLMapSnapshotterDelegateHost: public mbgl::MapSnapshotterObserver {
class MLNMapSnapshotterDelegateHost: public mbgl::MapSnapshotterObserver {
public:
MGLMapSnapshotterDelegateHost(MGLMapSnapshotter *snapshotter_) : snapshotter(snapshotter_) {}
MLNMapSnapshotterDelegateHost(MLNMapSnapshotter *snapshotter_) : snapshotter(snapshotter_) {}
void onDidFailLoadingStyle(const std::string& errorMessage) {
MGLMapSnapshotter *strongSnapshotter = snapshotter;
MLNMapSnapshotter *strongSnapshotter = snapshotter;
if ([strongSnapshotter.delegate respondsToSelector:@selector(mapSnapshotterDidFail:withError:)]) {
NSString *description = @(errorMessage.c_str());
NSDictionary *userInfo = @{
NSLocalizedDescriptionKey: NSLocalizedStringWithDefaultValue(@"SNAPSHOT_LOAD_STYLE_FAILED_DESC", nil, nil, @"The snapshot failed because the style can’t be loaded.", @"User-friendly error description"),
NSLocalizedFailureReasonErrorKey: description,
};
NSError *error = [NSError errorWithDomain:MGLErrorDomain code:MGLErrorCodeLoadStyleFailed userInfo:userInfo];
NSError *error = [NSError errorWithDomain:MLNErrorDomain code:MLNErrorCodeLoadStyleFailed userInfo:userInfo];
[strongSnapshotter.delegate mapSnapshotterDidFail:snapshotter withError:error];
}
}
void onDidFinishLoadingStyle() {
MGLMapSnapshotter *strongSnapshotter = snapshotter;
MLNMapSnapshotter *strongSnapshotter = snapshotter;
if ([strongSnapshotter.delegate respondsToSelector:@selector(mapSnapshotter:didFinishLoadingStyle:)]) {
[strongSnapshotter.delegate mapSnapshotter:snapshotter didFinishLoadingStyle:snapshotter.style];
}
}
void onStyleImageMissing(const std::string& imageName) {
MGLMapSnapshotter *strongSnapshotter = snapshotter;
MLNMapSnapshotter *strongSnapshotter = snapshotter;
if ([strongSnapshotter.delegate respondsToSelector:@selector(mapSnapshotter:didFailLoadingImageNamed:)]) {
[strongSnapshotter.delegate mapSnapshotter:snapshotter didFailLoadingImageNamed:@(imageName.c_str())];
}
}
private:
__weak MGLMapSnapshotter *snapshotter;
__weak MLNMapSnapshotter *snapshotter;
};
@interface MGLMapSnapshotOverlay() <MGLMapSnapshotProtocol>
@interface MLNMapSnapshotOverlay() <MLNMapSnapshotProtocol>
@property (nonatomic, assign) CGFloat scale;
- (instancetype)initWithContext:(CGContextRef)context scale:(CGFloat)scale pointForFn:(mbgl::MapSnapshotter::PointForFn)pointForFn latLngForFn:(mbgl::MapSnapshotter::LatLngForFn)latLngForFn;
@end
@implementation MGLMapSnapshotOverlay {
@implementation MLNMapSnapshotOverlay {
mbgl::MapSnapshotter::PointForFn _pointForFn;
mbgl::MapSnapshotter::LatLngForFn _latLngForFn;
}
@@ -100,21 +100,21 @@ private:
- (CGPoint)pointForCoordinate:(CLLocationCoordinate2D)coordinate
{
mbgl::ScreenCoordinate sc = _pointForFn(MGLLatLngFromLocationCoordinate2D(coordinate));
mbgl::ScreenCoordinate sc = _pointForFn(MLNLatLngFromLocationCoordinate2D(coordinate));
return CGPointMake(sc.x, sc.y);
}
- (CLLocationCoordinate2D)coordinateForPoint:(CGPoint)point
{
mbgl::LatLng latLng = _latLngForFn(mbgl::ScreenCoordinate(point.x, point.y));
return MGLLocationCoordinate2DFromLatLng(latLng);
return MLNLocationCoordinate2DFromLatLng(latLng);
}
#else
- (NSPoint)pointForCoordinate:(CLLocationCoordinate2D)coordinate
{
mbgl::ScreenCoordinate sc = _pointForFn(MGLLatLngFromLocationCoordinate2D(coordinate));
mbgl::ScreenCoordinate sc = _pointForFn(MLNLatLngFromLocationCoordinate2D(coordinate));
CGFloat height = ((CGFloat)CGBitmapContextGetHeight(self.context))/self.scale;
return NSMakePoint(sc.x, height - sc.y);
}
@@ -124,13 +124,13 @@ private:
CGFloat height = ((CGFloat)CGBitmapContextGetHeight(self.context))/self.scale;
auto screenCoord = mbgl::ScreenCoordinate(point.x, height - point.y);
mbgl::LatLng latLng = _latLngForFn(screenCoord);
return MGLLocationCoordinate2DFromLatLng(latLng);
return MLNLocationCoordinate2DFromLatLng(latLng);
}
#endif
@end
@interface MGLMapSnapshotOptions ()
@interface MLNMapSnapshotOptions ()
/**
:nodoc:
@@ -145,17 +145,17 @@ private:
@property (nonatomic, readwrite) BOOL showsLogo;
@end
@implementation MGLMapSnapshotOptions
@implementation MLNMapSnapshotOptions
- (instancetype _Nonnull)initWithStyleURL:(nullable NSURL *)styleURL camera:(MGLMapCamera *)camera size:(CGSize)size
- (instancetype _Nonnull)initWithStyleURL:(nullable NSURL *)styleURL camera:(MLNMapCamera *)camera size:(CGSize)size
{
MGLLogDebug(@"Initializing withStyleURL: %@ camera: %@ size: %@", styleURL, camera, MGLStringFromSize(size));
MLNLogDebug(@"Initializing withStyleURL: %@ camera: %@ size: %@", styleURL, camera, MLNStringFromSize(size));
self = [super init];
if (self)
{
if ( !styleURL)
{
styleURL = [MGLStyle defaultStyleURL];
styleURL = [MLNStyle defaultStyleURL];
}
_styleURL = styleURL;
_size = size;
@@ -181,18 +181,18 @@ private:
@end
@interface MGLMapSnapshot() <MGLMapSnapshotProtocol>
- (instancetype)initWithImage:(nullable MGLImage *)image scale:(CGFloat)scale pointForFn:(mbgl::MapSnapshotter::PointForFn)pointForFn latLngForFn:(mbgl::MapSnapshotter::LatLngForFn)latLngForFn;
@interface MLNMapSnapshot() <MLNMapSnapshotProtocol>
- (instancetype)initWithImage:(nullable MLNImage *)image scale:(CGFloat)scale pointForFn:(mbgl::MapSnapshotter::PointForFn)pointForFn latLngForFn:(mbgl::MapSnapshotter::LatLngForFn)latLngForFn;
@property (nonatomic) CGFloat scale;
@end
@implementation MGLMapSnapshot {
@implementation MLNMapSnapshot {
mbgl::MapSnapshotter::PointForFn _pointForFn;
mbgl::MapSnapshotter::LatLngForFn _latLngForFn;
}
- (instancetype)initWithImage:(nullable MGLImage *)image scale:(CGFloat)scale pointForFn:(mbgl::MapSnapshotter::PointForFn)pointForFn latLngForFn:(mbgl::MapSnapshotter::LatLngForFn)latLngForFn
- (instancetype)initWithImage:(nullable MLNImage *)image scale:(CGFloat)scale pointForFn:(mbgl::MapSnapshotter::PointForFn)pointForFn latLngForFn:(mbgl::MapSnapshotter::LatLngForFn)latLngForFn
{
self = [super init];
if (self) {
@@ -208,21 +208,21 @@ private:
- (CGPoint)pointForCoordinate:(CLLocationCoordinate2D)coordinate
{
mbgl::ScreenCoordinate sc = _pointForFn(MGLLatLngFromLocationCoordinate2D(coordinate));
mbgl::ScreenCoordinate sc = _pointForFn(MLNLatLngFromLocationCoordinate2D(coordinate));
return CGPointMake(sc.x, sc.y);
}
- (CLLocationCoordinate2D)coordinateForPoint:(CGPoint)point
{
mbgl::LatLng latLng = _latLngForFn(mbgl::ScreenCoordinate(point.x, point.y));
return MGLLocationCoordinate2DFromLatLng(latLng);
return MLNLocationCoordinate2DFromLatLng(latLng);
}
#else
- (NSPoint)pointForCoordinate:(CLLocationCoordinate2D)coordinate
{
mbgl::ScreenCoordinate sc = _pointForFn(MGLLatLngFromLocationCoordinate2D(coordinate));
mbgl::ScreenCoordinate sc = _pointForFn(MLNLatLngFromLocationCoordinate2D(coordinate));
return NSMakePoint(sc.x, self.image.size.height - sc.y);
}
@@ -230,21 +230,21 @@ private:
{
auto screenCoord = mbgl::ScreenCoordinate(point.x, self.image.size.height - point.y);
mbgl::LatLng latLng = _latLngForFn(screenCoord);
return MGLLocationCoordinate2DFromLatLng(latLng);
return MLNLocationCoordinate2DFromLatLng(latLng);
}
#endif
@end
@interface MGLMapSnapshotter()
@interface MLNMapSnapshotter()
@property (nonatomic) BOOL loading;
@property (nonatomic) BOOL terminated;
@end
@implementation MGLMapSnapshotter {
@implementation MLNMapSnapshotter {
std::unique_ptr<mbgl::MapSnapshotter> _mbglMapSnapshotter;
std::unique_ptr<MGLMapSnapshotterDelegateHost> _delegateHost;
std::unique_ptr<MLNMapSnapshotterDelegateHost> _delegateHost;
}
- (void)dealloc {
@@ -253,14 +253,14 @@ private:
}
- (instancetype)init {
NSAssert(NO, @"Please use -[MGLMapSnapshotter initWithOptions:]");
NSAssert(NO, @"Please use -[MLNMapSnapshotter initWithOptions:]");
[super doesNotRecognizeSelector:_cmd];
return nil;
}
- (instancetype)initWithOptions:(MGLMapSnapshotOptions *)options
- (instancetype)initWithOptions:(MLNMapSnapshotOptions *)options
{
MGLLogDebug(@"Initializing withOptions: %@", options);
MLNLogDebug(@"Initializing withOptions: %@", options);
self = [super init];
if (self) {
self.options = options;
@@ -279,33 +279,33 @@ private:
self.terminated = YES;
}
- (void)startWithCompletionHandler:(MGLMapSnapshotCompletionHandler)completion
- (void)startWithCompletionHandler:(MLNMapSnapshotCompletionHandler)completion
{
MGLLogDebug(@"Starting withCompletionHandler: %@", completion);
MLNLogDebug(@"Starting withCompletionHandler: %@", completion);
[self startWithQueue:dispatch_get_main_queue() completionHandler:completion];
}
- (void)startWithQueue:(dispatch_queue_t)queue completionHandler:(MGLMapSnapshotCompletionHandler)completionHandler {
- (void)startWithQueue:(dispatch_queue_t)queue completionHandler:(MLNMapSnapshotCompletionHandler)completionHandler {
[self startWithQueue:queue overlayHandler:nil completionHandler:completionHandler];
}
- (void)startWithOverlayHandler:(MGLMapSnapshotOverlayHandler)overlayHandler completionHandler:(MGLMapSnapshotCompletionHandler)completion {
- (void)startWithOverlayHandler:(MLNMapSnapshotOverlayHandler)overlayHandler completionHandler:(MLNMapSnapshotCompletionHandler)completion {
[self startWithQueue:dispatch_get_main_queue() overlayHandler:overlayHandler completionHandler:completion];
}
- (void)startWithQueue:(dispatch_queue_t)queue overlayHandler:(MGLMapSnapshotOverlayHandler)overlayHandler completionHandler:(MGLMapSnapshotCompletionHandler)completion
- (void)startWithQueue:(dispatch_queue_t)queue overlayHandler:(MLNMapSnapshotOverlayHandler)overlayHandler completionHandler:(MLNMapSnapshotCompletionHandler)completion
{
if (!completion) {
return;
}
// Ensure that offline storage has been initialized on the main thread, as MGLMapView and MGLOfflineStorage do when used directly.
// Ensure that offline storage has been initialized on the main thread, as MLNMapView and MLNOfflineStorage do when used directly.
// https://github.com/mapbox/mapbox-gl-native-ios/issues/227
if ([NSThread.currentThread isMainThread]) {
(void)[MGLOfflineStorage sharedOfflineStorage];
(void)[MLNOfflineStorage sharedOfflineStorage];
} else {
[NSException raise:NSInvalidArgumentException
format:@"-[MGLMapSnapshotter startWithQueue:completionHandler:] must be called from the main thread, not %@.", NSThread.currentThread];
format:@"-[MLNMapSnapshotter startWithQueue:completionHandler:] must be called from the main thread, not %@.", NSThread.currentThread];
}
if (self.loading) {
@@ -320,19 +320,19 @@ private:
format:@"Starting a snapshotter after application termination is not supported."];
}
MGLMapSnapshotOptions *options = [self.options copy];
MLNMapSnapshotOptions *options = [self.options copy];
[self configureWithOptions:options];
MGLLogDebug(@"Starting with options: %@", self.options);
MLNLogDebug(@"Starting with options: %@", self.options);
// Temporarily capture the snapshotter until the completion handler finishes executing, to keep standalone local usage of the snapshotter from becoming a no-op.
// POSTCONDITION: Only refer to this variable in the final result queue.
// POSTCONDITION: It is important to nil out this variable at some point in the future to avoid a leak. In cases where the completion handler gets called, the variable should be nilled out explicitly. If -cancel is called, mbgl releases the snapshot block below, causing the only remaining references to the snapshotter to go out of scope.
__block MGLMapSnapshotter *strongSelf = self;
__block MLNMapSnapshotter *strongSelf = self;
_mbglMapSnapshotter->snapshot(^(std::exception_ptr mbglError, mbgl::PremultipliedImage image, mbgl::MapSnapshotter::Attributions attributions, mbgl::MapSnapshotter::PointForFn pointForFn, mbgl::MapSnapshotter::LatLngForFn latLngForFn) {
if (mbglError) {
NSString *description = @(mbgl::util::toString(mbglError).c_str());
NSDictionary *userInfo = @{NSLocalizedDescriptionKey: description};
NSError *error = [NSError errorWithDomain:MGLErrorDomain code:MGLErrorCodeSnapshotFailed userInfo:userInfo];
NSError *error = [NSError errorWithDomain:MLNErrorDomain code:MLNErrorCodeSnapshotFailed userInfo:userInfo];
// Dispatch to result queue
dispatch_async(queue, ^{
@@ -342,9 +342,9 @@ private:
});
} else {
#if TARGET_OS_IPHONE
MGLImage *mglImage = [[MGLImage alloc] initWithMGLPremultipliedImage:std::move(image) scale:options.scale];
MLNImage *mglImage = [[MLNImage alloc] initWithMLNPremultipliedImage:std::move(image) scale:options.scale];
#else
MGLImage *mglImage = [[MGLImage alloc] initWithMGLPremultipliedImage:std::move(image)];
MLNImage *mglImage = [[MLNImage alloc] initWithMLNPremultipliedImage:std::move(image)];
mglImage.size = NSMakeSize(mglImage.size.width / options.scale,
mglImage.size.height / options.scale);
#endif
@@ -354,7 +354,7 @@ private:
dispatch_async(workQueue, ^{
// Call a function that cannot accidentally capture self.
NSError *error;
MGLMapSnapshot *snapshot = MGLSnapshotWithDecoratedImage(mglImage, options, attributions, pointForFn, latLngForFn, overlayHandler, &error);
MLNMapSnapshot *snapshot = MLNSnapshotWithDecoratedImage(mglImage, options, attributions, pointForFn, latLngForFn, overlayHandler, &error);
// Dispatch result to result queue
dispatch_async(queue, ^{
@@ -367,29 +367,29 @@ private:
});
}
MGLImage *MGLAttributedSnapshot(mbgl::MapSnapshotter::Attributions attributions, MGLImage *mglImage, MGLMapSnapshotOptions *options, void (^overlayHandler)()) {
MLNImage *MLNAttributedSnapshot(mbgl::MapSnapshotter::Attributions attributions, MLNImage *mglImage, MLNMapSnapshotOptions *options, void (^overlayHandler)()) {
NSArray<MGLAttributionInfo *> *attributionInfo = MGLAttributionInfosFromAttributions(attributions);
NSArray<MLNAttributionInfo *> *attributionInfo = MLNAttributionInfosFromAttributions(attributions);
#if TARGET_OS_IPHONE
MGLAttributionInfoStyle attributionInfoStyle = MGLAttributionInfoStyleLong;
for (NSUInteger styleValue = MGLAttributionInfoStyleLong; styleValue >= MGLAttributionInfoStyleShort; styleValue--) {
attributionInfoStyle = (MGLAttributionInfoStyle)styleValue;
CGSize attributionSize = [MGLMapSnapshotter attributionSizeWithLogoStyle:attributionInfoStyle sourceAttributionStyle:attributionInfoStyle attributionInfo:attributionInfo];
MLNAttributionInfoStyle attributionInfoStyle = MLNAttributionInfoStyleLong;
for (NSUInteger styleValue = MLNAttributionInfoStyleLong; styleValue >= MLNAttributionInfoStyleShort; styleValue--) {
attributionInfoStyle = (MLNAttributionInfoStyle)styleValue;
CGSize attributionSize = [MLNMapSnapshotter attributionSizeWithLogoStyle:attributionInfoStyle sourceAttributionStyle:attributionInfoStyle attributionInfo:attributionInfo];
if (attributionSize.width <= mglImage.size.width) {
break;
}
}
UIImage *logoImage = [MGLMapSnapshotter logoImageWithStyle:attributionInfoStyle];
CGSize attributionBackgroundSize = [MGLMapSnapshotter attributionTextSizeWithStyle:attributionInfoStyle attributionInfo:attributionInfo];
UIImage *logoImage = [MLNMapSnapshotter logoImageWithStyle:attributionInfoStyle];
CGSize attributionBackgroundSize = [MLNMapSnapshotter attributionTextSizeWithStyle:attributionInfoStyle attributionInfo:attributionInfo];
CGRect logoImageRect = CGRectMake(MGLLogoImagePosition.x, mglImage.size.height - (MGLLogoImagePosition.y + logoImage.size.height), logoImage.size.width, logoImage.size.height);
CGRect logoImageRect = CGRectMake(MLNLogoImagePosition.x, mglImage.size.height - (MLNLogoImagePosition.y + logoImage.size.height), logoImage.size.width, logoImage.size.height);
CGPoint attributionOrigin = CGPointMake(mglImage.size.width - 10 - attributionBackgroundSize.width,
logoImageRect.origin.y + (logoImageRect.size.height / 2) - (attributionBackgroundSize.height / 2) + 1);
if (!logoImage) {
CGSize defaultLogoSize = [MGLMapSnapshotter mapboxLongStyleLogo].size;
logoImageRect = CGRectMake(0, mglImage.size.height - (MGLLogoImagePosition.y + defaultLogoSize.height), 0, defaultLogoSize.height);
CGSize defaultLogoSize = [MLNMapSnapshotter mapboxLongStyleLogo].size;
logoImageRect = CGRectMake(0, mglImage.size.height - (MLNLogoImagePosition.y + defaultLogoSize.height), 0, defaultLogoSize.height);
attributionOrigin = CGPointMake(10, logoImageRect.origin.y + (logoImageRect.size.height / 2) - (attributionBackgroundSize.height / 2) + 1);
}
@@ -429,11 +429,11 @@ MGLImage *MGLAttributedSnapshot(mbgl::MapSnapshotter::Attributions attributions,
CIImage *ciAttributionImage = [[CIImage alloc] initWithCGImage:attributionImage.CGImage];
UIImage *blurredAttributionBackground = [MGLMapSnapshotter blurredAttributionBackground:ciAttributionImage];
UIImage *blurredAttributionBackground = [MLNMapSnapshotter blurredAttributionBackground:ciAttributionImage];
[blurredAttributionBackground drawInRect:attributionBackgroundFrame];
[MGLMapSnapshotter drawAttributionTextWithStyle:attributionInfoStyle origin:attributionTextPosition attributionInfo:attributionInfo];
[MLNMapSnapshotter drawAttributionTextWithStyle:attributionInfoStyle origin:attributionTextPosition attributionInfo:attributionInfo];
UIImage *compositedImage = UIGraphicsGetImageFromCurrentImageContext();
@@ -444,25 +444,25 @@ MGLImage *MGLAttributedSnapshot(mbgl::MapSnapshotter::Attributions attributions,
#else
NSRect targetFrame = { .origin = NSZeroPoint, .size = options.size };
MGLAttributionInfoStyle attributionInfoStyle = MGLAttributionInfoStyleLong;
for (NSUInteger styleValue = MGLAttributionInfoStyleLong; styleValue >= MGLAttributionInfoStyleShort; styleValue--) {
attributionInfoStyle = (MGLAttributionInfoStyle)styleValue;
CGSize attributionSize = [MGLMapSnapshotter attributionSizeWithLogoStyle:attributionInfoStyle sourceAttributionStyle:attributionInfoStyle attributionInfo:attributionInfo];
MLNAttributionInfoStyle attributionInfoStyle = MLNAttributionInfoStyleLong;
for (NSUInteger styleValue = MLNAttributionInfoStyleLong; styleValue >= MLNAttributionInfoStyleShort; styleValue--) {
attributionInfoStyle = (MLNAttributionInfoStyle)styleValue;
CGSize attributionSize = [MLNMapSnapshotter attributionSizeWithLogoStyle:attributionInfoStyle sourceAttributionStyle:attributionInfoStyle attributionInfo:attributionInfo];
if (attributionSize.width <= mglImage.size.width) {
break;
}
}
NSImage *logoImage = [MGLMapSnapshotter logoImageWithStyle:attributionInfoStyle];
CGSize attributionBackgroundSize = [MGLMapSnapshotter attributionTextSizeWithStyle:attributionInfoStyle attributionInfo:attributionInfo];
NSImage *logoImage = [MLNMapSnapshotter logoImageWithStyle:attributionInfoStyle];
CGSize attributionBackgroundSize = [MLNMapSnapshotter attributionTextSizeWithStyle:attributionInfoStyle attributionInfo:attributionInfo];
NSImage *sourceImage = mglImage;
CGRect logoImageRect = CGRectMake(MGLLogoImagePosition.x, MGLLogoImagePosition.y, logoImage.size.width, logoImage.size.height);
CGRect logoImageRect = CGRectMake(MLNLogoImagePosition.x, MLNLogoImagePosition.y, logoImage.size.width, logoImage.size.height);
CGPoint attributionOrigin = CGPointMake(targetFrame.size.width - 10 - attributionBackgroundSize.width,
MGLLogoImagePosition.y + 1);
MLNLogoImagePosition.y + 1);
if (!logoImage) {
CGSize defaultLogoSize = [MGLMapSnapshotter mapboxLongStyleLogo].size;
logoImageRect = CGRectMake(0, MGLLogoImagePosition.y, 0, defaultLogoSize.height);
CGSize defaultLogoSize = [MLNMapSnapshotter mapboxLongStyleLogo].size;
logoImageRect = CGRectMake(0, MLNLogoImagePosition.y, 0, defaultLogoSize.height);
attributionOrigin = CGPointMake(10, attributionOrigin.y);
}
@@ -501,11 +501,11 @@ MGLImage *MGLAttributedSnapshot(mbgl::MapSnapshotter::Attributions attributions,
CIImage *attributionBackgroundImage = [[CIImage alloc] initWithCGImage:[attributionBackground CGImage]];
NSImage *blurredAttributionBackground = [MGLMapSnapshotter blurredAttributionBackground:attributionBackgroundImage];
NSImage *blurredAttributionBackground = [MLNMapSnapshotter blurredAttributionBackground:attributionBackgroundImage];
[blurredAttributionBackground drawInRect:attributionBackgroundFrame];
[MGLMapSnapshotter drawAttributionTextWithStyle:attributionInfoStyle origin:attributionTextPosition attributionInfo:attributionInfo];
[MLNMapSnapshotter drawAttributionTextWithStyle:attributionInfoStyle origin:attributionTextPosition attributionInfo:attributionInfo];
[compositedImage unlockFocus];
@@ -513,8 +513,8 @@ MGLImage *MGLAttributedSnapshot(mbgl::MapSnapshotter::Attributions attributions,
#endif
}
MGLMapSnapshot *MGLSnapshotWithDecoratedImage(MGLImage *mglImage, MGLMapSnapshotOptions *options, mbgl::MapSnapshotter::Attributions attributions, mbgl::MapSnapshotter::PointForFn pointForFn, mbgl::MapSnapshotter::LatLngForFn latLngForFn, MGLMapSnapshotOverlayHandler overlayHandler, NSError * _Nullable *outError) {
MGLImage *compositedImage = MGLAttributedSnapshot(attributions, mglImage, options, ^{
MLNMapSnapshot *MLNSnapshotWithDecoratedImage(MLNImage *mglImage, MLNMapSnapshotOptions *options, mbgl::MapSnapshotter::Attributions attributions, mbgl::MapSnapshotter::PointForFn pointForFn, mbgl::MapSnapshotter::LatLngForFn latLngForFn, MLNMapSnapshotOverlayHandler overlayHandler, NSError * _Nullable *outError) {
MLNImage *compositedImage = MLNAttributedSnapshot(attributions, mglImage, options, ^{
if (!overlayHandler) {
return;
}
@@ -523,7 +523,7 @@ MGLMapSnapshot *MGLSnapshotWithDecoratedImage(MGLImage *mglImage, MGLMapSnapshot
if (!context) {
return;
}
MGLMapSnapshotOverlay *snapshotOverlay = [[MGLMapSnapshotOverlay alloc] initWithContext:context
MLNMapSnapshotOverlay *snapshotOverlay = [[MLNMapSnapshotOverlay alloc] initWithContext:context
scale:options.scale
pointForFn:pointForFn
latLngForFn:latLngForFn];
@@ -535,7 +535,7 @@ MGLMapSnapshot *MGLSnapshotWithDecoratedImage(MGLImage *mglImage, MGLMapSnapshot
if (!context) {
return;
}
MGLMapSnapshotOverlay *snapshotOverlay = [[MGLMapSnapshotOverlay alloc] initWithContext:context.CGContext
MLNMapSnapshotOverlay *snapshotOverlay = [[MLNMapSnapshotOverlay alloc] initWithContext:context.CGContext
scale:options.scale
pointForFn:pointForFn
latLngForFn:latLngForFn];
@@ -546,22 +546,22 @@ MGLMapSnapshot *MGLSnapshotWithDecoratedImage(MGLImage *mglImage, MGLMapSnapshot
});
if (compositedImage) {
return [[MGLMapSnapshot alloc] initWithImage:compositedImage
return [[MLNMapSnapshot alloc] initWithImage:compositedImage
scale:options.scale
pointForFn:pointForFn
latLngForFn:latLngForFn];
} else {
if (outError) {
NSDictionary *userInfo = @{NSLocalizedDescriptionKey: @"Failed to generate composited snapshot."};
*outError = [NSError errorWithDomain:MGLErrorDomain
code:MGLErrorCodeSnapshotFailed
*outError = [NSError errorWithDomain:MLNErrorDomain
code:MLNErrorCodeSnapshotFailed
userInfo:userInfo];
}
return nil;
}
}
NSArray<MGLAttributionInfo *> *MGLAttributionInfosFromAttributions(mbgl::MapSnapshotter::Attributions attributions) {
NSArray<MLNAttributionInfo *> *MLNAttributionInfosFromAttributions(mbgl::MapSnapshotter::Attributions attributions) {
NSMutableArray *infos = [NSMutableArray array];
#if TARGET_OS_IPHONE
@@ -573,7 +573,7 @@ NSArray<MGLAttributionInfo *> *MGLAttributionInfosFromAttributions(mbgl::MapSnap
#endif
for (auto attribution : attributions) {
NSString *attributionHTMLString = @(attribution.c_str());
NSArray *tileSetInfos = [MGLAttributionInfo attributionInfosFromHTMLString:attributionHTMLString
NSArray *tileSetInfos = [MLNAttributionInfo attributionInfosFromHTMLString:attributionHTMLString
fontSize:fontSize
linkColor:attributeFontColor];
[infos growArrayByAddingAttributionInfosFromArray:tileSetInfos];
@@ -581,9 +581,9 @@ NSArray<MGLAttributionInfo *> *MGLAttributionInfosFromAttributions(mbgl::MapSnap
return infos;
}
+ (void)drawAttributionTextWithStyle:(MGLAttributionInfoStyle)attributionInfoStyle origin:(CGPoint)origin attributionInfo:(NSArray<MGLAttributionInfo *>*)attributionInfo
+ (void)drawAttributionTextWithStyle:(MLNAttributionInfoStyle)attributionInfoStyle origin:(CGPoint)origin attributionInfo:(NSArray<MLNAttributionInfo *>*)attributionInfo
{
for (MGLAttributionInfo *info in attributionInfo) {
for (MLNAttributionInfo *info in attributionInfo) {
if (info.isFeedbackLink) {
continue;
}
@@ -594,7 +594,7 @@ NSArray<MGLAttributionInfo *> *MGLAttributionInfosFromAttributions(mbgl::MapSnap
}
}
+ (MGLImage *)blurredAttributionBackground:(CIImage *)backgroundImage
+ (MLNImage *)blurredAttributionBackground:(CIImage *)backgroundImage
{
CGAffineTransform transform = CGAffineTransformIdentity;
CIFilter *clamp = [CIFilter filterWithName:@"CIAffineClamp"];
@@ -613,7 +613,7 @@ NSArray<MGLAttributionInfo *> *MGLAttributionInfosFromAttributions(mbgl::MapSnap
CIContext *ctx = [CIContext contextWithOptions:nil];
CGImageRef cgimg = [ctx createCGImage:blurredImage fromRect:[backgroundImage extent]];
MGLImage *image;
MLNImage *image;
#if TARGET_OS_IPHONE
image = [UIImage imageWithCGImage:cgimg];
@@ -625,30 +625,30 @@ NSArray<MGLAttributionInfo *> *MGLAttributionInfosFromAttributions(mbgl::MapSnap
return image;
}
+ (MGLImage *)logoImageWithStyle:(MGLAttributionInfoStyle)style
+ (MLNImage *)logoImageWithStyle:(MLNAttributionInfoStyle)style
{
MGLImage *logoImage;
MLNImage *logoImage;
switch (style) {
case MGLAttributionInfoStyleLong:
logoImage = [MGLMapSnapshotter mapboxLongStyleLogo];
case MLNAttributionInfoStyleLong:
logoImage = [MLNMapSnapshotter mapboxLongStyleLogo];
break;
case MGLAttributionInfoStyleMedium:
case MLNAttributionInfoStyleMedium:
#if TARGET_OS_IPHONE
logoImage = [UIImage imageNamed:@"mapbox_helmet" inBundle:[NSBundle mgl_frameworkBundle] compatibleWithTraitCollection:nil];
#else
logoImage = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mgl_frameworkBundle] pathForResource:@"mapbox_helmet" ofType:@"pdf"]];
#endif
break;
case MGLAttributionInfoStyleShort:
case MLNAttributionInfoStyleShort:
logoImage = nil;
break;
}
return logoImage;
}
+ (MGLImage *)mapboxLongStyleLogo
+ (MLNImage *)mapboxLongStyleLogo
{
MGLImage *logoImage;
MLNImage *logoImage;
#if TARGET_OS_IPHONE
logoImage =[UIImage imageNamed:@"mapbox" inBundle:[NSBundle mgl_frameworkBundle] compatibleWithTraitCollection:nil];
#else
@@ -657,16 +657,16 @@ NSArray<MGLAttributionInfo *> *MGLAttributionInfosFromAttributions(mbgl::MapSnap
return logoImage;
}
+ (CGSize)attributionSizeWithLogoStyle:(MGLAttributionInfoStyle)logoStyle sourceAttributionStyle:(MGLAttributionInfoStyle)attributionStyle attributionInfo:(NSArray<MGLAttributionInfo *>*)attributionInfo
+ (CGSize)attributionSizeWithLogoStyle:(MLNAttributionInfoStyle)logoStyle sourceAttributionStyle:(MLNAttributionInfoStyle)attributionStyle attributionInfo:(NSArray<MLNAttributionInfo *>*)attributionInfo
{
MGLImage *logoImage = [self logoImageWithStyle:logoStyle];
MLNImage *logoImage = [self logoImageWithStyle:logoStyle];
CGSize attributionBackgroundSize = [MGLMapSnapshotter attributionTextSizeWithStyle:attributionStyle attributionInfo:attributionInfo];
CGSize attributionBackgroundSize = [MLNMapSnapshotter attributionTextSizeWithStyle:attributionStyle attributionInfo:attributionInfo];
CGSize attributionSize = CGSizeZero;
if (logoImage) {
attributionSize.width = MGLLogoImagePosition.x + logoImage.size.width + 10;
attributionSize.width = MLNLogoImagePosition.x + logoImage.size.width + 10;
}
attributionSize.width = attributionSize.width + 10 + attributionBackgroundSize.width + 10;
attributionSize.height = MAX(logoImage.size.height, attributionBackgroundSize.height);
@@ -674,10 +674,10 @@ NSArray<MGLAttributionInfo *> *MGLAttributionInfosFromAttributions(mbgl::MapSnap
return attributionSize;
}
+ (CGSize)attributionTextSizeWithStyle:(MGLAttributionInfoStyle)attributionStyle attributionInfo:(NSArray<MGLAttributionInfo *>*)attributionInfo
+ (CGSize)attributionTextSizeWithStyle:(MLNAttributionInfoStyle)attributionStyle attributionInfo:(NSArray<MLNAttributionInfo *>*)attributionInfo
{
CGSize attributionBackgroundSize = CGSizeMake(10, 0);
for (MGLAttributionInfo *info in attributionInfo) {
for (MLNAttributionInfo *info in attributionInfo) {
if (info.isFeedbackLink) {
continue;
}
@@ -691,7 +691,7 @@ NSArray<MGLAttributionInfo *> *MGLAttributionInfosFromAttributions(mbgl::MapSnap
- (void)cancel
{
MGLLogInfo(@"Cancelling snapshotter.");
MLNLogInfo(@"Cancelling snapshotter.");
if (_mbglMapSnapshotter) {
_mbglMapSnapshotter->cancel();
@@ -700,37 +700,37 @@ NSArray<MGLAttributionInfo *> *MGLAttributionInfosFromAttributions(mbgl::MapSnap
_delegateHost.reset();
}
- (void)configureWithOptions:(MGLMapSnapshotOptions *)options {
auto mbglFileSource = [[MGLOfflineStorage sharedOfflineStorage] mbglFileSource];
- (void)configureWithOptions:(MLNMapSnapshotOptions *)options {
auto mbglFileSource = [[MLNOfflineStorage sharedOfflineStorage] mbglFileSource];
// Size; taking into account the minimum texture size for OpenGL ES
// For non retina screens the ratio is 1:1 MGLSnapshotterMinimumPixelSize
// For non retina screens the ratio is 1:1 MLNSnapshotterMinimumPixelSize
mbgl::Size size = {
static_cast<uint32_t>(MAX(options.size.width, MGLSnapshotterMinimumPixelSize)),
static_cast<uint32_t>(MAX(options.size.height, MGLSnapshotterMinimumPixelSize))
static_cast<uint32_t>(MAX(options.size.width, MLNSnapshotterMinimumPixelSize)),
static_cast<uint32_t>(MAX(options.size.height, MLNSnapshotterMinimumPixelSize))
};
float pixelRatio = MAX(options.scale, 1);
// App-global configuration
MGLRendererConfiguration *config = [MGLRendererConfiguration currentConfiguration];
MLNRendererConfiguration *config = [MLNRendererConfiguration currentConfiguration];
auto tileServerOptions = [[MGLSettings sharedSettings] tileServerOptionsInternal];
auto tileServerOptions = [[MLNSettings sharedSettings] tileServerOptionsInternal];
mbgl::ResourceOptions resourceOptions;
resourceOptions
.withTileServerOptions(*tileServerOptions)
.withCachePath(MGLOfflineStorage.sharedOfflineStorage.databasePath.UTF8String)
.withCachePath(MLNOfflineStorage.sharedOfflineStorage.databasePath.UTF8String)
.withAssetPath(NSBundle.mainBundle.resourceURL.path.UTF8String);
mbgl::ClientOptions clientOptions;
auto apiKey = [[MGLSettings sharedSettings] apiKey];
auto apiKey = [[MLNSettings sharedSettings] apiKey];
if (apiKey) {
resourceOptions.withApiKey([apiKey UTF8String]);
}
// Create the snapshotter
auto localFontFamilyName = config.localFontFamilyName ? std::string(config.localFontFamilyName.UTF8String) : nullptr;
_delegateHost = std::make_unique<MGLMapSnapshotterDelegateHost>(self);
_delegateHost = std::make_unique<MLNMapSnapshotterDelegateHost>(self);
_mbglMapSnapshotter = std::make_unique<mbgl::MapSnapshotter>(
size, pixelRatio, resourceOptions, clientOptions, *_delegateHost, localFontFamilyName);
@@ -739,7 +739,7 @@ NSArray<MGLAttributionInfo *> *MGLAttributionInfosFromAttributions(mbgl::MapSnap
// Camera options
mbgl::CameraOptions cameraOptions;
if (CLLocationCoordinate2DIsValid(options.camera.centerCoordinate)) {
cameraOptions.center = MGLLatLngFromLocationCoordinate2D(options.camera.centerCoordinate);
cameraOptions.center = MLNLatLngFromLocationCoordinate2D(options.camera.centerCoordinate);
}
if (options.camera.heading >= 0) {
cameraOptions.bearing = MAX(0, options.camera.heading);
@@ -755,16 +755,16 @@ NSArray<MGLAttributionInfo *> *MGLAttributionInfosFromAttributions(mbgl::MapSnap
}
// Region
if (!MGLCoordinateBoundsIsEmpty(options.coordinateBounds)) {
_mbglMapSnapshotter->setRegion(MGLLatLngBoundsFromCoordinateBounds(options.coordinateBounds));
if (!MLNCoordinateBoundsIsEmpty(options.coordinateBounds)) {
_mbglMapSnapshotter->setRegion(MLNLatLngBoundsFromCoordinateBounds(options.coordinateBounds));
}
}
- (MGLStyle *)style {
- (MLNStyle *)style {
if (!_mbglMapSnapshotter) {
return nil;
}
return [[MGLStyle alloc] initWithRawStyle:&_mbglMapSnapshotter->getStyle() stylable:self];
return [[MLNStyle alloc] initWithRawStyle:&_mbglMapSnapshotter->getStyle() stylable:self];
}
@end

View File

@@ -1,6 +1,6 @@
#import "MGLMapSnapshotter.h"
#import "MLNMapSnapshotter.h"
@protocol MGLMapSnapshotProtocol <NSObject>
@protocol MLNMapSnapshotProtocol <NSObject>
#if TARGET_OS_IPHONE
- (CGPoint)pointForCoordinate:(CLLocationCoordinate2D)coordinate;

View File

@@ -1,26 +1,26 @@
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#import "MGLFoundation.h"
#import "MGLShape.h"
#import "MLNFoundation.h"
#import "MLNShape.h"
NS_ASSUME_NONNULL_BEGIN
/**
The `MGLMultiPoint` class is an abstract superclass used to define shapes
The `MLNMultiPoint` class is an abstract superclass used to define shapes
composed of multiple vertices.
Create instances of `MGLPolyline` or `MGLPolygon` in order to use
properties of `MGLMultiPoint`. Do not create instances of `MGLMultiPoint`
Create instances of `MLNPolyline` or `MLNPolygon` in order to use
properties of `MLNMultiPoint`. Do not create instances of `MLNMultiPoint`
directly and do not create your own subclasses of this class. You can use
the method and properties of this class to access information about the
vertices of the line or polygon.
Do not confuse `MGLMultiPoint` with `MGLPointCollection`, which represents a
Do not confuse `MLNMultiPoint` with `MLNPointCollection`, which represents a
collection of related but disconnected points.
*/
MGL_EXPORT
@interface MGLMultiPoint : MGLShape
MLN_EXPORT
@interface MLNMultiPoint : MLNShape
/**
The array of vertices associated with the shape.
@@ -62,8 +62,8 @@ MGL_EXPORT
Inserts the given vertices into the shape.
If the shape is currently visible on the map as an annotation, it is redrawn
immediately. If the shape is part of an `MGLShapeSource` object, you must
explicitly set the `MGLShapeSource.shape` property in order for any style
immediately. If the shape is part of an `MLNShapeSource` object, you must
explicitly set the `MLNShapeSource.shape` property in order for any style
layers that use the source to be redrawn.
@param coords The array of coordinates to insert into the shape. The data in
@@ -78,8 +78,8 @@ MGL_EXPORT
Appends the given vertices to the shape.
If the shape is currently visible on the map as an annotation, it is redrawn
immediately. If the shape is part of an `MGLShapeSource` object, you must
explicitly set the `MGLShapeSource.shape` property in order for any style
immediately. If the shape is part of an `MLNShapeSource` object, you must
explicitly set the `MLNShapeSource.shape` property in order for any style
layers that use the source to be redrawn.
@param coords The array of coordinates to add to the shape. The data in this
@@ -93,8 +93,8 @@ MGL_EXPORT
vertices from a given C array.
If the shape is currently visible on the map as an annotation, it is redrawn
immediately. If the shape is part of an `MGLShapeSource` object, you must
explicitly set the `MGLShapeSource.shape` property in order for any style
immediately. If the shape is part of an `MLNShapeSource` object, you must
explicitly set the `MLNShapeSource.shape` property in order for any style
layers that use the source to be redrawn.
The number of coordinates in `coords` must be equal to the length of `range`.
@@ -119,8 +119,8 @@ MGL_EXPORT
of vertices from a given C array.
If the shape is currently visible on the map as an annotation, it is redrawn
immediately. If the shape is part of an `MGLShapeSource` object, you must
explicitly set the `MGLShapeSource.shape` property in order for any style
immediately. If the shape is part of an `MLNShapeSource` object, you must
explicitly set the `MLNShapeSource.shape` property in order for any style
layers that use the source to be redrawn.
If `count` is greater than the `length` field of `range`, some vertices will
@@ -148,8 +148,8 @@ MGL_EXPORT
Removes the vertices at the given range from the shape.
If the shape is currently visible on the map as an annotation, it is redrawn
immediately. If the shape is part of an `MGLShapeSource` object, you must
explicitly set the `MGLShapeSource.shape` property in order for any style
immediately. If the shape is part of an `MLNShapeSource` object, you must
explicitly set the `MLNShapeSource.shape` property in order for any style
layers that use the source to be redrawn.
If `range` extends beyond the shape’s `coordinates` property, an

View File

@@ -1,11 +1,11 @@
#import "MGLMultiPoint_Private.h"
#import "MGLGeometry_Private.h"
#import "MGLShape_Private.h"
#import "NSCoder+MGLAdditions.h"
#import "MGLTypes.h"
#import "MGLLoggingConfiguration_Private.h"
#import "MLNMultiPoint_Private.h"
#import "MLNGeometry_Private.h"
#import "MLNShape_Private.h"
#import "NSCoder+MLNAdditions.h"
#import "MLNTypes.h"
#import "MLNLoggingConfiguration_Private.h"
@implementation MGLMultiPoint
@implementation MLNMultiPoint
{
std::optional<mbgl::LatLngBounds> _bounds;
std::vector<CLLocationCoordinate2D> _coordinates;
@@ -13,7 +13,7 @@
- (instancetype)initWithCoordinates:(const CLLocationCoordinate2D *)coords count:(NSUInteger)count
{
MGLLogDebug(@"Initializing with %lu coordinates.", (unsigned long) count);
MLNLogDebug(@"Initializing with %lu coordinates.", (unsigned long) count);
self = [super init];
if (self)
@@ -30,7 +30,7 @@
- (instancetype)initWithCoder:(NSCoder *)decoder
{
MGLLogInfo(@"Initializing with coder.");
MLNLogInfo(@"Initializing with coder.");
if (self = [super initWithCoder:decoder]) {
_coordinates = [decoder mgl_decodeLocationCoordinates2DForKey:@"coordinates"];
}
@@ -46,9 +46,9 @@
- (BOOL)isEqual:(id)other
{
if (self == other) return YES;
if (![other isKindOfClass:[MGLMultiPoint class]]) return NO;
if (![other isKindOfClass:[MLNMultiPoint class]]) return NO;
MGLMultiPoint *otherMultipoint = other;
MLNMultiPoint *otherMultipoint = other;
return ([super isEqual:otherMultipoint]
&& _coordinates == otherMultipoint->_coordinates);
}
@@ -64,7 +64,7 @@
- (CLLocationCoordinate2D)coordinate
{
MGLAssert([self pointCount] > 0, @"A multipoint must have coordinates");
MLNAssert([self pointCount] > 0, @"A multipoint must have coordinates");
return _coordinates.at(0);
}
@@ -96,7 +96,7 @@
}
- (void)setCoordinates:(CLLocationCoordinate2D *)coords count:(NSUInteger)count {
MGLLogDebug(@"Setting: %lu coordinates.", (unsigned long)count);
MLNLogDebug(@"Setting: %lu coordinates.", (unsigned long)count);
if (!count) {
[NSException raise:NSInvalidArgumentException
format:@"A multipoint must have at least one vertex."];
@@ -109,7 +109,7 @@
}
- (void)insertCoordinates:(const CLLocationCoordinate2D *)coords count:(NSUInteger)count atIndex:(NSUInteger)index {
MGLLogDebug(@"Inserting %lu coordinates at index %lu.", (unsigned long)count, (unsigned long)index);
MLNLogDebug(@"Inserting %lu coordinates at index %lu.", (unsigned long)count, (unsigned long)index);
if (!count) {
return;
}
@@ -128,18 +128,18 @@
- (void)appendCoordinates:(const CLLocationCoordinate2D *)coords count:(NSUInteger)count
{
MGLLogDebug(@"Appending %lu coordinates.", (unsigned long)count);
MLNLogDebug(@"Appending %lu coordinates.", (unsigned long)count);
[self insertCoordinates:coords count:count atIndex:_coordinates.size()];
}
- (void)replaceCoordinatesInRange:(NSRange)range withCoordinates:(const CLLocationCoordinate2D *)coords
{
MGLLogDebug(@"Replacing coordinates in range: %@", NSStringFromRange(range));
MLNLogDebug(@"Replacing coordinates in range: %@", NSStringFromRange(range));
[self replaceCoordinatesInRange:range withCoordinates:coords count:range.length];
}
- (void)replaceCoordinatesInRange:(NSRange)range withCoordinates:(const CLLocationCoordinate2D *)coords count:(NSUInteger)count {
MGLLogDebug(@"Replacing %lu coordinates in range %@.", (unsigned long)count, NSStringFromRange(range));
MLNLogDebug(@"Replacing %lu coordinates in range %@.", (unsigned long)count, NSStringFromRange(range));
if (!count && !range.length) {
return;
}
@@ -162,35 +162,35 @@
}
- (void)removeCoordinatesInRange:(NSRange)range {
MGLLogDebug(@"Removing coordinatesInRange: %@", NSStringFromRange(range));
MLNLogDebug(@"Removing coordinatesInRange: %@", NSStringFromRange(range));
CLLocationCoordinate2D coords;
[self replaceCoordinatesInRange:range withCoordinates:&coords count:0];
}
- (MGLCoordinateBounds)overlayBounds
- (MLNCoordinateBounds)overlayBounds
{
if (!_bounds) {
mbgl::LatLngBounds bounds = mbgl::LatLngBounds::empty();
for (auto coordinate : _coordinates) {
if (!MGLLocationCoordinate2DIsValid(coordinate)) {
if (!MLNLocationCoordinate2DIsValid(coordinate)) {
bounds = mbgl::LatLngBounds::empty();
break;
}
bounds.extend(MGLLatLngFromLocationCoordinate2D(coordinate));
bounds.extend(MLNLatLngFromLocationCoordinate2D(coordinate));
}
_bounds = bounds;
}
return MGLCoordinateBoundsFromLatLngBounds(*_bounds);
return MLNCoordinateBoundsFromLatLngBounds(*_bounds);
}
- (BOOL)intersectsOverlayBounds:(MGLCoordinateBounds)overlayBounds
- (BOOL)intersectsOverlayBounds:(MLNCoordinateBounds)overlayBounds
{
return MGLCoordinateBoundsIntersectsCoordinateBounds(self.overlayBounds, overlayBounds);
return MLNCoordinateBoundsIntersectsCoordinateBounds(self.overlayBounds, overlayBounds);
}
- (mbgl::Annotation)annotationObjectWithDelegate:(__unused id <MGLMultiPointDelegate>)delegate
- (mbgl::Annotation)annotationObjectWithDelegate:(__unused id <MLNMultiPointDelegate>)delegate
{
MGLAssert(NO, @"Cannot add an annotation from an instance of %@", NSStringFromClass([self class]));
MLNAssert(NO, @"Cannot add an annotation from an instance of %@", NSStringFromClass([self class]));
return mbgl::SymbolAnnotation(mbgl::Point<double>());
}
@@ -198,7 +198,7 @@
{
return [NSString stringWithFormat:@"<%@: %p; count = %lu; bounds = %@>",
NSStringFromClass([self class]), (void *)self, (unsigned long)[self pointCount],
MGLStringFromCoordinateBounds(self.overlayBounds)];
MLNStringFromCoordinateBounds(self.overlayBounds)];
}
@end

View File

@@ -1,6 +1,6 @@
#import "MGLMultiPoint.h"
#import "MLNMultiPoint.h"
#import "MGLGeometry.h"
#import "MLNGeometry.h"
#import <mbgl/annotation/annotation.hpp>
#import <mbgl/util/feature.hpp>
@@ -11,35 +11,35 @@
NS_ASSUME_NONNULL_BEGIN
@class MGLPolygon;
@class MGLPolyline;
@class MLNPolygon;
@class MLNPolyline;
@protocol MGLMultiPointDelegate;
@protocol MLNMultiPointDelegate;
@interface MGLMultiPoint (Private)
@interface MLNMultiPoint (Private)
- (instancetype)initWithCoordinates:(const CLLocationCoordinate2D *)coords count:(NSUInteger)count;
- (BOOL)intersectsOverlayBounds:(MGLCoordinateBounds)overlayBounds;
- (BOOL)intersectsOverlayBounds:(MLNCoordinateBounds)overlayBounds;
/** Constructs a shape annotation object, asking the delegate for style values. */
- (mbgl::Annotation)annotationObjectWithDelegate:(id <MGLMultiPointDelegate>)delegate;
- (mbgl::Annotation)annotationObjectWithDelegate:(id <MLNMultiPointDelegate>)delegate;
@end
/** An object that tells the MGLMultiPoint instance how to style itself. */
@protocol MGLMultiPointDelegate <NSObject>
/** An object that tells the MLNMultiPoint instance how to style itself. */
@protocol MLNMultiPointDelegate <NSObject>
/** Returns the fill alpha value for the given annotation. */
- (double)alphaForShapeAnnotation:(MGLShape *)annotation;
- (double)alphaForShapeAnnotation:(MLNShape *)annotation;
/** Returns the stroke color object for the given annotation. */
- (mbgl::Color)strokeColorForShapeAnnotation:(MGLShape *)annotation;
- (mbgl::Color)strokeColorForShapeAnnotation:(MLNShape *)annotation;
/** Returns the fill color object for the given annotation. */
- (mbgl::Color)fillColorForPolygonAnnotation:(MGLPolygon *)annotation;
- (mbgl::Color)fillColorForPolygonAnnotation:(MLNPolygon *)annotation;
/** Returns the stroke width object for the given annotation. */
- (CGFloat)lineWidthForPolylineAnnotation:(MGLPolyline *)annotation;
- (CGFloat)lineWidthForPolylineAnnotation:(MLNPolyline *)annotation;
@end

View File

@@ -1,17 +1,17 @@
#import <Foundation/Foundation.h>
#import "MGLFoundation.h"
#import "MLNFoundation.h"
NS_ASSUME_NONNULL_BEGIN
@class MGLNetworkConfiguration;
@class MLNNetworkConfiguration;
@protocol MGLNetworkConfigurationDelegate <NSObject>
@protocol MLNNetworkConfigurationDelegate <NSObject>
@optional
/**
:nodoc:
Provides an `NSURLSession` object for the specified `MGLNetworkConfiguration`.
Provides an `NSURLSession` object for the specified `MLNNetworkConfiguration`.
This API should be considered experimental, likely to be removed or changed in
future releases.
@@ -23,27 +23,27 @@ NS_ASSUME_NONNULL_BEGIN
and sessions created with a delegate that conforms to `NSURLSessionDataDelegate`
are not supported at this time.
*/
- (NSURLSession *)sessionForNetworkConfiguration:(MGLNetworkConfiguration *)configuration;
- (NSURLSession *)sessionForNetworkConfiguration:(MLNNetworkConfiguration *)configuration;
@end
/**
The `MGLNetworkConfiguration` object provides a global way to set a base
The `MLNNetworkConfiguration` object provides a global way to set a base
`NSURLSessionConfiguration`, and other resources.
*/
MGL_EXPORT
@interface MGLNetworkConfiguration : NSObject
MLN_EXPORT
@interface MLNNetworkConfiguration : NSObject
/**
:nodoc:
Delegate for the `MGLNetworkConfiguration` class.
Delegate for the `MLNNetworkConfiguration` class.
*/
@property (nonatomic, weak) id<MGLNetworkConfigurationDelegate> delegate;
@property (nonatomic, weak) id<MLNNetworkConfigurationDelegate> delegate;
/**
Returns the shared instance of the `MGLNetworkConfiguration` class.
Returns the shared instance of the `MLNNetworkConfiguration` class.
*/
@property (class, nonatomic, readonly) MGLNetworkConfiguration *sharedManager;
@property (class, nonatomic, readonly) MLNNetworkConfiguration *sharedManager;
/**
The session configuration object that is used by the `NSURLSession` objects
@@ -52,8 +52,8 @@ MGL_EXPORT
If this property is set to nil or if no session configuration is provided this property
is set to the default session configuration.
Assign this object before instantiating any `MGLMapView` object, or using
`MGLOfflineStorage`
Assign this object before instantiating any `MLNMapView` object, or using
`MLNOfflineStorage`
@note `NSURLSession` objects store a copy of this configuration. Any further changes
to mutable properties on this configuration object passed to a session’s initializer

View File

@@ -1,24 +1,24 @@
#import "MGLNetworkConfiguration_Private.h"
#import "MGLLoggingConfiguration_Private.h"
#import "MLNNetworkConfiguration_Private.h"
#import "MLNLoggingConfiguration_Private.h"
#if TARGET_OS_IPHONE || TARGET_OS_SIMULATOR
#import "MGLSettings_Private.h"
#import "MLNSettings_Private.h"
#endif
#import "MGLReachability.h"
#import "MLNReachability.h"
static NSString * const MGLStartTime = @"start_time";
static NSString * const MGLResourceType = @"resource_type";
NSString * const kMGLDownloadPerformanceEvent = @"mobile.performance_trace";
static NSString * const MLNStartTime = @"start_time";
static NSString * const MLNResourceType = @"resource_type";
NSString * const kMLNDownloadPerformanceEvent = @"mobile.performance_trace";
@interface MGLNetworkConfiguration () <MGLNativeNetworkDelegate>
@interface MLNNetworkConfiguration () <MLNNativeNetworkDelegate>
@property (nonatomic, strong) NSMutableDictionary<NSString *, NSDictionary*> *events;
@property (nonatomic, weak) id<MGLNetworkConfigurationMetricsDelegate> metricsDelegate;
@property (nonatomic, weak) id<MLNNetworkConfigurationMetricsDelegate> metricsDelegate;
@property (nonatomic) dispatch_queue_t eventsQueue;
@end
@implementation MGLNetworkConfiguration
@implementation MLNNetworkConfiguration
{
NSURLSessionConfiguration *_sessionConfig;
}
@@ -35,7 +35,7 @@ NSString * const kMGLDownloadPerformanceEvent = @"mobile.performance_trace";
+ (instancetype)sharedManager {
static dispatch_once_t onceToken;
static MGLNetworkConfiguration *_sharedManager;
static MLNNetworkConfiguration *_sharedManager;
dispatch_once(&onceToken, ^{
_sharedManager = [[self alloc] init];
});
@@ -50,7 +50,7 @@ NSString * const kMGLDownloadPerformanceEvent = @"mobile.performance_trace";
- (void)resetNativeNetworkManagerDelegate {
// Tell core about our network integration. `delegate` here is not (yet)
// intended to be set to nil, except for testing.
[MGLNativeNetworkManager sharedManager].delegate = self;
[MLNNativeNetworkManager sharedManager].delegate = self;
}
+ (NSURLSessionConfiguration *)defaultSessionConfiguration {
@@ -64,9 +64,9 @@ NSString * const kMGLDownloadPerformanceEvent = @"mobile.performance_trace";
return sessionConfiguration;
}
// MARK: - MGLNativeNetworkDelegate
// MARK: - MLNNativeNetworkDelegate
- (NSURLSession *)sessionForNetworkManager:(MGLNativeNetworkManager *)networkManager {
- (NSURLSession *)sessionForNetworkManager:(MLNNativeNetworkManager *)networkManager {
// Note: this method is NOT called on the main thread.
NSURLSession *session;
if ([self.delegate respondsToSelector:@selector(sessionForNetworkConfiguration:)]) {
@@ -98,7 +98,7 @@ NSString * const kMGLDownloadPerformanceEvent = @"mobile.performance_trace";
- (void)setSessionConfiguration:(NSURLSessionConfiguration *)sessionConfiguration {
@synchronized (self) {
if (sessionConfiguration == nil) {
_sessionConfig = [MGLNetworkConfiguration defaultSessionConfiguration];
_sessionConfig = [MLNNetworkConfiguration defaultSessionConfiguration];
} else {
_sessionConfig = sessionConfiguration;
}
@@ -108,7 +108,7 @@ NSString * const kMGLDownloadPerformanceEvent = @"mobile.performance_trace";
- (void)startDownloadEvent:(NSString *)urlString type:(NSString *)resourceType {
if (urlString && resourceType && ![self eventDictionaryForKey:urlString]) {
NSDate *startDate = [NSDate date];
[self setEventDictionary:@{ MGLStartTime: startDate, MGLResourceType: resourceType }
[self setEventDictionary:@{ MLNStartTime: startDate, MLNResourceType: resourceType }
forKey:urlString];
}
}
@@ -122,11 +122,11 @@ NSString * const kMGLDownloadPerformanceEvent = @"mobile.performance_trace";
}
- (void)debugLog:(NSString *)message {
MGLLogDebug(message);
MLNLogDebug(message);
}
- (void)errorLog:(NSString *)message {
MGLLogError(message);
MLNLogError(message);
}
// MARK: - Event management
@@ -150,7 +150,7 @@ NSString * const kMGLDownloadPerformanceEvent = @"mobile.performance_trace";
{
NSString *urlString = response.URL.relativePath;
NSDictionary *parameters = [self eventDictionaryForKey:urlString];
NSDate *startDate = [parameters objectForKey:MGLStartTime];
NSDate *startDate = [parameters objectForKey:MLNStartTime];
NSDate *endDate = [NSDate date];
NSTimeInterval elapsedTime = [endDate timeIntervalSinceDate:startDate];
NSDateFormatter* iso8601Formatter = [[NSDateFormatter alloc] init];
@@ -159,14 +159,14 @@ NSString * const kMGLDownloadPerformanceEvent = @"mobile.performance_trace";
NSMutableArray *attributes = [NSMutableArray array];
[attributes addObject:@{ @"name" : @"requestUrl" , @"value" : urlString }];
[attributes addObject:@{ @"name" : MGLResourceType , @"value" : [parameters objectForKey:MGLResourceType] }];
[attributes addObject:@{ @"name" : MLNResourceType , @"value" : [parameters objectForKey:MLNResourceType] }];
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
[attributes addObject:@{ @"name" : @"responseCode", @"value" : @(responseCode)}];
}
BOOL isWIFIOn = [[MGLReachability reachabilityWithHostName:response.URL.host] isReachableViaWiFi];
BOOL isWIFIOn = [[MLNReachability reachabilityWithHostName:response.URL.host] isReachableViaWiFi];
[attributes addObject:@{ @"name" : @"wifiOn", @"value" : @(isWIFIOn)}];
if (action) {
@@ -176,7 +176,7 @@ NSString * const kMGLDownloadPerformanceEvent = @"mobile.performance_trace";
double elapsedTimeInMS = elapsedTime * 1000.0;
return @{
@"event" : kMGLDownloadPerformanceEvent,
@"event" : kMLNDownloadPerformanceEvent,
@"created" : createdDate,
@"sessionId" : [NSUUID UUID].UUIDString,
@"counters" : @[ @{ @"name" : @"elapsedMS" , @"value" : @(elapsedTimeInMS) } ],
@@ -210,14 +210,14 @@ NSString * const kMGLDownloadPerformanceEvent = @"mobile.performance_trace";
@end
@implementation MGLNetworkConfiguration (ForTesting)
@implementation MLNNetworkConfiguration (ForTesting)
+ (void)testing_clearNativeNetworkManagerDelegate {
[MGLNativeNetworkManager sharedManager].delegate = nil;
[MLNNativeNetworkManager sharedManager].delegate = nil;
}
+ (id)testing_nativeNetworkManagerDelegate {
return [MGLNativeNetworkManager sharedManager].delegate;
return [MLNNativeNetworkManager sharedManager].delegate;
}
@end

View File

@@ -1,21 +1,21 @@
#import "MGLNetworkConfiguration.h"
#import "MLNNetworkConfiguration.h"
#include <mbgl/interface/native_apple_interface.h>
NS_ASSUME_NONNULL_BEGIN
@class MGLNetworkConfiguration;
@protocol MGLNetworkConfigurationMetricsDelegate <NSObject>
@class MLNNetworkConfiguration;
@protocol MLNNetworkConfigurationMetricsDelegate <NSObject>
- (void)networkConfiguration:(MGLNetworkConfiguration *)networkConfiguration didGenerateMetricEvent:(NSDictionary *)metricEvent;
- (void)networkConfiguration:(MLNNetworkConfiguration *)networkConfiguration didGenerateMetricEvent:(NSDictionary *)metricEvent;
@end
extern NSString * const kMGLDownloadPerformanceEvent;
extern NSString * const kMLNDownloadPerformanceEvent;
@interface MGLNetworkConfiguration (Private)
@interface MLNNetworkConfiguration (Private)
@property (nonatomic, strong) NSMutableDictionary<NSString*, NSDictionary*> *events;
@property (nonatomic, weak) id<MGLNetworkConfigurationMetricsDelegate> metricsDelegate;
@property (nonatomic, weak) id<MLNNetworkConfigurationMetricsDelegate> metricsDelegate;
- (void)resetNativeNetworkManagerDelegate;
- (void)startDownloadEvent:(NSString *)urlString type:(NSString *)resourceType;

View File

@@ -1,63 +1,63 @@
#import <Foundation/Foundation.h>
#import "MGLFoundation.h"
#import "MGLTypes.h"
#import "MGLOfflineRegion.h"
#import "MLNFoundation.h"
#import "MLNTypes.h"
#import "MLNOfflineRegion.h"
NS_ASSUME_NONNULL_BEGIN
FOUNDATION_EXTERN MGL_EXPORT MGLExceptionName const MGLInvalidOfflinePackException;
FOUNDATION_EXTERN MLN_EXPORT MLNExceptionName const MLNInvalidOfflinePackException;
/**
The state an offline pack is currently in.
*/
typedef NS_ENUM (NSInteger, MGLOfflinePackState) {
typedef NS_ENUM (NSInteger, MLNOfflinePackState) {
/**
It is unknown whether the pack is inactive, active, or complete.
This is the initial state of a pack. The state of a pack becomes known by
the time the shared `MGLOfflineStorage` object sends the first
`MGLOfflinePackProgressChangedNotification` about the pack. For inactive
the time the shared `MLNOfflineStorage` object sends the first
`MLNOfflinePackProgressChangedNotification` about the pack. For inactive
packs, you must explicitly request a progress update using the
`-[MGLOfflinePack requestProgress]` method.
`-[MLNOfflinePack requestProgress]` method.
An invalid pack always has a state of `MGLOfflinePackStateInvalid`, never
`MGLOfflinePackStateUnknown`.
An invalid pack always has a state of `MLNOfflinePackStateInvalid`, never
`MLNOfflinePackStateUnknown`.
*/
MGLOfflinePackStateUnknown = 0,
MLNOfflinePackStateUnknown = 0,
/**
The pack is incomplete and is not currently downloading.
This is the initial state of a pack that is created using the
`-[MGLOfflineStorage addPackForRegion:withContext:completionHandler:]`
method, as well as after the `-[MGLOfflinePack suspend]` method is
`-[MLNOfflineStorage addPackForRegion:withContext:completionHandler:]`
method, as well as after the `-[MLNOfflinePack suspend]` method is
called.
*/
MGLOfflinePackStateInactive = 1,
MLNOfflinePackStateInactive = 1,
/**
The pack is incomplete and is currently downloading.
This is the state of a pack after the `-[MGLOfflinePack resume]` method is
This is the state of a pack after the `-[MLNOfflinePack resume]` method is
called.
*/
MGLOfflinePackStateActive = 2,
MLNOfflinePackStateActive = 2,
/**
The pack has downloaded to completion.
*/
MGLOfflinePackStateComplete = 3,
MLNOfflinePackStateComplete = 3,
/**
The pack has been removed using the
`-[MGLOfflineStorage removePack:withCompletionHandler:]` method. Sending
`-[MLNOfflineStorage removePack:withCompletionHandler:]` method. Sending
any message to the pack will raise an exception.
*/
MGLOfflinePackStateInvalid = 4,
MLNOfflinePackStateInvalid = 4,
};
/**
A structure containing information about an offline pack’s current download
progress.
*/
typedef struct __attribute__((objc_boxable)) MGLOfflinePackProgress {
typedef struct __attribute__((objc_boxable)) MLNOfflinePackProgress {
/**
The number of resources, including tiles, that have been completely
downloaded and are ready to use offline.
@@ -94,37 +94,37 @@ typedef struct __attribute__((objc_boxable)) MGLOfflinePackProgress {
upper bound.
*/
uint64_t maximumResourcesExpected;
} MGLOfflinePackProgress;
} MLNOfflinePackProgress;
/**
An `MGLOfflinePack` represents a collection of resources necessary for viewing
An `MLNOfflinePack` represents a collection of resources necessary for viewing
a region offline to a local database.
To create an instance of `MGLOfflinePack`, use the
`+[MGLOfflineStorage addPackForRegion:withContext:completionHandler:]` method.
A pack created using `-[MGLOfflinePack init]` is immediately invalid.
To create an instance of `MLNOfflinePack`, use the
`+[MLNOfflineStorage addPackForRegion:withContext:completionHandler:]` method.
A pack created using `-[MLNOfflinePack init]` is immediately invalid.
### Example
```swift
MGLOfflineStorage.shared.addPack(for: region, withContext: context) { (pack, error) in
MLNOfflineStorage.shared.addPack(for: region, withContext: context) { (pack, error) in
guard let pack = pack else {
// If adding the pack fails, log an error to console.
print("Error:", error?.localizedDescription ?? "unknown error adding pack at \(#file)(\(#line)) in \(#function)")
return
}
// Start an MGLOfflinePack download
// Start an MLNOfflinePack download
pack.resume()
}
```
*/
MGL_EXPORT
@interface MGLOfflinePack : NSObject
MLN_EXPORT
@interface MLNOfflinePack : NSObject
/**
The region for which the pack manages resources.
*/
@property (nonatomic, readonly) id <MGLOfflineRegion> region;
@property (nonatomic, readonly) id <MLNOfflineRegion> region;
/**
Arbitrary data stored alongside the downloaded resources.
@@ -157,14 +157,14 @@ MGL_EXPORT
The pack’s current state.
The state of an inactive or completed pack is computed lazily and is set to
`MGLOfflinePackStateUnknown` by default. To request the pack’s status, use the
`MLNOfflinePackStateUnknown` by default. To request the pack’s status, use the
`-requestProgress` method. To get notified when the state becomes known and
when it changes, observe KVO change notifications on this pack’s `state` key
path. Alternatively, you can add an observer for
`MGLOfflinePackProgressChangedNotification`s about this pack that come from the
`MLNOfflinePackProgressChangedNotification`s about this pack that come from the
default notification center.
*/
@property (nonatomic, readonly) MGLOfflinePackState state;
@property (nonatomic, readonly) MLNOfflinePackState state;
/**
The pack’s current progress.
@@ -174,10 +174,10 @@ MGL_EXPORT
`-requestProgress` method. To get notified when the progress becomes
known and when it changes, observe KVO change notifications on this pack’s
`state` key path. Alternatively, you can add an observer for
`MGLOfflinePackProgressChangedNotification`s about this pack that come from the
`MLNOfflinePackProgressChangedNotification`s about this pack that come from the
default notification center.
*/
@property (nonatomic, readonly) MGLOfflinePackProgress progress;
@property (nonatomic, readonly) MLNOfflinePackProgress progress;
/**
Resumes downloading if the pack is inactive.
@@ -210,9 +210,9 @@ MGL_EXPORT
The state and progress of an inactive or completed pack are computed lazily. If
you need the state or progress of a pack whose `state` property is currently
set to `MGLOfflinePackStateUnknown`, observe KVO change notifications on this
set to `MLNOfflinePackStateUnknown`, observe KVO change notifications on this
pack’s `state` key path, then call this method. Alternatively, you can add an
observer for `MGLOfflinePackProgressChangedNotification` about this pack that
observer for `MLNOfflinePackProgressChangedNotification` about this pack that
come from the default notification center.
*/
- (void)requestProgress;

View File

@@ -1,72 +1,72 @@
#import "MGLOfflinePack_Private.h"
#import "MLNOfflinePack_Private.h"
#import "MGLOfflineStorage_Private.h"
#import "MGLOfflineRegion_Private.h"
#import "MGLTilePyramidOfflineRegion.h"
#import "MGLTilePyramidOfflineRegion_Private.h"
#import "MGLShapeOfflineRegion.h"
#import "MGLShapeOfflineRegion_Private.h"
#import "MGLLoggingConfiguration_Private.h"
#import "MLNOfflineStorage_Private.h"
#import "MLNOfflineRegion_Private.h"
#import "MLNTilePyramidOfflineRegion.h"
#import "MLNTilePyramidOfflineRegion_Private.h"
#import "MLNShapeOfflineRegion.h"
#import "MLNShapeOfflineRegion_Private.h"
#import "MLNLoggingConfiguration_Private.h"
#import "NSValue+MGLAdditions.h"
#import "NSValue+MLNAdditions.h"
#include <mbgl/map/map_options.hpp>
#include <mbgl/storage/database_file_source.hpp>
const MGLExceptionName MGLInvalidOfflinePackException = @"MGLInvalidOfflinePackException";
const MLNExceptionName MLNInvalidOfflinePackException = @"MLNInvalidOfflinePackException";
/**
Assert that the current offline pack is valid.
This macro should be used at the beginning of any public-facing instance method
of `MGLOfflinePack`. For private methods, an assertion is more appropriate.
of `MLNOfflinePack`. For private methods, an assertion is more appropriate.
*/
#define MGLAssertOfflinePackIsValid() \
#define MLNAssertOfflinePackIsValid() \
do { \
if (_state == MGLOfflinePackStateInvalid) { \
[NSException raise:MGLInvalidOfflinePackException \
if (_state == MLNOfflinePackStateInvalid) { \
[NSException raise:MLNInvalidOfflinePackException \
format: \
@"-[MGLOfflineStorage removePack:withCompletionHandler:] has been called " \
@"on this instance of MGLOfflinePack, rendering it invalid. It is an " \
@"-[MLNOfflineStorage removePack:withCompletionHandler:] has been called " \
@"on this instance of MLNOfflinePack, rendering it invalid. It is an " \
@"error to send any message to this pack."]; \
} \
} while (NO);
@interface MGLTilePyramidOfflineRegion () <MGLOfflineRegion_Private, MGLTilePyramidOfflineRegion_Private>
@interface MLNTilePyramidOfflineRegion () <MLNOfflineRegion_Private, MLNTilePyramidOfflineRegion_Private>
@end
@interface MGLShapeOfflineRegion () <MGLOfflineRegion_Private, MGLShapeOfflineRegion_Private>
@interface MLNShapeOfflineRegion () <MLNOfflineRegion_Private, MLNShapeOfflineRegion_Private>
@end
class MBGLOfflineRegionObserver : public mbgl::OfflineRegionObserver {
public:
MBGLOfflineRegionObserver(MGLOfflinePack *pack_) : pack(pack_) {}
MBGLOfflineRegionObserver(MLNOfflinePack *pack_) : pack(pack_) {}
void statusChanged(mbgl::OfflineRegionStatus status) override;
void responseError(mbgl::Response::Error error) override;
void mapboxTileCountLimitExceeded(uint64_t limit) override;
private:
__weak MGLOfflinePack *pack = nullptr;
__weak MLNOfflinePack *pack = nullptr;
};
@interface MGLOfflinePack ()
@interface MLNOfflinePack ()
@property (nonatomic, nullable, readwrite) mbgl::OfflineRegion *mbglOfflineRegion;
@property (nonatomic, readwrite) MGLOfflinePackProgress progress;
@property (nonatomic, readwrite) MLNOfflinePackProgress progress;
@end
@implementation MGLOfflinePack {
@implementation MLNOfflinePack {
BOOL _isSuspending;
std::shared_ptr<mbgl::DatabaseFileSource> _mbglDatabaseFileSource;
}
- (instancetype)init {
MGLLogInfo(@"Calling this initializer is not allowed.");
MLNLogInfo(@"Calling this initializer is not allowed.");
if (self = [super init]) {
_state = MGLOfflinePackStateInvalid;
NSLog(@"%s called; did you mean to call +[MGLOfflineStorage addPackForRegion:withContext:completionHandler:] instead?", __PRETTY_FUNCTION__);
_state = MLNOfflinePackStateInvalid;
NSLog(@"%s called; did you mean to call +[MLNOfflineStorage addPackForRegion:withContext:completionHandler:] instead?", __PRETTY_FUNCTION__);
}
return self;
}
@@ -74,62 +74,62 @@ private:
- (instancetype)initWithMBGLRegion:(mbgl::OfflineRegion *)region {
if (self = [super init]) {
_mbglOfflineRegion = region;
_state = MGLOfflinePackStateUnknown;
_state = MLNOfflinePackStateUnknown;
_mbglDatabaseFileSource = [[MGLOfflineStorage sharedOfflineStorage] mbglDatabaseFileSource];
_mbglDatabaseFileSource = [[MLNOfflineStorage sharedOfflineStorage] mbglDatabaseFileSource];
_mbglDatabaseFileSource->setOfflineRegionObserver(*_mbglOfflineRegion, std::make_unique<MBGLOfflineRegionObserver>(self));
}
return self;
}
- (void)dealloc {
MGLAssert(_state == MGLOfflinePackStateInvalid, @"MGLOfflinePack was not invalided prior to deallocation.");
MLNAssert(_state == MLNOfflinePackStateInvalid, @"MLNOfflinePack was not invalided prior to deallocation.");
}
- (id <MGLOfflineRegion>)region {
MGLAssertOfflinePackIsValid();
- (id <MLNOfflineRegion>)region {
MLNAssertOfflinePackIsValid();
const mbgl::OfflineRegionDefinition &regionDefinition = _mbglOfflineRegion->getDefinition();
MGLAssert([MGLTilePyramidOfflineRegion conformsToProtocol:@protocol(MGLOfflineRegion_Private)], @"MGLTilePyramidOfflineRegion should conform to MGLOfflineRegion_Private.");
MGLAssert([MGLShapeOfflineRegion conformsToProtocol:@protocol(MGLOfflineRegion_Private)], @"MGLShapeOfflineRegion should conform to MGLOfflineRegion_Private.");
MLNAssert([MLNTilePyramidOfflineRegion conformsToProtocol:@protocol(MLNOfflineRegion_Private)], @"MLNTilePyramidOfflineRegion should conform to MLNOfflineRegion_Private.");
MLNAssert([MLNShapeOfflineRegion conformsToProtocol:@protocol(MLNOfflineRegion_Private)], @"MLNShapeOfflineRegion should conform to MLNOfflineRegion_Private.");
return regionDefinition.match(
[&] (const mbgl::OfflineTilePyramidRegionDefinition def){
return (id <MGLOfflineRegion>)[[MGLTilePyramidOfflineRegion alloc] initWithOfflineRegionDefinition:def];
return (id <MLNOfflineRegion>)[[MLNTilePyramidOfflineRegion alloc] initWithOfflineRegionDefinition:def];
},
[&] (const mbgl::OfflineGeometryRegionDefinition& def){
return (id <MGLOfflineRegion>)[[MGLShapeOfflineRegion alloc] initWithOfflineRegionDefinition:def];
return (id <MLNOfflineRegion>)[[MLNShapeOfflineRegion alloc] initWithOfflineRegionDefinition:def];
});
}
- (NSData *)context {
MGLAssertOfflinePackIsValid();
MLNAssertOfflinePackIsValid();
const mbgl::OfflineRegionMetadata &metadata = _mbglOfflineRegion->getMetadata();
return [NSData dataWithBytes:&metadata[0] length:metadata.size()];
}
- (void)setContext:(NSData *)context completionHandler:(void (^_Nullable)(NSError * _Nullable error))completion {
MGLAssertOfflinePackIsValid();
MLNAssertOfflinePackIsValid();
mbgl::OfflineRegionMetadata metadata(context.length);
[context getBytes:&metadata[0] length:metadata.size()];
[self willChangeValueForKey:@"context"];
__weak MGLOfflinePack *weakSelf = self;
__weak MLNOfflinePack *weakSelf = self;
_mbglDatabaseFileSource->updateOfflineMetadata(_mbglOfflineRegion->getID(), metadata, [&, completion, weakSelf](mbgl::expected<mbgl::OfflineRegionMetadata, std::exception_ptr> mbglOfflineRegionMetadata) {
NSError *error;
if (!mbglOfflineRegionMetadata) {
NSString *errorDescription = @(mbgl::util::toString(mbglOfflineRegionMetadata.error()).c_str());
error = [NSError errorWithDomain:MGLErrorDomain code:MGLErrorCodeModifyingOfflineStorageFailed userInfo:errorDescription ? @{
error = [NSError errorWithDomain:MLNErrorDomain code:MLNErrorCodeModifyingOfflineStorageFailed userInfo:errorDescription ? @{
NSLocalizedDescriptionKey: errorDescription,
} : nil];
}
dispatch_async(dispatch_get_main_queue(), [&, completion, weakSelf, error](void) {
[weakSelf reloadWithCompletionHandler:^(NSError * _Nullable reloadingError) {
MGLOfflinePack *strongSelf = weakSelf;
MLNOfflinePack *strongSelf = weakSelf;
[strongSelf didChangeValueForKey:@"context"];
if (completion) {
completion(error ?: reloadingError);
@@ -141,11 +141,11 @@ private:
- (void)reloadWithCompletionHandler:(void (^)(NSError * _Nullable error))completion {
auto regionID = _mbglOfflineRegion->getID();
MGLOfflineStorage *sharedOfflineStorage = [MGLOfflineStorage sharedOfflineStorage];
__weak MGLOfflinePack *weakSelf = self;
[sharedOfflineStorage getPacksWithCompletionHandler:^(NSArray<MGLOfflinePack *> *packs, __unused NSError * _Nullable error) {
MGLOfflinePack *strongSelf = weakSelf;
for (MGLOfflinePack *pack in packs) {
MLNOfflineStorage *sharedOfflineStorage = [MLNOfflineStorage sharedOfflineStorage];
__weak MLNOfflinePack *weakSelf = self;
[sharedOfflineStorage getPacksWithCompletionHandler:^(NSArray<MLNOfflinePack *> *packs, __unused NSError * _Nullable error) {
MLNOfflinePack *strongSelf = weakSelf;
for (MLNOfflinePack *pack in packs) {
if (pack.mbglOfflineRegion->getID() == regionID) {
strongSelf.mbglOfflineRegion = pack.mbglOfflineRegion;
}
@@ -156,20 +156,20 @@ private:
}
- (void)resume {
MGLLogInfo(@"Resuming pack download.");
MGLAssertOfflinePackIsValid();
MLNLogInfo(@"Resuming pack download.");
MLNAssertOfflinePackIsValid();
self.state = MGLOfflinePackStateActive;
self.state = MLNOfflinePackStateActive;
_mbglDatabaseFileSource->setOfflineRegionDownloadState(*_mbglOfflineRegion, mbgl::OfflineRegionDownloadState::Active);
}
- (void)suspend {
MGLLogInfo(@"Suspending pack download.");
MGLAssertOfflinePackIsValid();
MLNLogInfo(@"Suspending pack download.");
MLNAssertOfflinePackIsValid();
if (self.state == MGLOfflinePackStateActive) {
self.state = MGLOfflinePackStateInactive;
if (self.state == MLNOfflinePackStateActive) {
self.state = MLNOfflinePackStateInactive;
_isSuspending = YES;
}
@@ -177,12 +177,12 @@ private:
}
- (void)invalidate {
MGLLogInfo(@"Invalidating pack.");
MGLAssert(_state != MGLOfflinePackStateInvalid, @"Cannot invalidate an already invalid offline pack.");
MGLAssert(self.mbglOfflineRegion, @"Should have a valid region");
MLNLogInfo(@"Invalidating pack.");
MLNAssert(_state != MLNOfflinePackStateInvalid, @"Cannot invalidate an already invalid offline pack.");
MLNAssert(self.mbglOfflineRegion, @"Should have a valid region");
@synchronized (self) {
self.state = MGLOfflinePackStateInvalid;
self.state = MLNOfflinePackStateInvalid;
if (self.mbglOfflineRegion) {
_mbglDatabaseFileSource->setOfflineRegionObserver(*self.mbglOfflineRegion, nullptr);
}
@@ -190,34 +190,34 @@ private:
}
}
- (void)setState:(MGLOfflinePackState)state {
MGLLogDebug(@"Setting state: %ld", (long)state);
- (void)setState:(MLNOfflinePackState)state {
MLNLogDebug(@"Setting state: %ld", (long)state);
if (!self.mbglOfflineRegion) {
// A progress update has arrived after the call to
// -[MGLOfflineStorage removePack:withCompletionHandler:] but before the
// -[MLNOfflineStorage removePack:withCompletionHandler:] but before the
// removal is complete and the completion handler is called.
MGLAssert(_state == MGLOfflinePackStateInvalid, @"A valid MGLOfflinePack has no mbgl::OfflineRegion.");
MLNAssert(_state == MLNOfflinePackStateInvalid, @"A valid MLNOfflinePack has no mbgl::OfflineRegion.");
return;
}
MGLAssert(_state != MGLOfflinePackStateInvalid, @"Cannot change the state of an invalid offline pack.");
MLNAssert(_state != MLNOfflinePackStateInvalid, @"Cannot change the state of an invalid offline pack.");
if (!_isSuspending || state != MGLOfflinePackStateActive) {
if (!_isSuspending || state != MLNOfflinePackStateActive) {
_isSuspending = NO;
_state = state;
}
}
- (void)requestProgress {
MGLLogInfo(@"Requesting pack progress.");
MGLAssertOfflinePackIsValid();
MLNLogInfo(@"Requesting pack progress.");
MLNAssertOfflinePackIsValid();
__weak MGLOfflinePack *weakSelf = self;
__weak MLNOfflinePack *weakSelf = self;
_mbglDatabaseFileSource->getOfflineRegionStatus(*_mbglOfflineRegion, [&, weakSelf](mbgl::expected<mbgl::OfflineRegionStatus, std::exception_ptr> status) {
if (status) {
mbgl::OfflineRegionStatus checkedStatus = *status;
dispatch_async(dispatch_get_main_queue(), ^{
MGLOfflinePack *strongSelf = weakSelf;
MLNOfflinePack *strongSelf = weakSelf;
[strongSelf offlineRegionStatusDidChange:checkedStatus];
});
}
@@ -225,15 +225,15 @@ private:
}
- (void)offlineRegionStatusDidChange:(mbgl::OfflineRegionStatus)status {
MGLAssert(_state != MGLOfflinePackStateInvalid, @"Cannot change update progress of an invalid offline pack.");
MLNAssert(_state != MLNOfflinePackStateInvalid, @"Cannot change update progress of an invalid offline pack.");
switch (status.downloadState) {
case mbgl::OfflineRegionDownloadState::Inactive:
self.state = status.complete() ? MGLOfflinePackStateComplete : MGLOfflinePackStateInactive;
self.state = status.complete() ? MLNOfflinePackStateComplete : MLNOfflinePackStateInactive;
break;
case mbgl::OfflineRegionDownloadState::Active:
self.state = MGLOfflinePackStateActive;
self.state = MLNOfflinePackStateActive;
break;
}
@@ -241,7 +241,7 @@ private:
return;
}
MGLOfflinePackProgress progress;
MLNOfflinePackProgress progress;
progress.countOfResourcesCompleted = status.completedResourceCount;
progress.countOfBytesCompleted = status.completedResourceSize;
progress.countOfTilesCompleted = status.completedTileCount;
@@ -250,54 +250,54 @@ private:
progress.maximumResourcesExpected = status.requiredResourceCountIsPrecise ? status.requiredResourceCount : UINT64_MAX;
self.progress = progress;
NSDictionary *userInfo = @{MGLOfflinePackUserInfoKeyState: @(self.state),
MGLOfflinePackUserInfoKeyProgress: [NSValue valueWithMGLOfflinePackProgress:progress]};
NSDictionary *userInfo = @{MLNOfflinePackUserInfoKeyState: @(self.state),
MLNOfflinePackUserInfoKeyProgress: [NSValue valueWithMLNOfflinePackProgress:progress]};
NSNotificationCenter *noteCenter = [NSNotificationCenter defaultCenter];
[noteCenter postNotificationName:MGLOfflinePackProgressChangedNotification
[noteCenter postNotificationName:MLNOfflinePackProgressChangedNotification
object:self
userInfo:userInfo];
}
- (void)didReceiveError:(NSError *)error {
MGLLogError(@"Error: %@", error.localizedDescription);
MGLLogInfo(@"Notifying about pack error.");
MLNLogError(@"Error: %@", error.localizedDescription);
MLNLogInfo(@"Notifying about pack error.");
NSDictionary *userInfo = @{ MGLOfflinePackUserInfoKeyError: error };
NSDictionary *userInfo = @{ MLNOfflinePackUserInfoKeyError: error };
NSNotificationCenter *noteCenter = [NSNotificationCenter defaultCenter];
[noteCenter postNotificationName:MGLOfflinePackErrorNotification
[noteCenter postNotificationName:MLNOfflinePackErrorNotification
object:self
userInfo:userInfo];
}
- (void)didReceiveMaximumAllowedMapboxTiles:(uint64_t)limit {
MGLLogInfo(@"Notifying reached maximum allowed Mapbox tiles: %lu", (unsigned long)limit);
NSDictionary *userInfo = @{ MGLOfflinePackUserInfoKeyMaximumCount: @(limit) };
MLNLogInfo(@"Notifying reached maximum allowed Mapbox tiles: %lu", (unsigned long)limit);
NSDictionary *userInfo = @{ MLNOfflinePackUserInfoKeyMaximumCount: @(limit) };
NSNotificationCenter *noteCenter = [NSNotificationCenter defaultCenter];
[noteCenter postNotificationName:MGLOfflinePackMaximumMapboxTilesReachedNotification
[noteCenter postNotificationName:MLNOfflinePackMaximumMapboxTilesReachedNotification
object:self
userInfo:userInfo];
}
NSError *MGLErrorFromResponseError(mbgl::Response::Error error) {
NSInteger errorCode = MGLErrorCodeUnknown;
NSError *MLNErrorFromResponseError(mbgl::Response::Error error) {
NSInteger errorCode = MLNErrorCodeUnknown;
switch (error.reason) {
case mbgl::Response::Error::Reason::NotFound:
errorCode = MGLErrorCodeNotFound;
errorCode = MLNErrorCodeNotFound;
break;
case mbgl::Response::Error::Reason::Server:
errorCode = MGLErrorCodeBadServerResponse;
errorCode = MLNErrorCodeBadServerResponse;
break;
case mbgl::Response::Error::Reason::Connection:
errorCode = MGLErrorCodeConnectionFailed;
errorCode = MLNErrorCodeConnectionFailed;
break;
default:
break;
}
return [NSError errorWithDomain:MGLErrorDomain code:errorCode userInfo:@{
return [NSError errorWithDomain:MLNErrorDomain code:errorCode userInfo:@{
NSLocalizedFailureReasonErrorKey: @(error.message.c_str())
}];
}
@@ -305,21 +305,21 @@ NSError *MGLErrorFromResponseError(mbgl::Response::Error error) {
@end
void MBGLOfflineRegionObserver::statusChanged(mbgl::OfflineRegionStatus status) {
__weak MGLOfflinePack *weakPack = pack;
__weak MLNOfflinePack *weakPack = pack;
dispatch_async(dispatch_get_main_queue(), ^{
[weakPack offlineRegionStatusDidChange:status];
});
}
void MBGLOfflineRegionObserver::responseError(mbgl::Response::Error error) {
__weak MGLOfflinePack *weakPack = pack;
__weak MLNOfflinePack *weakPack = pack;
dispatch_async(dispatch_get_main_queue(), ^{
[weakPack didReceiveError:MGLErrorFromResponseError(error)];
[weakPack didReceiveError:MLNErrorFromResponseError(error)];
});
}
void MBGLOfflineRegionObserver::mapboxTileCountLimitExceeded(uint64_t limit) {
__weak MGLOfflinePack *weakPack = pack;
__weak MLNOfflinePack *weakPack = pack;
dispatch_async(dispatch_get_main_queue(), ^{
[weakPack didReceiveMaximumAllowedMapboxTiles:limit];
});

View File

@@ -1,14 +1,14 @@
#import "MGLOfflinePack.h"
#import "MLNOfflinePack.h"
#include <mbgl/storage/offline.hpp>
NS_ASSUME_NONNULL_BEGIN
@interface MGLOfflinePack (Private)
@interface MLNOfflinePack (Private)
@property (nonatomic, nullable) mbgl::OfflineRegion *mbglOfflineRegion;
@property (nonatomic, readwrite) MGLOfflinePackState state;
@property (nonatomic, readwrite) MLNOfflinePackState state;
- (instancetype)initWithMBGLRegion:(mbgl::OfflineRegion *)region;

View File

@@ -3,10 +3,10 @@
NS_ASSUME_NONNULL_BEGIN
/**
An object conforming to the `MGLOfflineRegion` protocol determines which
resources are required by an `MGLOfflinePack` object.
An object conforming to the `MLNOfflineRegion` protocol determines which
resources are required by an `MLNOfflinePack` object.
*/
@protocol MGLOfflineRegion <NSObject>
@protocol MLNOfflineRegion <NSObject>
/**
URL of the style whose resources are required for offline viewing.
@@ -23,7 +23,7 @@ NS_ASSUME_NONNULL_BEGIN
Ideographic glyphs make up the majority of downloaded font data, but
it is possible to configure the renderer to use locally installed fonts
instead of relying on fonts downloaded as part of the offline pack.
See `MGLIdeographicFontFamilyName` setting. Also, for regions outside of
See `MLNIdeographicFontFamilyName` setting. Also, for regions outside of
China, Japan, and Korea, these glyphs will rarely appear for non-CJK users.
By default, this property is set to `NO`, so that the offline pack will

View File

@@ -1,12 +1,12 @@
#import <Foundation/Foundation.h>
#import "MGLOfflineRegion.h"
#import "MLNOfflineRegion.h"
#include <mbgl/storage/offline.hpp>
NS_ASSUME_NONNULL_BEGIN
@protocol MGLOfflineRegion_Private <MGLOfflineRegion>
@protocol MLNOfflineRegion_Private <MLNOfflineRegion>
/**
Creates and returns a C++ offline region definition corresponding to the

View File

@@ -1,26 +1,26 @@
#import <Foundation/Foundation.h>
#import "MGLFoundation.h"
#import "MGLTypes.h"
#import "MLNFoundation.h"
#import "MLNTypes.h"
NS_ASSUME_NONNULL_BEGIN
@class MGLOfflinePack;
@protocol MGLOfflineRegion;
@protocol MGLOfflineStorageDelegate;
@class MLNOfflinePack;
@protocol MLNOfflineRegion;
@protocol MLNOfflineStorageDelegate;
/**
Posted by the shared `MGLOfflineStorage` object when an `MGLOfflinePack`
Posted by the shared `MLNOfflineStorage` object when an `MLNOfflinePack`
object’s progress changes. The progress may change due to a resource being
downloaded or because the pack discovers during the download that more
resources are required for offline viewing. This notification is posted
whenever any field in the `progress` property changes.
The `object` is the `MGLOfflinePack` object whose progress changed. The
The `object` is the `MLNOfflinePack` object whose progress changed. The
`userInfo` dictionary contains the pack’s current state in the
`MGLOfflinePackUserInfoKeyState` key and details about the pack’s current
progress in the `MGLOfflinePackUserInfoKeyProgress` key. You may also consult
the `MGLOfflinePack.state` and `MGLOfflinePack.progress` properties, which
`MLNOfflinePackUserInfoKeyState` key and details about the pack’s current
progress in the `MLNOfflinePackUserInfoKeyProgress` key. You may also consult
the `MLNOfflinePack.state` and `MLNOfflinePack.progress` properties, which
provide the same values.
If you only need to observe changes in a particular pack’s progress, you can
@@ -32,76 +32,76 @@ NS_ASSUME_NONNULL_BEGIN
Download an offline map</a> example to learn how to calculate the progress
of an offline download.
*/
FOUNDATION_EXTERN MGL_EXPORT const NSNotificationName MGLOfflinePackProgressChangedNotification;
FOUNDATION_EXTERN MLN_EXPORT const NSNotificationName MLNOfflinePackProgressChangedNotification;
/**
Posted by the shared `MGLOfflineStorage` object whenever an `MGLOfflinePack`
Posted by the shared `MLNOfflineStorage` object whenever an `MLNOfflinePack`
object encounters an error while downloading. The error may be recoverable and
may not warrant the user’s attention. For example, the pack’s implementation
may attempt to re-request failed resources based on an exponential backoff
strategy or upon the restoration of network access.
The `object` is the `MGLOfflinePack` object that encountered the error. The
The `object` is the `MLNOfflinePack` object that encountered the error. The
`userInfo` dictionary contains the error object in the
`MGLOfflinePackUserInfoKeyError` key.
`MLNOfflinePackUserInfoKeyError` key.
*/
FOUNDATION_EXTERN MGL_EXPORT const NSNotificationName MGLOfflinePackErrorNotification;
FOUNDATION_EXTERN MLN_EXPORT const NSNotificationName MLNOfflinePackErrorNotification;
/**
Posted by the shared `MGLOfflineStorage` object when the maximum number of
Posted by the shared `MLNOfflineStorage` object when the maximum number of
Mapbox-hosted tiles has been downloaded and stored on the current device.
The `object` is the `MGLOfflinePack` object that reached the tile limit in the
The `object` is the `MLNOfflinePack` object that reached the tile limit in the
course of downloading. The `userInfo` dictionary contains the tile limit in the
`MGLOfflinePackUserInfoKeyMaximumCount` key.
`MLNOfflinePackUserInfoKeyMaximumCount` key.
Once this limit is reached, no instance of `MGLOfflinePack` can download
Once this limit is reached, no instance of `MLNOfflinePack` can download
additional tiles from Mapbox APIs until already downloaded tiles are removed by
calling the `-[MGLOfflineStorage removePack:withCompletionHandler:]` method.
calling the `-[MLNOfflineStorage removePack:withCompletionHandler:]` method.
*/
FOUNDATION_EXTERN MGL_EXPORT const NSNotificationName MGLOfflinePackMaximumMapboxTilesReachedNotification;
FOUNDATION_EXTERN MLN_EXPORT const NSNotificationName MLNOfflinePackMaximumMapboxTilesReachedNotification;
/**
A key in the `userInfo` property of a notification posted by `MGLOfflinePack`.
A key in the `userInfo` property of a notification posted by `MLNOfflinePack`.
*/
typedef NSString *MGLOfflinePackUserInfoKey NS_EXTENSIBLE_STRING_ENUM;
typedef NSString *MLNOfflinePackUserInfoKey NS_EXTENSIBLE_STRING_ENUM;
/**
The key for an `NSNumber` object that indicates an offline pack’s current
state. This key is used in the `userInfo` dictionary of an
`MGLOfflinePackProgressChangedNotification` notification. Call `-integerValue`
on the object to receive the `MGLOfflinePackState`-typed state.
`MLNOfflinePackProgressChangedNotification` notification. Call `-integerValue`
on the object to receive the `MLNOfflinePackState`-typed state.
*/
FOUNDATION_EXTERN MGL_EXPORT const MGLOfflinePackUserInfoKey MGLOfflinePackUserInfoKeyState;
FOUNDATION_EXTERN MLN_EXPORT const MLNOfflinePackUserInfoKey MLNOfflinePackUserInfoKeyState;
/**
The key for an `NSValue` object that indicates an offline pack’s current
progress. This key is used in the `userInfo` dictionary of an
`MGLOfflinePackProgressChangedNotification` notification. Call
`-MGLOfflinePackProgressValue` on the object to receive the
`MGLOfflinePackProgress`-typed progress.
`MLNOfflinePackProgressChangedNotification` notification. Call
`-MLNOfflinePackProgressValue` on the object to receive the
`MLNOfflinePackProgress`-typed progress.
*/
FOUNDATION_EXTERN MGL_EXPORT const MGLOfflinePackUserInfoKey MGLOfflinePackUserInfoKeyProgress;
FOUNDATION_EXTERN MLN_EXPORT const MLNOfflinePackUserInfoKey MLNOfflinePackUserInfoKeyProgress;
/**
The key for an `NSError` object that is encountered in the course of
downloading an offline pack. This key is used in the `userInfo` dictionary of
an `MGLOfflinePackErrorNotification` notification. The error’s domain is
`MGLErrorDomain`. See `MGLErrorCode` for possible error codes.
an `MLNOfflinePackErrorNotification` notification. The error’s domain is
`MLNErrorDomain`. See `MLNErrorCode` for possible error codes.
*/
FOUNDATION_EXTERN MGL_EXPORT const MGLOfflinePackUserInfoKey MGLOfflinePackUserInfoKeyError;
FOUNDATION_EXTERN MLN_EXPORT const MLNOfflinePackUserInfoKey MLNOfflinePackUserInfoKeyError;
/**
The key for an `NSNumber` object that indicates the maximum number of
Mapbox-hosted tiles that may be downloaded and stored on the current device.
This key is used in the `userInfo` dictionary of an
`MGLOfflinePackMaximumMapboxTilesReachedNotification` notification. Call
`MLNOfflinePackMaximumMapboxTilesReachedNotification` notification. Call
`-unsignedLongLongValue` on the object to receive the `uint64_t`-typed tile
limit.
*/
FOUNDATION_EXTERN MGL_EXPORT const MGLOfflinePackUserInfoKey MGLOfflinePackUserInfoKeyMaximumCount;
FOUNDATION_EXTERN MLN_EXPORT const MLNOfflinePackUserInfoKey MLNOfflinePackUserInfoKeyMaximumCount;
FOUNDATION_EXTERN MGL_EXPORT MGLExceptionName const MGLUnsupportedRegionTypeException;
FOUNDATION_EXTERN MLN_EXPORT MLNExceptionName const MLNUnsupportedRegionTypeException;
/**
A block to be called once an offline pack has been completely created and
@@ -115,7 +115,7 @@ FOUNDATION_EXTERN MGL_EXPORT MGLExceptionName const MGLUnsupportedRegionTypeExce
@param error Contains a pointer to an error object (if any) indicating why the
pack could not be created or added.
*/
typedef void (^MGLOfflinePackAdditionCompletionHandler)(MGLOfflinePack * _Nullable pack, NSError * _Nullable error);
typedef void (^MLNOfflinePackAdditionCompletionHandler)(MLNOfflinePack * _Nullable pack, NSError * _Nullable error);
/**
A block to be called once an offline pack has been completely invalidated and
@@ -128,7 +128,7 @@ typedef void (^MGLOfflinePackAdditionCompletionHandler)(MGLOfflinePack * _Nullab
@param error Contains a pointer to an error object (if any) indicating why the
pack could not be invalidated or removed.
*/
typedef void (^MGLOfflinePackRemovalCompletionHandler)(NSError * _Nullable error);
typedef void (^MLNOfflinePackRemovalCompletionHandler)(NSError * _Nullable error);
/**
A block to be called once the contents of a file are copied into the current packs.
@@ -140,7 +140,7 @@ typedef void (^MGLOfflinePackRemovalCompletionHandler)(NSError * _Nullable error
@param error A pointer to an error object (if any) indicating why the pack could
not be created or added.
*/
typedef void (^MGLBatchedOfflinePackAdditionCompletionHandler)(NSURL *fileURL, NSArray<MGLOfflinePack *> * _Nullable packs, NSError * _Nullable error);
typedef void (^MLNBatchedOfflinePackAdditionCompletionHandler)(NSURL *fileURL, NSArray<MLNOfflinePack *> * _Nullable packs, NSError * _Nullable error);
/**
A block to be called once the data has been preloaded.
@@ -149,36 +149,36 @@ A block to be called once the data has been preloaded.
@param error Contains a pointer to an error object (if any) indicating why the
data could not be pre-loaded.
*/
typedef void (^MGLOfflinePreloadDataCompletionHandler)(NSURL * url, NSError * _Nullable error);
typedef void (^MLNOfflinePreloadDataCompletionHandler)(NSURL * url, NSError * _Nullable error);
/**
The type of resource that is requested.
*/
typedef NS_ENUM(NSUInteger, MGLResourceKind) {
typedef NS_ENUM(NSUInteger, MLNResourceKind) {
/** Unknown type */
MGLResourceKindUnknown,
MLNResourceKindUnknown,
/** Style sheet JSON file */
MGLResourceKindStyle,
MLNResourceKindStyle,
/** TileJSON file as specified in https://maplibre.org/maplibre-gl-js-docs/style-spec/#root-sources */
MGLResourceKindSource,
MLNResourceKindSource,
/** A vector or raster tile as described in the style sheet at
https://maplibre.org/maplibre-gl-js-docs/style-spec/#sources */
MGLResourceKindTile,
MLNResourceKindTile,
/** Signed distance field glyphs for text rendering. These are the URLs specified in the style
in https://maplibre.org/maplibre-gl-js-docs/style-spec/#root-glyphs */
MGLResourceKindGlyphs,
MLNResourceKindGlyphs,
/** Image part of a sprite sheet. It is constructed of the prefix in
https://maplibre.org/maplibre-gl-js-docs/style-spec/#root-sprite and a PNG file extension. */
MGLResourceKindSpriteImage,
MLNResourceKindSpriteImage,
/** JSON part of a sprite sheet. It is constructed of the prefix in
https://maplibre.org/maplibre-gl-js-docs/style-spec/#root-sprite and a JSON file extension. */
MGLResourceKindSpriteJSON,
MLNResourceKindSpriteJSON,
/** Image data for a georeferenced image source. **/
MGLResourceKindImage,
MLNResourceKindImage,
};
/**
MGLOfflineStorage implements a singleton (shared object) that manages offline
MLNOfflineStorage implements a singleton (shared object) that manages offline
packs and ambient caching. All of this class’s instance methods are asynchronous,
reflecting the fact that offline resources are stored in a database. The shared
object maintains a canonical collection of offline packs in its `packs` property.
@@ -193,13 +193,13 @@ typedef NS_ENUM(NSUInteger, MGLResourceKind) {
Download an offline map</a> example to learn how to create and register an
offline pack for a defined region.
*/
MGL_EXPORT
@interface MGLOfflineStorage : NSObject
MLN_EXPORT
@interface MLNOfflineStorage : NSObject
/**
Returns the shared offline storage object.
*/
@property (class, nonatomic, readonly) MGLOfflineStorage *sharedOfflineStorage;
@property (class, nonatomic, readonly) MLNOfflineStorage *sharedOfflineStorage;
// MARK: - Accessing the Delegate
@@ -211,7 +211,7 @@ MGL_EXPORT
add or remove custom parameters, or reroute certain requests to other servers
or endpoints.
*/
@property(nonatomic, weak, nullable) IBOutlet id<MGLOfflineStorageDelegate> delegate;
@property(nonatomic, weak, nullable) IBOutlet id<MLNOfflineStorageDelegate> delegate;
// MARK: - Managing the Database of Offline Packs
@@ -219,7 +219,7 @@ MGL_EXPORT
The file path at which offline packs and the ambient cache are stored.
To customize this path, specify the
[`MGLOfflineStorageDatabasePath`](../infoplist-keys.html#mglofflinestoragedatabasepath)
[`MLNOfflineStorageDatabasePath`](../infoplist-keys.html#mglofflinestoragedatabasepath)
key in Info.plist.
*/
@property (nonatomic, readonly, copy) NSString *databasePath;
@@ -228,7 +228,7 @@ MGL_EXPORT
The file URL at which offline packs and the ambient cache are stored.
To customize this path, specify the
[`MGLOfflineStorageDatabasePath`](../infoplist-keys.html#mglofflinestoragedatabasepath)
[`MLNOfflineStorageDatabasePath`](../infoplist-keys.html#mglofflinestoragedatabasepath)
key in Info.plist.
*/
@property (nonatomic, readonly, copy) NSURL *databaseURL;
@@ -248,7 +248,7 @@ MGL_EXPORT
file has been added to offline storage. This handler is executed
asynchronously on the main queue.
*/
- (void)addContentsOfFile:(NSString *)filePath withCompletionHandler:(nullable MGLBatchedOfflinePackAdditionCompletionHandler)completion;
- (void)addContentsOfFile:(NSString *)filePath withCompletionHandler:(nullable MLNBatchedOfflinePackAdditionCompletionHandler)completion;
/**
Adds the offline packs located at the given URL to offline storage.
@@ -265,7 +265,7 @@ MGL_EXPORT
file has been added to offline storage. This handler is executed
asynchronously on the main queue.
*/
- (void)addContentsOfURL:(NSURL *)fileURL withCompletionHandler:(nullable MGLBatchedOfflinePackAdditionCompletionHandler)completion;
- (void)addContentsOfURL:(NSURL *)fileURL withCompletionHandler:(nullable MLNBatchedOfflinePackAdditionCompletionHandler)completion;
// MARK: - Managing Offline Packs
@@ -282,7 +282,7 @@ MGL_EXPORT
`packs` property, observe KVO change notifications on the `packs` key path.
The initial load results in an `NSKeyValueChangeSetting` change.
*/
@property (nonatomic, strong, readonly, nullable) NSArray<MGLOfflinePack *> *packs;
@property (nonatomic, strong, readonly, nullable) NSArray<MLNOfflinePack *> *packs;
/**
Creates and registers an offline pack that downloads the resources needed to
@@ -291,10 +291,10 @@ MGL_EXPORT
The resulting pack is added to the shared offline storage object’s `packs`
property, then the `completion` block is executed with that pack passed in.
The pack has an initial state of `MGLOfflinePackStateInactive`. To begin
downloading resources, call `-[MGLOfflinePack resume]` on the pack from within
The pack has an initial state of `MLNOfflinePackStateInactive`. To begin
downloading resources, call `-[MLNOfflinePack resume]` on the pack from within
the completion handler. To monitor download progress, add an observer for
`MGLOfflinePackProgressChangedNotification`s about that pack.
`MLNOfflinePackProgressChangedNotification`s about that pack.
To detect when any call to this method results in a new pack, observe KVO
change notifications on the shared offline storage object’s `packs` key path.
@@ -305,7 +305,7 @@ MGL_EXPORT
@param completion The completion handler to call once the pack has been added.
This handler is executed asynchronously on the main queue.
*/
- (void)addPackForRegion:(id <MGLOfflineRegion>)region withContext:(NSData *)context completionHandler:(nullable MGLOfflinePackAdditionCompletionHandler)completion;
- (void)addPackForRegion:(id <MLNOfflineRegion>)region withContext:(NSData *)context completionHandler:(nullable MLNOfflinePackAdditionCompletionHandler)completion;
/**
Unregisters the given offline pack and allows resources that are no longer
@@ -332,7 +332,7 @@ MGL_EXPORT
@param completion The completion handler to call once the pack has been
removed. This handler is executed asynchronously on the main queue.
*/
- (void)removePack:(MGLOfflinePack *)pack withCompletionHandler:(nullable MGLOfflinePackRemovalCompletionHandler)completion;
- (void)removePack:(MLNOfflinePack *)pack withCompletionHandler:(nullable MLNOfflinePackRemovalCompletionHandler)completion;
/**
Invalidates the specified offline pack. This method checks that the tiles
@@ -348,10 +348,10 @@ MGL_EXPORT
removed. This handler is executed asynchronously on the main queue.
*/
- (void)invalidatePack:(MGLOfflinePack *)pack withCompletionHandler:(void (^)(NSError * _Nullable))completion;
- (void)invalidatePack:(MLNOfflinePack *)pack withCompletionHandler:(void (^)(NSError * _Nullable))completion;
/**
Forcibly, asynchronously reloads the `packs` property. At some point after this
method is called, the pointer values of the `MGLOfflinePack` objects in the
method is called, the pointer values of the `MLNOfflinePack` objects in the
`packs` property change, even if the underlying data for these packs has not
changed. If this method is called while a pack is actively downloading, the
behavior is undefined.
@@ -369,7 +369,7 @@ MGL_EXPORT
stored on the current device.
Once this limit is reached, an
`MGLOfflinePackMaximumMapboxTilesReachedNotification` is posted for every
`MLNOfflinePackMaximumMapboxTilesReachedNotification` is posted for every
attempt to download additional tiles until already downloaded tiles are removed
by calling the `-removePack:withCompletionHandler:` method.
@@ -381,7 +381,7 @@ MGL_EXPORT
The cumulative size, measured in bytes, of all downloaded resources on disk.
The returned value includes all resources, including tiles, whether downloaded
as part of an offline pack or due to caching during normal use of `MGLMapView`.
as part of an offline pack or due to caching during normal use of `MLNMapView`.
*/
@property (nonatomic, readonly) unsigned long long countOfBytesCompleted;
@@ -496,16 +496,16 @@ MGL_EXPORT
preloaded. This handler is executed asynchronously on the main queue.
*/
- (void)preloadData:(NSData *)data forURL:(NSURL *)url modificationDate:(nullable NSDate *)modified expirationDate:(nullable NSDate *)expires eTag:(nullable NSString *)eTag mustRevalidate:(BOOL)mustRevalidate
completionHandler:(nullable MGLOfflinePreloadDataCompletionHandler)completion;
completionHandler:(nullable MLNOfflinePreloadDataCompletionHandler)completion;
@end
/**
The `MGLOfflineStorageDelegate` protocol defines methods that a delegate of an
`MGLOfflineStorage` object can optionally implement to transform various types
The `MLNOfflineStorageDelegate` protocol defines methods that a delegate of an
`MLNOfflineStorage` object can optionally implement to transform various types
of URLs before downloading them via the internet.
*/
@protocol MGLOfflineStorageDelegate <NSObject>
@protocol MLNOfflineStorageDelegate <NSObject>
/**
Sent whenever a URL needs to be transformed.
@@ -515,8 +515,8 @@ MGL_EXPORT
@param url The original URL to be transformed.
@return A URL that will now be downloaded.
*/
- (NSURL *)offlineStorage:(MGLOfflineStorage *)storage
URLForResourceOfKind:(MGLResourceKind)kind
- (NSURL *)offlineStorage:(MLNOfflineStorage *)storage
URLForResourceOfKind:(MLNResourceKind)kind
withURL:(NSURL *)url;
@end

View File

@@ -1,17 +1,17 @@
#import "MGLOfflineStorage_Private.h"
#import "MLNOfflineStorage_Private.h"
#import "MGLFoundation_Private.h"
#import "MGLSettings_Private.h"
#import "MGLGeometry_Private.h"
#import "MGLOfflinePack_Private.h"
#import "MGLOfflineRegion_Private.h"
#import "MGLTilePyramidOfflineRegion.h"
#import "MGLShapeOfflineRegion.h"
#import "NSBundle+MGLAdditions.h"
#import "NSValue+MGLAdditions.h"
#import "NSDate+MGLAdditions.h"
#import "MGLLoggingConfiguration_Private.h"
#import "MGLNetworkConfiguration_Private.h"
#import "MLNFoundation_Private.h"
#import "MLNSettings_Private.h"
#import "MLNGeometry_Private.h"
#import "MLNOfflinePack_Private.h"
#import "MLNOfflineRegion_Private.h"
#import "MLNTilePyramidOfflineRegion.h"
#import "MLNShapeOfflineRegion.h"
#import "NSBundle+MLNAdditions.h"
#import "NSValue+MLNAdditions.h"
#import "NSDate+MLNAdditions.h"
#import "MLNLoggingConfiguration_Private.h"
#import "MLNNetworkConfiguration_Private.h"
#include <mbgl/actor/actor.hpp>
#include <mbgl/actor/scheduler.hpp>
@@ -25,38 +25,38 @@
#include <memory>
static NSString * const MGLOfflineStorageDatabasePathInfoDictionaryKey = @"MGLOfflineStorageDatabasePath";
static NSString * const MGLOfflineStorageFileName = @"cache.db";
static NSString * const MGLOfflineStorageFileName3_2_0_beta_1 = @"offline.db";
static NSString * const MLNOfflineStorageDatabasePathInfoDictionaryKey = @"MLNOfflineStorageDatabasePath";
static NSString * const MLNOfflineStorageFileName = @"cache.db";
static NSString * const MLNOfflineStorageFileName3_2_0_beta_1 = @"offline.db";
const NSNotificationName MGLOfflinePackProgressChangedNotification = @"MGLOfflinePackProgressChanged";
const NSNotificationName MGLOfflinePackErrorNotification = @"MGLOfflinePackError";
const NSNotificationName MGLOfflinePackMaximumMapboxTilesReachedNotification = @"MGLOfflinePackMaximumMapboxTilesReached";
const NSNotificationName MLNOfflinePackProgressChangedNotification = @"MLNOfflinePackProgressChanged";
const NSNotificationName MLNOfflinePackErrorNotification = @"MLNOfflinePackError";
const NSNotificationName MLNOfflinePackMaximumMapboxTilesReachedNotification = @"MLNOfflinePackMaximumMapboxTilesReached";
const MGLOfflinePackUserInfoKey MGLOfflinePackUserInfoKeyState = @"State";
const MGLOfflinePackUserInfoKey MGLOfflinePackUserInfoKeyProgress = @"Progress";
const MGLOfflinePackUserInfoKey MGLOfflinePackUserInfoKeyError = @"Error";
const MGLOfflinePackUserInfoKey MGLOfflinePackUserInfoKeyMaximumCount = @"MaximumCount";
const MLNOfflinePackUserInfoKey MLNOfflinePackUserInfoKeyState = @"State";
const MLNOfflinePackUserInfoKey MLNOfflinePackUserInfoKeyProgress = @"Progress";
const MLNOfflinePackUserInfoKey MLNOfflinePackUserInfoKeyError = @"Error";
const MLNOfflinePackUserInfoKey MLNOfflinePackUserInfoKeyMaximumCount = @"MaximumCount";
const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegionTypeException";
const MLNExceptionName MLNUnsupportedRegionTypeException = @"MLNUnsupportedRegionTypeException";
@interface MGLOfflineStorage ()
@interface MLNOfflineStorage ()
@property (nonatomic, strong, readwrite) NSMutableArray<MGLOfflinePack *> *packs;
@property (nonatomic, strong, readwrite) NSMutableArray<MLNOfflinePack *> *packs;
@property (nonatomic) std::shared_ptr<mbgl::DatabaseFileSource> mbglDatabaseFileSource;
@property (nonatomic) std::shared_ptr<mbgl::FileSource> mbglOnlineFileSource;
@property (nonatomic) std::shared_ptr<mbgl::FileSource> mbglFileSource;
@property (nonatomic, getter=isPaused) BOOL paused;
@end
@implementation MGLOfflineStorage {
@implementation MLNOfflineStorage {
NSURL *_databaseURL;
std::unique_ptr<mbgl::Actor<mbgl::ResourceTransform::TransformCallback>> _mbglResourceTransform;
}
+ (instancetype)sharedOfflineStorage {
static dispatch_once_t onceToken;
static MGLOfflineStorage *sharedOfflineStorage;
static MLNOfflineStorage *sharedOfflineStorage;
dispatch_once(&onceToken, ^{
sharedOfflineStorage = [[self alloc] init];
#if TARGET_OS_IPHONE || TARGET_OS_SIMULATOR
@@ -66,12 +66,12 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
[sharedOfflineStorage reloadPacks];
});
// Always ensure the MGLNativeNetworkManager delegate is setup. Calling
// Always ensure the MLNNativeNetworkManager delegate is setup. Calling
// `resetNativeNetworkManagerDelegate` is not necessary here, since the shared
// manager already calls it.
//
// TODO: Consider only calling this for testing?
[MGLNetworkConfiguration sharedManager];
[MLNNetworkConfiguration sharedManager];
return sharedOfflineStorage;
}
@@ -98,8 +98,8 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
}
#endif
- (void)setDelegate:(id<MGLOfflineStorageDelegate>)newValue {
MGLLogDebug(@"Setting delegate: %@", newValue);
- (void)setDelegate:(id<MLNOfflineStorageDelegate>)newValue {
MLNLogDebug(@"Setting delegate: %@", newValue);
_delegate = newValue;
if ([self.delegate respondsToSelector:@selector(offlineStorage:URLForResourceOfKind:withURL:)]) {
_mbglResourceTransform = std::make_unique<mbgl::Actor<mbgl::ResourceTransform::TransformCallback>>(*mbgl::Scheduler::GetCurrent(), [offlineStorage = self](auto kind_, const std::string& url_, mbgl::ResourceTransform::FinishedCallback cb) {
@@ -107,31 +107,31 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
[NSURL URLWithString:[[NSString alloc] initWithBytes:url_.data()
length:url_.length()
encoding:NSUTF8StringEncoding]];
MGLResourceKind kind = MGLResourceKindUnknown;
MLNResourceKind kind = MLNResourceKindUnknown;
switch (kind_) {
case mbgl::Resource::Kind::Tile:
kind = MGLResourceKindTile;
kind = MLNResourceKindTile;
break;
case mbgl::Resource::Kind::Glyphs:
kind = MGLResourceKindGlyphs;
kind = MLNResourceKindGlyphs;
break;
case mbgl::Resource::Kind::Style:
kind = MGLResourceKindStyle;
kind = MLNResourceKindStyle;
break;
case mbgl::Resource::Kind::Source:
kind = MGLResourceKindSource;
kind = MLNResourceKindSource;
break;
case mbgl::Resource::Kind::SpriteImage:
kind = MGLResourceKindSpriteImage;
kind = MLNResourceKindSpriteImage;
break;
case mbgl::Resource::Kind::SpriteJSON:
kind = MGLResourceKindSpriteJSON;
kind = MLNResourceKindSpriteJSON;
break;
case mbgl::Resource::Kind::Image:
kind = MGLResourceKindImage;
kind = MLNResourceKindImage;
break;
case mbgl::Resource::Kind::Unknown:
kind = MGLResourceKindUnknown;
kind = MLNResourceKindUnknown;
break;
}
@@ -154,12 +154,12 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
// Ensure network configuration & appropriate delegate prior to starting the
// run loop. Calling `resetNativeNetworkManagerDelegate` is not necessary here,
// since the shared manager already calls it.
[MGLNetworkConfiguration sharedManager];
[MLNNetworkConfiguration sharedManager];
MGLInitializeRunLoop();
MLNInitializeRunLoop();
if (self = [super init]) {
mbgl::TileServerOptions* tileServerOptions = [[MGLSettings sharedSettings] tileServerOptionsInternal];
mbgl::TileServerOptions* tileServerOptions = [[MLNSettings sharedSettings] tileServerOptionsInternal];
mbgl::ResourceOptions resourceOptions;
resourceOptions.withCachePath(self.databasePath.UTF8String)
.withAssetPath([NSBundle mainBundle].resourceURL.path.UTF8String)
@@ -170,14 +170,14 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
_mbglDatabaseFileSource = std::static_pointer_cast<mbgl::DatabaseFileSource>(std::shared_ptr<mbgl::FileSource>(mbgl::FileSourceManager::get()->getFileSource(mbgl::FileSourceType::Database, resourceOptions, clientOptions)));
// Observe for changes to the tile server options (and find out the current one).
[[MGLSettings sharedSettings] addObserver:self
[[MLNSettings sharedSettings] addObserver:self
forKeyPath:@"tileServerOptionsChangeToken"
options:(NSKeyValueObservingOptionInitial |
NSKeyValueObservingOptionNew)
context:NULL];
// Observe for changes to the global access token (and find out the current one).
[[MGLSettings sharedSettings] addObserver:self
[[MLNSettings sharedSettings] addObserver:self
forKeyPath:@"apiKey"
options:(NSKeyValueObservingOptionInitial |
NSKeyValueObservingOptionNew)
@@ -189,23 +189,23 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[[MGLSettings sharedSettings] removeObserver:self forKeyPath:@"tileServerOptionsChangeToken"];
[[MGLSettings sharedSettings] removeObserver:self forKeyPath:@"apiKey"];
[[MLNSettings sharedSettings] removeObserver:self forKeyPath:@"tileServerOptionsChangeToken"];
[[MLNSettings sharedSettings] removeObserver:self forKeyPath:@"apiKey"];
for (MGLOfflinePack *pack in self.packs) {
for (MLNOfflinePack *pack in self.packs) {
[pack invalidate];
}
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *, id> *)change context:(void *)context {
// Synchronize the file source’s access token with the global one in MGLSettings.
if ([keyPath isEqualToString:@"apiKey"] && object == [MGLSettings sharedSettings]) {
// Synchronize the file source’s access token with the global one in MLNSettings.
if ([keyPath isEqualToString:@"apiKey"] && object == [MLNSettings sharedSettings]) {
NSString *apiKey = change[NSKeyValueChangeNewKey];
if (![apiKey isKindOfClass:[NSNull class]]) {
_mbglOnlineFileSource->setProperty(mbgl::API_KEY_KEY, apiKey.UTF8String);
}
} else if ([keyPath isEqualToString:@"tileServerOptionsChangeToken"] && object == [MGLSettings sharedSettings]) {
auto tileServerOptions = [[MGLSettings sharedSettings] tileServerOptionsInternal];
} else if ([keyPath isEqualToString:@"tileServerOptionsChangeToken"] && object == [MLNSettings sharedSettings]) {
auto tileServerOptions = [[MLNSettings sharedSettings] tileServerOptionsInternal];
auto apiBaseURL = tileServerOptions->baseURL();
auto resourceOptions = _mbglOnlineFileSource->getResourceOptions().clone();
_mbglOnlineFileSource->setResourceOptions(resourceOptions.withTileServerOptions(*tileServerOptions).clone());
@@ -222,7 +222,7 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
- (NSURL *)databaseURL {
if (!_databaseURL) {
NSString *customPath = [NSBundle.mainBundle objectForInfoDictionaryKey:MGLOfflineStorageDatabasePathInfoDictionaryKey];
NSString *customPath = [NSBundle.mainBundle objectForInfoDictionaryKey:MLNOfflineStorageDatabasePathInfoDictionaryKey];
if ([customPath isKindOfClass:[NSString class]]) {
_databaseURL = [NSURL fileURLWithPath:customPath.stringByStandardizingPath isDirectory:NO relativeToURL:NSBundle.mainBundle.resourceURL];
@@ -294,7 +294,7 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
// unfortunately it has to live in the same file as offline resources.
[databaseDirectoryURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:NULL];
}
return [databaseDirectoryURL URLByAppendingPathComponent:MGLOfflineStorageFileName];
return [databaseDirectoryURL URLByAppendingPathComponent:MLNOfflineStorageFileName];
}
/**
@@ -305,7 +305,7 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
#if TARGET_OS_IPHONE || TARGET_OS_SIMULATOR
// ~/Documents/offline.db
NSArray *legacyPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *legacyDatabasePath = [legacyPaths.firstObject stringByAppendingPathComponent:MGLOfflineStorageFileName3_2_0_beta_1];
NSString *legacyDatabasePath = [legacyPaths.firstObject stringByAppendingPathComponent:MLNOfflineStorageFileName3_2_0_beta_1];
#elif TARGET_OS_MAC
// ~/Library/Caches/tld.app.bundle.id/offline.db
NSString *bundleIdentifier = [NSBundle mgl_applicationBundleIdentifier];
@@ -315,22 +315,22 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
create:NO
error:nil];
legacyDatabaseDirectoryURL = [legacyDatabaseDirectoryURL URLByAppendingPathComponent:bundleIdentifier];
NSURL *legacyDatabaseURL = [legacyDatabaseDirectoryURL URLByAppendingPathComponent:MGLOfflineStorageFileName3_2_0_beta_1];
NSURL *legacyDatabaseURL = [legacyDatabaseDirectoryURL URLByAppendingPathComponent:MLNOfflineStorageFileName3_2_0_beta_1];
NSString *legacyDatabasePath = legacyDatabaseURL ? legacyDatabaseURL.path : @"";
#endif
return legacyDatabasePath;
}
- (void)addContentsOfFile:(NSString *)filePath withCompletionHandler:(MGLBatchedOfflinePackAdditionCompletionHandler)completion {
MGLLogDebug(@"Adding contentsOfFile: %@ completionHandler: %@", filePath, completion);
- (void)addContentsOfFile:(NSString *)filePath withCompletionHandler:(MLNBatchedOfflinePackAdditionCompletionHandler)completion {
MLNLogDebug(@"Adding contentsOfFile: %@ completionHandler: %@", filePath, completion);
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
[self addContentsOfURL:fileURL withCompletionHandler:completion];
}
- (void)addContentsOfURL:(NSURL *)fileURL withCompletionHandler:(MGLBatchedOfflinePackAdditionCompletionHandler)completion {
MGLLogDebug(@"Adding contentsOfURL: %@ completionHandler: %@", fileURL, completion);
- (void)addContentsOfURL:(NSURL *)fileURL withCompletionHandler:(MLNBatchedOfflinePackAdditionCompletionHandler)completion {
MLNLogDebug(@"Adding contentsOfURL: %@ completionHandler: %@", fileURL, completion);
NSFileManager *fileManager = [NSFileManager defaultManager];
if (!fileURL.isFileURL) {
@@ -340,23 +340,23 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
[NSException raise:NSInvalidArgumentException format:@"The file path: %@ must be writable", fileURL.absoluteString];
}
__weak MGLOfflineStorage *weakSelf = self;
[self _addContentsOfFile:fileURL.path withCompletionHandler:^(NSArray<MGLOfflinePack *> * _Nullable packs, NSError * _Nullable error) {
__weak MLNOfflineStorage *weakSelf = self;
[self _addContentsOfFile:fileURL.path withCompletionHandler:^(NSArray<MLNOfflinePack *> * _Nullable packs, NSError * _Nullable error) {
if (packs) {
NSMutableDictionary *packsByIdentifier = [NSMutableDictionary dictionary];
MGLOfflineStorage *strongSelf = weakSelf;
for (MGLOfflinePack *pack in packs) {
MLNOfflineStorage *strongSelf = weakSelf;
for (MLNOfflinePack *pack in packs) {
[packsByIdentifier setObject:pack forKey:@(pack.mbglOfflineRegion->getID())];
}
id mutablePacks = [strongSelf mutableArrayValueForKey:@"packs"];
NSMutableIndexSet *replaceIndexSet = [NSMutableIndexSet indexSet];
NSMutableArray *replacePacksArray = [NSMutableArray array];
[strongSelf.packs enumerateObjectsUsingBlock:^(MGLOfflinePack * _Nonnull pack, NSUInteger idx, BOOL * _Nonnull stop) {
MGLOfflinePack *newPack = packsByIdentifier[@(pack.mbglOfflineRegion->getID())];
[strongSelf.packs enumerateObjectsUsingBlock:^(MLNOfflinePack * _Nonnull pack, NSUInteger idx, BOOL * _Nonnull stop) {
MLNOfflinePack *newPack = packsByIdentifier[@(pack.mbglOfflineRegion->getID())];
if (newPack) {
MGLOfflinePack *previousPack = [mutablePacks objectAtIndex:idx];
MLNOfflinePack *previousPack = [mutablePacks objectAtIndex:idx];
[previousPack invalidate];
[replaceIndexSet addIndex:idx];
[replacePacksArray addObject:[packsByIdentifier objectForKey:@(newPack.mbglOfflineRegion->getID())]];
@@ -377,13 +377,13 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
}];
}
- (void)_addContentsOfFile:(NSString *)filePath withCompletionHandler:(void (^)(NSArray<MGLOfflinePack *> * _Nullable packs, NSError * _Nullable error))completion {
- (void)_addContentsOfFile:(NSString *)filePath withCompletionHandler:(void (^)(NSArray<MLNOfflinePack *> * _Nullable packs, NSError * _Nullable error))completion {
_mbglDatabaseFileSource->mergeOfflineRegions(std::string(static_cast<const char *>([filePath UTF8String])), [&, completion, filePath](mbgl::expected<mbgl::OfflineRegions, std::exception_ptr> result) {
NSError *error;
NSMutableArray *packs;
if (!result) {
NSString *description = [NSString stringWithFormat:NSLocalizedStringWithDefaultValue(@"ADD_FILE_CONTENTS_FAILED_DESC", @"Foundation", nil, @"Unable to add offline packs from the file at %@.", @"User-friendly error description"), filePath];
error = [NSError errorWithDomain:MGLErrorDomain code:MGLErrorCodeModifyingOfflineStorageFailed
error = [NSError errorWithDomain:MLNErrorDomain code:MLNErrorCodeModifyingOfflineStorageFailed
userInfo:@{
NSLocalizedDescriptionKey: description,
NSLocalizedFailureReasonErrorKey: @(mbgl::util::toString(result.error()).c_str())
@@ -392,7 +392,7 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
auto& regions = result.value();
packs = [NSMutableArray arrayWithCapacity:regions.size()];
for (auto &region : regions) {
MGLOfflinePack *pack = [[MGLOfflinePack alloc] initWithMBGLRegion:new mbgl::OfflineRegion(std::move(region))];
MLNOfflinePack *pack = [[MLNOfflinePack alloc] initWithMBGLRegion:new mbgl::OfflineRegion(std::move(region))];
[packs addObject:pack];
}
}
@@ -406,12 +406,12 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
// MARK: Pack management methods
- (void)addPackForRegion:(id <MGLOfflineRegion>)region withContext:(NSData *)context completionHandler:(MGLOfflinePackAdditionCompletionHandler)completion {
MGLLogDebug(@"Adding packForRegion: %@ contextLength: %lu completionHandler: %@", region, (unsigned long)context.length, completion);
__weak MGLOfflineStorage *weakSelf = self;
[self _addPackForRegion:region withContext:context completionHandler:^(MGLOfflinePack * _Nullable pack, NSError * _Nullable error) {
pack.state = MGLOfflinePackStateInactive;
MGLOfflineStorage *strongSelf = weakSelf;
- (void)addPackForRegion:(id <MLNOfflineRegion>)region withContext:(NSData *)context completionHandler:(MLNOfflinePackAdditionCompletionHandler)completion {
MLNLogDebug(@"Adding packForRegion: %@ contextLength: %lu completionHandler: %@", region, (unsigned long)context.length, completion);
__weak MLNOfflineStorage *weakSelf = self;
[self _addPackForRegion:region withContext:context completionHandler:^(MLNOfflinePack * _Nullable pack, NSError * _Nullable error) {
pack.state = MLNOfflinePackStateInactive;
MLNOfflineStorage *strongSelf = weakSelf;
[[strongSelf mutableArrayValueForKey:@"packs"] addObject:pack];
if (completion) {
completion(pack, error);
@@ -419,26 +419,26 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
}];
}
- (void)_addPackForRegion:(id <MGLOfflineRegion>)region withContext:(NSData *)context completionHandler:(MGLOfflinePackAdditionCompletionHandler)completion {
if (![region conformsToProtocol:@protocol(MGLOfflineRegion_Private)]) {
[NSException raise:MGLUnsupportedRegionTypeException
- (void)_addPackForRegion:(id <MLNOfflineRegion>)region withContext:(NSData *)context completionHandler:(MLNOfflinePackAdditionCompletionHandler)completion {
if (![region conformsToProtocol:@protocol(MLNOfflineRegion_Private)]) {
[NSException raise:MLNUnsupportedRegionTypeException
format:@"Regions of type %@ are unsupported.", NSStringFromClass([region class])];
return;
}
const mbgl::OfflineRegionDefinition regionDefinition = [(id <MGLOfflineRegion_Private>)region offlineRegionDefinition];
const mbgl::OfflineRegionDefinition regionDefinition = [(id <MLNOfflineRegion_Private>)region offlineRegionDefinition];
mbgl::OfflineRegionMetadata metadata(context.length);
[context getBytes:&metadata[0] length:metadata.size()];
_mbglDatabaseFileSource->createOfflineRegion(regionDefinition, metadata, [&, completion](mbgl::expected<mbgl::OfflineRegion, std::exception_ptr> mbglOfflineRegion) {
NSError *error;
if (!mbglOfflineRegion) {
NSString *errorDescription = @(mbgl::util::toString(mbglOfflineRegion.error()).c_str());
error = [NSError errorWithDomain:MGLErrorDomain code:MGLErrorCodeModifyingOfflineStorageFailed userInfo:errorDescription ? @{
error = [NSError errorWithDomain:MLNErrorDomain code:MLNErrorCodeModifyingOfflineStorageFailed userInfo:errorDescription ? @{
NSLocalizedDescriptionKey: errorDescription,
} : nil];
}
if (completion) {
MGLOfflinePack *pack = mbglOfflineRegion ? [[MGLOfflinePack alloc] initWithMBGLRegion:new mbgl::OfflineRegion(std::move(mbglOfflineRegion.value()))] : nil;
MLNOfflinePack *pack = mbglOfflineRegion ? [[MLNOfflinePack alloc] initWithMBGLRegion:new mbgl::OfflineRegion(std::move(mbglOfflineRegion.value()))] : nil;
dispatch_async(dispatch_get_main_queue(), [&, completion, error, pack](void) {
completion(pack, error);
});
@@ -446,8 +446,8 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
});
}
- (void)removePack:(MGLOfflinePack *)pack withCompletionHandler:(MGLOfflinePackRemovalCompletionHandler)completion {
MGLLogDebug(@"Removing pack: %@ completionHandler: %@", pack, completion);
- (void)removePack:(MLNOfflinePack *)pack withCompletionHandler:(MLNOfflinePackRemovalCompletionHandler)completion {
MLNLogDebug(@"Removing pack: %@ completionHandler: %@", pack, completion);
[[self mutableArrayValueForKey:@"packs"] removeObject:pack];
[self _removePack:pack withCompletionHandler:^(NSError * _Nullable error) {
if (completion) {
@@ -456,13 +456,13 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
}];
}
- (void)_removePack:(MGLOfflinePack *)pack withCompletionHandler:(MGLOfflinePackRemovalCompletionHandler)completion {
- (void)_removePack:(MLNOfflinePack *)pack withCompletionHandler:(MLNOfflinePackRemovalCompletionHandler)completion {
mbgl::OfflineRegion *mbglOfflineRegion = pack.mbglOfflineRegion;
[pack invalidate];
if (!mbglOfflineRegion) {
MGLAssert(pack.state == MGLOfflinePackStateInvalid, @"State should be invalid");
MLNAssert(pack.state == MLNOfflinePackStateInvalid, @"State should be invalid");
completion(nil);
return;
}
@@ -470,7 +470,7 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
_mbglDatabaseFileSource->deleteOfflineRegion(std::move(*mbglOfflineRegion), [&, completion](std::exception_ptr exception) {
NSError *error;
if (exception) {
error = [NSError errorWithDomain:MGLErrorDomain code:MGLErrorCodeModifyingOfflineStorageFailed userInfo:@{
error = [NSError errorWithDomain:MLNErrorDomain code:MLNErrorCodeModifyingOfflineStorageFailed userInfo:@{
NSLocalizedDescriptionKey: @(mbgl::util::toString(exception).c_str()),
}];
}
@@ -483,7 +483,7 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
}
- (void)invalidatePack:(MGLOfflinePack *)pack withCompletionHandler:(void (^)(NSError * _Nullable))completion {
- (void)invalidatePack:(MLNOfflinePack *)pack withCompletionHandler:(void (^)(NSError * _Nullable))completion {
mbgl::OfflineRegion& region = *pack.mbglOfflineRegion;
NSError *error;
if (!pack.mbglOfflineRegion) {
@@ -493,7 +493,7 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
_mbglDatabaseFileSource->invalidateOfflineRegion(region, [&](std::exception_ptr exception) {
if (exception) {
error = [NSError errorWithDomain:MGLErrorDomain code:MGLErrorCodeModifyingOfflineStorageFailed userInfo:@{
error = [NSError errorWithDomain:MLNErrorDomain code:MLNErrorCodeModifyingOfflineStorageFailed userInfo:@{
NSLocalizedDescriptionKey: @(mbgl::util::toString(exception).c_str()),
}];
}
@@ -506,28 +506,28 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
}
- (void)reloadPacks {
MGLLogInfo(@"Reloading packs.");
[self getPacksWithCompletionHandler:^(NSArray<MGLOfflinePack *> *packs, __unused NSError * _Nullable error) {
for (MGLOfflinePack *pack in self.packs) {
MLNLogInfo(@"Reloading packs.");
[self getPacksWithCompletionHandler:^(NSArray<MLNOfflinePack *> *packs, __unused NSError * _Nullable error) {
for (MLNOfflinePack *pack in self.packs) {
[pack invalidate];
}
self.packs = [packs mutableCopy];
}];
}
- (void)getPacksWithCompletionHandler:(void (^)(NSArray<MGLOfflinePack *> *packs, NSError * _Nullable error))completion {
- (void)getPacksWithCompletionHandler:(void (^)(NSArray<MLNOfflinePack *> *packs, NSError * _Nullable error))completion {
_mbglDatabaseFileSource->listOfflineRegions([&, completion](mbgl::expected<mbgl::OfflineRegions, std::exception_ptr> result) {
NSError *error;
NSMutableArray *packs;
if (!result) {
error = [NSError errorWithDomain:MGLErrorDomain code:MGLErrorCodeUnknown userInfo:@{
error = [NSError errorWithDomain:MLNErrorDomain code:MLNErrorCodeUnknown userInfo:@{
NSLocalizedDescriptionKey: @(mbgl::util::toString(result.error()).c_str()),
}];
} else {
auto& regions = result.value();
packs = [NSMutableArray arrayWithCapacity:regions.size()];
for (auto &region : regions) {
MGLOfflinePack *pack = [[MGLOfflinePack alloc] initWithMBGLRegion:new mbgl::OfflineRegion(std::move(region))];
MLNOfflinePack *pack = [[MLNOfflinePack alloc] initWithMBGLRegion:new mbgl::OfflineRegion(std::move(region))];
[packs addObject:pack];
}
}
@@ -540,7 +540,7 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
}
- (void)setMaximumAllowedMapboxTiles:(uint64_t)maximumCount {
MGLLogDebug(@"Setting maximumAllowedMapboxTiles: %lu", (unsigned long)maximumCount);
MLNLogDebug(@"Setting maximumAllowedMapboxTiles: %lu", (unsigned long)maximumCount);
_mbglDatabaseFileSource->setOfflineMapboxTileCountLimit(maximumCount);
}
@@ -551,7 +551,7 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
NSError *error;
if (completion) {
if (exception) {
error = [NSError errorWithDomain:MGLErrorDomain code:MGLErrorCodeModifyingOfflineStorageFailed userInfo:@{
error = [NSError errorWithDomain:MLNErrorDomain code:MLNErrorCodeModifyingOfflineStorageFailed userInfo:@{
NSLocalizedDescriptionKey: @(mbgl::util::toString(exception).c_str()),
}];
}
@@ -568,7 +568,7 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
if (completion) {
if (exception) {
// Convert std::exception_ptr to an NSError.
error = [NSError errorWithDomain:MGLErrorDomain code:MGLErrorCodeModifyingOfflineStorageFailed userInfo:@{
error = [NSError errorWithDomain:MLNErrorDomain code:MLNErrorCodeModifyingOfflineStorageFailed userInfo:@{
NSLocalizedDescriptionKey: @(mbgl::util::toString(exception).c_str()),
}];
}
@@ -584,7 +584,7 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
NSError *error;
if (completion) {
if (exception) {
error = [NSError errorWithDomain:MGLErrorDomain code:MGLErrorCodeModifyingOfflineStorageFailed userInfo:@{
error = [NSError errorWithDomain:MLNErrorDomain code:MLNErrorCodeModifyingOfflineStorageFailed userInfo:@{
NSLocalizedDescriptionKey: @(mbgl::util::toString(exception).c_str()),
}];
}
@@ -600,7 +600,7 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
NSError *error;
if (completion) {
if (exception) {
error = [NSError errorWithDomain:MGLErrorDomain code:MGLErrorCodeUnknown userInfo:@{
error = [NSError errorWithDomain:MLNErrorDomain code:MLNErrorCodeUnknown userInfo:@{
NSLocalizedDescriptionKey: @(mbgl::util::toString(exception).c_str()),
}];
}
@@ -622,7 +622,7 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
}
- (void)preloadData:(NSData *)data forURL:(NSURL *)url modificationDate:(nullable NSDate *)modified expirationDate:(nullable NSDate *)expires eTag:(nullable NSString *)eTag mustRevalidate:(BOOL)mustRevalidate
completionHandler:(nullable MGLOfflinePreloadDataCompletionHandler)completion {
completionHandler:(nullable MLNOfflinePreloadDataCompletionHandler)completion {
mbgl::Resource resource(mbgl::Resource::Kind::Unknown, url.absoluteString.UTF8String);
mbgl::Response response;
response.data = std::make_shared<std::string>(static_cast<const char*>(data.bytes), data.length);
@@ -633,11 +633,11 @@ const MGLExceptionName MGLUnsupportedRegionTypeException = @"MGLUnsupportedRegio
}
if (modified) {
response.modified = mbgl::Timestamp() + std::chrono::duration_cast<mbgl::Seconds>(MGLDurationFromTimeInterval(modified.timeIntervalSince1970));
response.modified = mbgl::Timestamp() + std::chrono::duration_cast<mbgl::Seconds>(MLNDurationFromTimeInterval(modified.timeIntervalSince1970));
}
if (expires) {
response.expires = mbgl::Timestamp() + std::chrono::duration_cast<mbgl::Seconds>(MGLDurationFromTimeInterval(expires.timeIntervalSince1970));
response.expires = mbgl::Timestamp() + std::chrono::duration_cast<mbgl::Seconds>(MLNDurationFromTimeInterval(expires.timeIntervalSince1970));
}
std::function<void()> callback;

Some files were not shown because too many files have changed in this diff Show More