UNPKG

nativescript-mapbox

Version:

A Nativescript plugin for Mapbox Native Maps.

1,177 lines (1,123 loc) 83 kB
"use strict"; var _this = this; Object.defineProperty(exports, "__esModule", { value: true }); var fs = require("tns-core-modules/file-system"); var imgSrc = require("tns-core-modules/image-source"); var utils = require("tns-core-modules/utils/utils"); var http = require("tns-core-modules/http"); var color_1 = require("tns-core-modules/color"); var mapbox_common_1 = require("./mapbox.common"); exports.MapStyle = mapbox_common_1.MapStyle; var geo_utils_1 = require("./geo.utils"); var _markers = []; var _markerIconDownloadCache = []; var _setMapboxMapOptions = function (mapView, settings) { mapView.logoView.hidden = settings.hideLogo; mapView.attributionButton.hidden = settings.hideAttribution; mapView.compassView.hidden = settings.hideCompass; mapView.rotateEnabled = !settings.disableRotation; mapView.scrollEnabled = !settings.disableScroll; mapView.zoomEnabled = !settings.disableZoom; mapView.allowsTilting = !settings.disableTilt; if (settings.center && settings.center.lat && settings.center.lng) { var centerCoordinate = CLLocationCoordinate2DMake(settings.center.lat, settings.center.lng); mapView.setCenterCoordinateZoomLevelAnimated(centerCoordinate, settings.zoomLevel, false); } else { mapView.setZoomLevelAnimated(settings.zoomLevel, false); } mapView.showsUserLocation = settings.showUserLocation; mapView.autoresizingMask = 2 | 16; }; var _getMapStyle = function (input) { if (/^mapbox:\/\/styles/.test(input) || /^http:\/\//.test(input) || /^https:\/\//.test(input)) { return NSURL.URLWithString(input); } else if (/^~\//.test(input)) { var assetPath = 'file://' + fs.knownFolders.currentApp().path + '/'; input = input.replace(/^~\//, assetPath); return NSURL.URLWithString(input); } else if (input === mapbox_common_1.MapStyle.LIGHT || input === mapbox_common_1.MapStyle.LIGHT.toString()) { return MGLStyle.lightStyleURL; } else if (input === mapbox_common_1.MapStyle.DARK || input === mapbox_common_1.MapStyle.DARK.toString()) { return MGLStyle.darkStyleURL; } else if (input === mapbox_common_1.MapStyle.OUTDOORS || input === mapbox_common_1.MapStyle.OUTDOORS.toString()) { return MGLStyle.outdoorsStyleURL; } else if (input === mapbox_common_1.MapStyle.SATELLITE || input === mapbox_common_1.MapStyle.SATELLITE.toString()) { return MGLStyle.satelliteStyleURL; } else if (input === mapbox_common_1.MapStyle.SATELLITE_STREETS || input === mapbox_common_1.MapStyle.SATELLITE_STREETS.toString()) { return MGLStyle.satelliteStreetsStyleURL; } else if (input === mapbox_common_1.MapStyle.TRAFFIC_DAY || input === mapbox_common_1.MapStyle.TRAFFIC_DAY.toString()) { return NSURL.URLWithString("mapbox://styles/mapbox/traffic-day-v2"); } else if (input === mapbox_common_1.MapStyle.TRAFFIC_NIGHT || input === mapbox_common_1.MapStyle.TRAFFIC_NIGHT.toString()) { return NSURL.URLWithString("mapbox://styles/mapbox/traffic-night-v2"); } else { return MGLStyle.streetsStyleURL; } }; var _getTrackingMode = function (input) { return 0; }; var MapboxView = (function (_super) { __extends(MapboxView, _super); function MapboxView() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.nativeMapView = null; _this.delegate = null; _this.settings = null; _this.initialized = false; _this.initCountHack = 50; return _this; } MapboxView.prototype.setConfig = function (settings) { this.settings = settings; }; MapboxView.prototype.getNativeMapView = function () { return this.nativeMapView; }; MapboxView.prototype.createNativeView = function () { var v = _super.prototype.createNativeView.call(this); return v; }; MapboxView.prototype.initNativeView = function () { var _this = this; this.nativeView.owner = this; _super.prototype.initNativeView.call(this); this.on('loaded', function () { if (!_this.initialized) { _this.initMap(); _this.initialized = true; } else { } }); this.on('unloaded', function () { }); }; MapboxView.prototype.disposeNativeView = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: this.nativeView.owner = null; return [4, this.mapbox.destroy()]; case 1: _a.sent(); _super.prototype.disposeNativeView.call(this); return [2]; } }); }); }; MapboxView.prototype.getMapboxApi = function () { return this.mapbox; }; MapboxView.prototype.initMap = function () { var _this = this; if (!this.settings && !this.config.accessToken) { if (this.initCountHack > 50) { return; } setTimeout(function () { _this.initMap(); }, 50); this.initCountHack++; return; } if (!this.settings) { this.settings = Mapbox.merge(this.config, Mapbox.defaults); } else { this.settings = Mapbox.merge(this.settings, Mapbox.defaults); } if (!this.nativeMapView) { this.mapbox = new Mapbox(); var drawMap = function () { MGLAccountManager.accessToken = _this.settings.accessToken; _this.nativeMapView = MGLMapView.alloc().initWithFrameStyleURL(CGRectMake(0, 0, _this.nativeView.frame.size.width, _this.nativeView.frame.size.height), _getMapStyle(_this.settings.style)); _this.nativeMapView.delegate = _this.delegate = MGLMapViewDelegateImpl.new().initWithCallback(function () { _this.mapbox.setMapboxViewInstance(_this.nativeMapView); _this.notify({ eventName: mapbox_common_1.MapboxViewBase.mapReadyEvent, object: _this, map: _this, ios: _this.nativeMapView }); _this.notify({ eventName: mapbox_common_1.MapboxViewBase.locationPermissionGrantedEvent, object: _this, map: _this, ios: _this.nativeMapView }); }); _setMapboxMapOptions(_this.nativeMapView, _this.settings); _markers = []; _this.nativeView.addSubview(_this.nativeMapView); _this.mapbox.setOnMoveBeginListener(function (data) { _this.notify({ eventName: mapbox_common_1.MapboxViewBase.moveBeginEvent, object: _this, map: _this, ios: _this.nativeMapView }); }, _this.nativeMapView); }; setTimeout(drawMap, this.settings.delay ? this.settings.delay : 0); } }; MapboxView.prototype.onLayout = function (left, top, right, bottom) { _super.prototype.onLayout.call(this, left, top, right, bottom); if (this.nativeMapView) { this.nativeMapView.layer.frame = this.ios.layer.bounds; } }; return MapboxView; }(mapbox_common_1.MapboxViewBase)); exports.MapboxView = MapboxView; var CustomUserLocationAnnotationView = (function (_super) { __extends(CustomUserLocationAnnotationView, _super); function CustomUserLocationAnnotationView() { return _super !== null && _super.apply(this, arguments) || this; } CustomUserLocationAnnotationView.prototype.init = function () { this.size = 48; _super.prototype.initWithFrame.call(this, CGRectMake(0, 0, this.size, this.size)); this.renderModeChanged = true; this.userLocationRenderMode = 'NORMAL'; return this; }; CustomUserLocationAnnotationView.prototype.update = function () { if (CLLocationCoordinate2DIsValid(this.userLocation.coordinate)) { if (!this.dot) { this.drawNonTrackingLocationMarker(); } if (this.userLocationRenderMode == 'GPS') { this.updateHeading(); } } }; CustomUserLocationAnnotationView.prototype.drawTrackingLocationMarker = function () { this.drawTrackingDot(); this.drawArrow(); }; CustomUserLocationAnnotationView.prototype.drawNonTrackingLocationMarker = function () { this.drawNonTrackingDot(); if (this.arrow) { this.arrow.removeFromSuperlayer(); this.arrow = null; } }; CustomUserLocationAnnotationView.prototype.drawTrackingDot = function () { this.size = 48; this.bounds = CGRectMake(0, 0, this.size, this.size); var dot = CALayer.layer(); dot.frame = this.bounds; dot.cornerRadius = this.size / 2; dot.backgroundColor = this.tintColor.CGColor; dot.borderWidth = 4; var whiteColor = new color_1.Color("#FFFFFF"); dot.borderColor = whiteColor.ios.CGColor; if (!this.dot) { this.layer.addSublayer(dot); } else { this.layer.replaceSublayerWith(this.dot, dot); } this.dot = dot; }; CustomUserLocationAnnotationView.prototype.drawNonTrackingDot = function () { this.size = 24; this.bounds = CGRectMake(0, 0, this.size, this.size); var dot = CALayer.layer(); dot.frame = this.bounds; dot.cornerRadius = this.size / 2; dot.backgroundColor = this.tintColor.CGColor; dot.borderWidth = 1; var whiteColor = new color_1.Color("#FFFFFF"); dot.borderColor = whiteColor.ios.CGColor; if (!this.dot) { this.layer.addSublayer(dot); } else { this.layer.replaceSublayerWith(this.dot, dot); } this.dot = dot; }; CustomUserLocationAnnotationView.prototype.drawArrow = function () { var arrow = CAShapeLayer.layer(); arrow.path = this.arrowPath(); arrow.frame = CGRectMake(0, 0, this.size / 2, this.size / 2); arrow.position = CGPointMake(CGRectGetMidX(this.dot.frame), CGRectGetMidY(this.dot.frame)); arrow.fillColor = this.dot.borderColor; if (!this.arrow) { this.layer.addSublayer(arrow); } else { this.layer.replaceSublayerWith(this.arrow, arrow); } this.arrow = arrow; }; CustomUserLocationAnnotationView.prototype.updateHeading = function () { if (!this.arrow) { return; } if (typeof this.userLocation == 'undefined') { return; } if ((typeof this.userLocation.heading == 'undefined') || (this.userLocation.heading === null)) { return; } if ((typeof this.userLocation.heading.trueHeading == 'undefined') || (this.userLocation.heading.trueHeading === null)) { return; } if (this.userLocation.heading.trueHeading > 0) { this.arrow.hidden = false; var degrees = this.mapView.direction - this.userLocation.heading.trueHeading; var rotation = degrees * Math.PI / 180; rotation = -rotation; if (fabs(rotation) > 0.01) { CATransaction.begin(); CATransaction.setDisableActions(true); this.arrow.setAffineTransform(CGAffineTransformRotate(CGAffineTransformIdentity, rotation)); CATransaction.commit(); } } else { this.arrow.hidden = true; } }; CustomUserLocationAnnotationView.prototype.arrowPath = function () { var max = this.size / 2; var pad = 3; var top = CGPointMake(max * 0.5, 0); var left = CGPointMake(0 + pad, max - pad); var right = CGPointMake(max - pad, max - pad); var center = CGPointMake(max * 0.5, max * 0.6); var bezierPath = UIBezierPath.bezierPath(); bezierPath.moveToPoint(top); bezierPath.addLineToPoint(left); bezierPath.addLineToPoint(center); bezierPath.addLineToPoint(right); bezierPath.addLineToPoint(top); bezierPath.closePath(); return bezierPath.CGPath; }; CustomUserLocationAnnotationView.prototype.changeUserLocationRenderMode = function (renderMode) { this.userLocationRenderMode = renderMode; if (renderMode == 'GPS') { this.drawTrackingLocationMarker(); } else { this.drawNonTrackingLocationMarker(); } }; return CustomUserLocationAnnotationView; }(MGLUserLocationAnnotationView)); exports.CustomUserLocationAnnotationView = CustomUserLocationAnnotationView; var Mapbox = (function (_super) { __extends(Mapbox, _super); function Mapbox() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.circles = []; _this.lines = []; _this.eventCallbacks = []; return _this; } Mapbox.prototype.setMapboxMapInstance = function (mapboxMapInstance) { this._mapboxMapInstance = mapboxMapInstance; }; Mapbox.prototype.setMapboxViewInstance = function (mapboxViewInstance) { this._mapboxViewInstance = mapboxViewInstance; }; Mapbox.prototype.initEventHandlerShim = function (settings, mapboxNativeViewInstance) { var _this = this; this.setOnMapClickListener(function (point) { return _this.checkForCircleClickEvent(point); }, mapboxNativeViewInstance); }; Mapbox.prototype.onMapEvent = function (eventName, id, callback, nativeMapView) { }; Mapbox.prototype.offMapEvent = function (eventName, id, nativeMapView) { }; Mapbox.prototype.checkForCircleClickEvent = function (point) { for (var i = 0; i < this.circles.length; i++) { if (geo_utils_1.GeoUtils.isLocationInCircle(point.lng, point.lat, this.circles[i].center[0], this.circles[i].center[1], this.circles[i].radius)) { for (var x = 0; x < this.eventCallbacks['click'].length; x++) { var entry = this.eventCallbacks['click'][x]; if (entry.id == this.circles[i].id) { return entry.callback(point); } } } } return false; }; Mapbox.prototype.show = function (options) { var _this = this; return new Promise(function (resolve, reject) { try { var settings = Mapbox.merge(options, Mapbox.defaults); if (settings.accessToken === undefined) { reject("Please set the 'accessToken' parameter"); return; } if (_this._mapboxViewInstance) { _this._mapboxViewInstance.removeFromSuperview(); } var view_1 = utils.ios.getter(UIApplication, UIApplication.sharedApplication).keyWindow.rootViewController.view, frameRect = view_1.frame, mapFrame = CGRectMake(settings.margins.left, settings.margins.top, frameRect.size.width - settings.margins.left - settings.margins.right, frameRect.size.height - settings.margins.top - settings.margins.bottom), styleURL = _getMapStyle(settings.style); MGLAccountManager.accessToken = settings.accessToken; _this._mapboxViewInstance = MGLMapView.alloc().initWithFrameStyleURL(mapFrame, styleURL); _setMapboxMapOptions(_this._mapboxViewInstance, settings); _this._mapboxViewInstance.delegate = MGLMapViewDelegateImpl.new().initWithCallback(function (mapView) { resolve({ ios: mapView }); }); _markers = []; _addMarkers(settings.markers); setTimeout(function () { view_1.addSubview(_this._mapboxViewInstance); }, 500); } catch (ex) { reject(ex); } }); }; Mapbox.prototype.hide = function () { var _this = this; return new Promise(function (resolve, reject) { try { if (_this._mapboxViewInstance) { _this._mapboxViewInstance.removeFromSuperview(); } resolve(); } catch (ex) { reject(ex); } }); }; Mapbox.prototype.unhide = function () { var _this = this; return new Promise(function (resolve, reject) { try { if (_this._mapboxViewInstance) { var view = utils.ios.getter(UIApplication, UIApplication.sharedApplication).keyWindow.rootViewController.view; view.addSubview(_this._mapboxViewInstance); resolve(); } else { reject("No map found"); } } catch (ex) { reject(ex); } }); }; Mapbox.prototype.destroy = function (nativeMap) { var _this = this; return new Promise(function (resolve, reject) { var theMap = nativeMap || _this._mapboxViewInstance; if (theMap) { theMap.removeFromSuperview(); theMap.delegate = null; } resolve(); }); }; Mapbox.prototype.onStart = function (nativeMap) { return Promise.resolve(); }; Mapbox.prototype.onResume = function (nativeMap) { return Promise.resolve(); }; Mapbox.prototype.onPause = function (nativeMap) { return Promise.resolve(); }; Mapbox.prototype.onStop = function (nativeMap) { return Promise.resolve(); }; Mapbox.prototype.onLowMemory = function (nativeMap) { return Promise.resolve(); }; Mapbox.prototype.onDestroy = function (nativeMap) { return Promise.resolve(); }; Mapbox.prototype.setMapStyle = function (style, nativeMap) { var _this = this; return new Promise(function (resolve, reject) { try { var theMap = nativeMap || _this._mapboxViewInstance; var delegate = theMap.delegate; delegate.setStyleLoadedCallback(function (mapView) { resolve(); }); theMap.styleURL = _getMapStyle(style); } catch (ex) { reject(ex); } }); }; Mapbox.prototype.addMarkers = function (markers, nativeMap) { var _this = this; return new Promise(function (resolve, reject) { try { var theMap = nativeMap || _this._mapboxViewInstance; _addMarkers(markers, theMap); resolve(); } catch (ex) { reject(ex); } }); }; Mapbox.prototype.removeMarkers = function (ids, nativeMap) { var _this = this; return new Promise(function (resolve, reject) { try { var theMap = nativeMap || _this._mapboxViewInstance; var markersToRemove_1 = []; _markers.forEach(function (marker) { if (!ids || (marker.id && ids.indexOf(marker.id) > -1)) { markersToRemove_1.push(marker.ios); } }); if (ids) { _markers = _markers.filter(function (marker) { return ids.indexOf(marker.id) < 0; }); } else { _markers = []; } if (markersToRemove_1.length > 0) { theMap.removeAnnotations(markersToRemove_1); } resolve(); } catch (ex) { reject(ex); } }); }; Mapbox.prototype.setCenter = function (options, nativeMap) { var _this = this; return new Promise(function (resolve, reject) { try { var theMap = nativeMap || _this._mapboxViewInstance; var animated = options.animated === undefined || options.animated; var coordinate = CLLocationCoordinate2DMake(options.lat, options.lng); theMap.setCenterCoordinateAnimated(coordinate, animated); resolve(); } catch (ex) { reject(ex); } }); }; Mapbox.prototype.getCenter = function (nativeMap) { var _this = this; return new Promise(function (resolve, reject) { try { var theMap = nativeMap || _this._mapboxViewInstance; var coordinate = theMap.centerCoordinate; resolve({ lat: coordinate.latitude, lng: coordinate.longitude }); } catch (ex) { reject(ex); } }); }; Mapbox.prototype.setZoomLevel = function (options, nativeMap) { var _this = this; return new Promise(function (resolve, reject) { try { var theMap = nativeMap || _this._mapboxViewInstance; var animated = options.animated === undefined || options.animated; var level = options.level; if (level >= 0 && level <= 20) { theMap.setZoomLevelAnimated(level, animated); resolve(); } else { reject("invalid ZoomLevel, use any double value from 0 to 20 (like 8.3)"); } } catch (ex) { reject(ex); } }); }; Mapbox.prototype.getZoomLevel = function (nativeMap) { var _this = this; return new Promise(function (resolve, reject) { try { var theMap = nativeMap || _this._mapboxViewInstance; resolve(theMap.zoomLevel); } catch (ex) { reject(ex); } }); }; Mapbox.prototype.setTilt = function (options, nativeMap) { var _this = this; return new Promise(function (resolve, reject) { try { var theMap = nativeMap || _this._mapboxViewInstance; var cam = theMap.camera; cam.pitch = options.tilt; var durationMs = options.duration ? options.duration : 5000; theMap.setCameraWithDurationAnimationTimingFunction(cam, durationMs / 1000, CAMediaTimingFunction.functionWithName(kCAMediaTimingFunctionEaseInEaseOut)); setTimeout(function () { resolve(); }, durationMs); } catch (ex) { reject(ex); } }); }; Mapbox.prototype.getTilt = function (nativeMap) { var _this = this; return new Promise(function (resolve, reject) { try { var theMap = nativeMap || _this._mapboxViewInstance; resolve(theMap.camera.pitch); } catch (ex) { reject(ex); } }); }; Mapbox.prototype.getUserLocation = function (nativeMap) { var _this = this; return new Promise(function (resolve, reject) { try { var theMap = nativeMap || _this._mapboxViewInstance; var loc = theMap.userLocation; if (loc === null) { reject("Location not available"); } else { resolve({ location: { lat: loc.coordinate.latitude, lng: loc.coordinate.longitude }, speed: loc.location ? loc.location.speed : 0 }); } } catch (ex) { reject(ex); } }); }; Mapbox.prototype._stringToCameraMode = function (mode) { switch (mode) { case "NONE": return 0; case "NONE_COMPASS": return 0; case "NONE_GPS": return 0; case "TRACKING": return 1; case "TRACK_COMPASS": return 2; case "TRACKING_GPS": return 1; case "TRACK_GPS_NORTH": return 3; } }; Mapbox.prototype._stringToRenderMode = function (mode) { var renderMode; switch (mode) { case 'NORMAL': return 'NORMAL'; case 'COMPASS': return 'COMPASS'; case 'GPS': return 'GPS'; } }; Mapbox.prototype.showUserLocationMarker = function (options, nativeMap) { var _this = this; return new Promise(function (resolve, reject) { try { var theMap = nativeMap || _this._mapboxViewInstance; theMap.showsUserLocation = true; theMap.userTrackingMode = _this._stringToCameraMode(options.cameraMode); theMap.showsUserHeadingIndicator = true; _this.userLocationRenderMode = _this._stringToRenderMode(options.renderMode); var delegate = theMap.delegate; delegate.changeUserLocationRenderMode(_this.userLocationRenderMode); if (typeof options.clickListener != 'undefined') { delegate.setUserLocationClickListener(options.clickListener); } resolve(); } catch (ex) { reject(ex); } }); }; Mapbox.prototype.hideUserLocationMarker = function (nativeMap) { return new Promise(function (resolve, reject) { try { resolve(); } catch (ex) { reject(ex); } }); }; Mapbox.prototype.changeUserLocationMarkerMode = function (renderModeString, cameraModeString, nativeMap) { var _this = this; return new Promise(function (resolve, reject) { try { var theMap = nativeMap || _this._mapboxViewInstance; theMap.userTrackingMode = _this._stringToCameraMode(cameraModeString); var delegate = theMap.delegate; var renderMode = _this._stringToRenderMode(renderModeString); delegate.changeUserLocationRenderMode(renderMode); } catch (ex) { reject(ex); } }); }; Mapbox.prototype.forceUserLocationUpdate = function (location, nativeMap) { }; Mapbox.prototype.queryRenderedFeatures = function (options, nativeMap) { var _this = this; return new Promise(function (resolve, reject) { try { var theMap = nativeMap || _this._mapboxViewInstance; var point = options.point; if (point === undefined) { reject("Please set the 'point' parameter"); return; } var _a = theMap.convertCoordinateToPointToView({ latitude: point.lat, longitude: point.lng }, theMap), x = _a.x, y = _a.y; var features = theMap.visibleFeaturesAtPoint({ x: x, y: y }); var result = []; for (var i = 0; i < features.count; i++) { var feature = features.objectAtIndex(i); var properties = []; if (feature.attributes && feature.attributes.count > 0) { var keys = utils.ios.collections.nsArrayToJSArray(feature.attributes.allKeys); for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) { var key = keys_1[_i]; properties.push({ key: key, value: feature.attributes.valueForKey(key), }); } } result.push({ id: feature.identifier, properties: properties, }); } resolve(result); } catch (ex) { reject(ex); } }); }; Mapbox.prototype.addPolygon = function (options, nativeMap) { var _this = this; return new Promise(function (resolve, reject) { var theMap = nativeMap || _this._mapboxViewInstance; var points = options.points; if (points === undefined) { reject("Please set the 'points' parameter"); return; } var coordinateArray = []; points.forEach(function (point) { return coordinateArray.push([point.lng, point.lat]); }); var polygonID = "polygon_" + (options.id || new Date().getTime()); if (theMap.style.sourceWithIdentifier(polygonID)) { reject("Remove the polygon with this id first with 'removePolygons': " + polygonID); return; } var geoJSON = "{\n \"type\": \"FeatureCollection\",\n \"features\": [\n {\n \"id\": " + JSON.stringify(polygonID) + ",\n \"type\": \"Feature\",\n \"properties\": {\n },\n \"geometry\": {\n \"type\": \"Polygon\",\n \"coordinates\": [" + JSON.stringify(coordinateArray) + "]\n }\n }\n ]\n }"; var geoDataStr = NSString.stringWithString(geoJSON); var geoData = geoDataStr.dataUsingEncoding(NSUTF8StringEncoding); var geoDataBase64Enc = geoData.base64EncodedStringWithOptions(0); var geo = NSData.alloc().initWithBase64EncodedStringOptions(geoDataBase64Enc, null); var shape = MGLShape.shapeWithDataEncodingError(geo, NSUTF8StringEncoding); var source = MGLShapeSource.alloc().initWithIdentifierShapeOptions(polygonID, shape, null); theMap.style.addSource(source); if (options.strokeColor || options.strokeWidth || options.strokeOpacity) { var strokeLayer = MGLLineStyleLayer.alloc().initWithIdentifierSource(polygonID + "_stroke", source); strokeLayer.lineColor = NSExpression.expressionForConstantValue(!options.strokeColor ? UIColor.blackColor : (options.strokeColor instanceof color_1.Color ? options.strokeColor.ios : new color_1.Color(options.strokeColor).ios)); strokeLayer.lineWidth = NSExpression.expressionForConstantValue(options.strokeWidth || 5); strokeLayer.lineOpacity = NSExpression.expressionForConstantValue(options.strokeOpacity === undefined ? 1 : options.strokeOpacity); theMap.style.addLayer(strokeLayer); } var layer = MGLFillStyleLayer .alloc() .initWithIdentifierSource(polygonID, source); layer.fillColor = NSExpression.expressionForConstantValue(!options.fillColor ? UIColor.blackColor : (options.fillColor instanceof color_1.Color ? options.fillColor.ios : new color_1.Color(options.fillColor).ios)); layer.fillOpacity = NSExpression.expressionForConstantValue(options.fillOpacity === undefined ? 1 : options.fillOpacity); theMap.style.addLayer(layer); resolve(); }); }; Mapbox.prototype.addPolyline = function (options, nativeMap) { var _this = this; return new Promise(function (resolve, reject) { var theMap = nativeMap || _this._mapboxViewInstance; var points = options.points; if (points === undefined) { reject("Please set the 'points' parameter"); return; } var coordinateArray = []; points.forEach(function (point) { return coordinateArray.push([point.lng, point.lat]); }); var polylineID = "polyline_" + (options.id || new Date().getTime()); if (theMap.style.sourceWithIdentifier(polylineID)) { reject("Remove the polyline with this id first with 'removePolylines': " + polylineID); return; } var geoJSON = "{\"type\": \"FeatureCollection\", \"features\": [{\"type\": \"Feature\",\"properties\": {},\"geometry\": {\"type\": \"LineString\", \"coordinates\": " + JSON.stringify(coordinateArray) + "}}]}"; var geoDataStr = NSString.stringWithString(geoJSON); var geoData = geoDataStr.dataUsingEncoding(NSUTF8StringEncoding); var geoDataBase64Enc = geoData.base64EncodedStringWithOptions(0); var geo = NSData.alloc().initWithBase64EncodedStringOptions(geoDataBase64Enc, null); var shape = MGLShape.shapeWithDataEncodingError(geo, NSUTF8StringEncoding); var source = MGLShapeSource.alloc().initWithIdentifierShapeOptions(polylineID, shape, null); theMap.style.addSource(source); var layer = MGLLineStyleLayer.alloc().initWithIdentifierSource(polylineID, source); layer.lineColor = NSExpression.expressionForConstantValue(!options.color ? UIColor.blackColor : (options.color instanceof color_1.Color ? options.color.ios : new color_1.Color(options.color).ios)); layer.lineWidth = NSExpression.expressionForConstantValue(options.width || 5); layer.lineOpacity = NSExpression.expressionForConstantValue(options.opacity === undefined ? 1 : options.opacity); theMap.style.addLayer(layer); resolve(); }); }; Mapbox.prototype.removePolyById = function (theMap, id) { var layer = theMap.style.layerWithIdentifier(id); if (layer !== null) { theMap.style.removeLayer(layer); } layer = theMap.style.layerWithIdentifier(id + "_stroke"); if (layer !== null) { theMap.style.removeLayer(layer); } var source = theMap.style.sourceWithIdentifier(id); if (source !== null) { theMap.style.removeSource(source); } }; Mapbox.prototype.removePolys = function (polyType, ids, nativeMap) { var _this = this; return new Promise(function (resolve) { var theMap = nativeMap || _this._mapboxViewInstance; ids.forEach(function (id) { return _this.removePolyById(theMap, polyType + id); }); resolve(); }); }; Mapbox.prototype.removePolygons = function (ids, nativeMap) { return this.removePolys("polygon_", ids, nativeMap); }; Mapbox.prototype.removePolylines = function (ids, nativeMap) { return this.removePolys("polyline_", ids, nativeMap); }; Mapbox.prototype.animateCamera = function (options, nativeMap) { var _this = this; return new Promise(function (resolve, reject) { try { var theMap = nativeMap || _this._mapboxViewInstance; var target = options.target; if (target === undefined) { reject("Please set the 'target' parameter"); return; } var cam = theMap.camera; cam.centerCoordinate = CLLocationCoordinate2DMake(target.lat, target.lng); if (options.altitude) { cam.altitude = options.altitude; } if (options.bearing) { cam.heading = options.bearing; } if (options.tilt) { cam.pitch = options.tilt; } var durationMs = options.duration ? options.duration : 10000; theMap.setCameraWithDurationAnimationTimingFunction(cam, durationMs / 1000, CAMediaTimingFunction.functionWithName(kCAMediaTimingFunctionEaseInEaseOut)); setTimeout(function () { resolve(); }, durationMs); } catch (ex) { reject(ex); } }); }; Mapbox.prototype.setOnMapClickListener = function (listener, nativeMap) { var _this = this; return new Promise(function (resolve, reject) { try { var theMap = nativeMap || _this._mapboxViewInstance; if (!theMap) { reject("No map has been loaded"); return; } theMap['mapTapHandler'] = MapTapHandlerImpl.initWithOwnerAndListenerForMap(new WeakRef(_this), listener, theMap); var tapGestureRecognizer = UITapGestureRecognizer.alloc().initWithTargetAction(theMap['mapTapHandler'], "tap"); for (var i = 0; i < theMap.gestureRecognizers.count; i++) { var recognizer = theMap.gestureRecognizers.objectAtIndex(i); if (recognizer instanceof UITapGestureRecognizer) { tapGestureRecognizer.requireGestureRecognizerToFail(recognizer); } } theMap.addGestureRecognizer(tapGestureRecognizer); resolve(); } catch (ex) { reject(ex); } }); }; Mapbox.prototype.setOnMapLongClickListener = function (listener, nativeMap) { var _this = this; return new Promise(function (resolve, reject) { try { var theMap = nativeMap || _this._mapboxViewInstance; if (!theMap) { reject("No map has been loaded"); return; } theMap['mapLongPressHandler'] = MapLongPressHandlerImpl.initWithOwnerAndListenerForMap(new WeakRef(_this), listener, theMap); var longPressGestureRecognizer = UILongPressGestureRecognizer.alloc().initWithTargetAction(theMap['mapLongPressHandler'], "longPress"); for (var i = 0; i < theMap.gestureRecognizers.count; i++) { var recognizer = theMap.gestureRecognizers.objectAtIndex(i); if (recognizer instanceof UILongPressGestureRecognizer) { longPressGestureRecognizer.requireGestureRecognizerToFail(recognizer); } } theMap.addGestureRecognizer(longPressGestureRecognizer); resolve(); } catch (ex) { reject(ex); } }); }; Mapbox.prototype.setOnScrollListener = function (listener, nativeMap) { var _this = this; return new Promise(function (resolve, reject) { try { var theMap = nativeMap || _this._mapboxViewInstance; if (!theMap) { reject("No map has been loaded"); return; } theMap['mapPanHandler'] = MapPanHandlerImpl.initWithOwnerAndListenerForMap(new WeakRef(_this), listener, theMap); for (var i = 0; i < theMap.gestureRecognizers.count; i++) { var recognizer = theMap.gestureRecognizers.objectAtIndex(i); if (recognizer instanceof UIPanGestureRecognizer) { recognizer.addTargetAction(theMap['mapPanHandler'], "pan"); break; } } resolve(); } catch (ex) { reject(ex); } }); }; Mapbox.prototype.setOnMoveBeginListener = function (listener, nativeMap) { var _this = this; return new Promise(function (resolve, reject) { try { var theMap = nativeMap || _this._mapboxViewInstance; if (!theMap) { reject("No map has been loaded"); return; } theMap['mapOnMoveBeginHandler'] = MapPanHandlerImpl.initWithOwnerAndListenerForMap(new WeakRef(_this), listener, theMap); theMap['mapOnMoveBeginHandler'].setOnMoveBegin(); for (var i = 0; i < theMap.gestureRecognizers.count; i++) { var recognizer = theMap.gestureRecognizers.objectAtIndex(i); if (recognizer instanceof UIPanGestureRecognizer) { recognizer.addTargetAction(theMap['mapOnMoveBeginHandler'], "pan"); break; } } resolve(); } catch (ex) { reject(ex); } }); }; Mapbox.prototype.setOnFlingListener = function (listener, nativeMap) { return Promise.reject("'setOnFlingListener' is not supported on iOS"); }; Mapbox.prototype.setOnCameraMoveListener = function (listener, nativeMap) { return Promise.reject("'setOnCameraMoveListener' not currently supported on iOS"); }; Mapbox.prototype.setOnCameraMoveCancelListener = function (listener, nativeMap) { return Promise.reject("'setOnCameraMoveCancelListener' not currently supported on iOS"); }; Mapbox.prototype.setOnCameraIdleListener = function (listener, nativeMap) { return Promise.reject("'setOnCameraIdleListener' not currently supported on iOS"); }; Mapbox.prototype.getViewport = function (nativeMap) { var _this = this; return new Promise(function (resolve, reject) { try { var theMap = nativeMap || _this._mapboxViewInstance; if (!theMap) { reject("No map has been loaded"); return; } var visibleBounds = theMap.visibleCoordinateBounds; var bounds = { north: visibleBounds.ne.latitude, east: visibleBounds.ne.longitude, south: visibleBounds.sw.latitude, west: visibleBounds.sw.longitude }; resolve({ bounds: bounds, zoomLevel: theMap.zoomLevel }); } catch (ex) { reject(ex); } }); }; Mapbox.prototype.setViewport = function (options, nativeMap) { var _this = this; return new Promise(function (resolve, reject) { try { var theMap = nativeMap || _this._mapboxViewInstance; if (!theMap) { reject("No map has been loaded"); return; } var bounds = { sw: CLLocationCoordinate2DMake(options.bounds.south, options.bounds.west), ne: CLLocationCoordinate2DMake(options.bounds.north, options.bounds.east) }; var animated = options.animated === undefined || options.animated; var padding = Mapbox.merge(options.padding === undefined ? {} : options.padding, { top: 25, left: 25, bottom: 25, right: 25 }); theMap.setVisibleCoordinateBoundsEdgePaddingAnimated(bounds, padding, animated); resolve(); } catch (ex) { reject(ex); } }); }; Mapbox.prototype.downloadOfflineRegion = function (options) { return new Promise(function (resolve, reject) { try { var styleURL = _getMapStyle(options.style); var swCoordinate = CLLocationCoordinate2DMake(options.bounds.south, options.bounds.west); var neCoordinate = CLLocationCoordinate2DMake(options.bounds.north, options.bounds.east); var bounds = { sw: swCoordinate, ne: neCoordinate }; var region = MGLTilePyramidOfflineRegion.alloc().initWithStyleURLBoundsFromZoomLevelToZoomLevel(styleURL, bounds, options.minZoom, options.maxZoom); if (options.accessToken) { MGLAccountManager.accessToken = options.accessToken; } if (options.onProgress) { _addObserver(MGLOfflinePackProgressChangedNotification, function (notification) { var offlinePack = notification.object; var offlinePackProgress = offlinePack.progress; var userInfo = NSKeyedUnarchiver.unarchiveObjectWithData(offlinePack.context); var complete = offlinePackProgress.countOfResourcesCompleted === offlinePackProgress.countOfResourcesExpected; options.onProgress({ name: userInfo.objectForKey("name"), completed: offlinePackProgress.countOfResourcesCompleted, expected: offlinePackProgress.countOfResourcesExpected, percentage: Math.round((offlinePackProgress.countOfResourcesCompleted / offlinePackProgress.countOfResourcesExpected) * 10000) / 100, complete: complete }); if (complete) { resolve(); } }); } _addObserver(MGLOfflinePackErrorNotification, function (notification) { var offlinePack = notification.object; var userInfo = NSKeyedUnarchiver.unarchiveObjectWithData(offlinePack.context); var error = notification.userInfo[MGLOfflinePackUserInfoKeyError]; reject({ name: userInfo.objectForKey("name"), error: "Download error. " + error }); }); _addObserver(MGLOfflinePackMaximumMapboxTilesReachedNotification, function (notification) { var offlinePack = notification.object; var userInfo = NSKeyedUnarchiver.unarchiveObjectWithData(offlinePack.context); var maximumCount = notification.userInfo[MGLOfflinePackUserInfoKeyMaximumCount]; (("Offline region '" + userInfo.objectForKey("name") + "' reached the tile limit of " + maximumCount) && 0); }); var userInfo = { "name": options.name }; var context = NSKeyedArchiver.archivedDataWithRootObject(userInfo); MGLOfflineStorage.sharedOfflineStorage.addPackForRegionWithContextCompletionHandler(region, context, function (pack, error) { if (error) { reject(error.localizedFailureReason); } else { pack.resume(); } }); } catch (ex) { reject(ex); } }); }; Mapbox.prototype.listOfflineRegions = function (options) { return new Promise(function (resolve, reject) { try { var packs = MGLOfflineStorage.sharedOfflineStorage.packs; if (!packs) { reject("No packs found or Mapbox not ready yet"); return; } var regions = []; for (var i = 0; i < packs.count; i++) { var pack = packs.objectAtIndex(i); var region = pack.region; var userInfo = NSKeyedUnarchiver.unarchiveObjectWithData(pack.context); regions.push({ name: userInfo.objectForKey("name"), style: "" + region.styleURL, minZoom: region.minimumZoomLevel, maxZoom: region.maximumZoomLevel, bounds: { north: re