Beispiel #1
0
        /// <summary>
        /// NOTE: Need to invoke in main thread on iOS
        /// https://www.mapbox.com/help/mobile-offline/#requirements
        /// </summary>
        /// <param name="name">Name.</param>
        /// <param name="minimumZoomLevel">Minimum zoom level.</param>
        /// <param name="maximumZoomLevel">Maximum zoom level.</param>
        /// <param name="bounds">Bounds - the geographic bounding box.</param>
        public void dowloadMap(string name, double minimumZoomLevel, double maximumZoomLevel, Bounds bounds)
        {
            Device.BeginInvokeOnMainThread(async() => {
                var packs = await offlineService.GetPacks();
                if (packs != null && packs.Any(p => p.Info.ContainsValue(name)))
                {
                    Debug.WriteLine("A pack with the same name/key already exist");
                    return;
                }

                var region = new OfflinePackRegion {
                    StyleURL         = mapStyle,
                    MinimumZoomLevel = minimumZoomLevel,
                    MaximumZoomLevel = maximumZoomLevel,
                    Bounds           = bounds
                };

                var pack = await offlineService.DownloadMap(region, new System.Collections.Generic.Dictionary <string, string> {
                    { packNameKey, name },
                    { packCreatedAtKey, DateTime.Now.ToString("HH:mm:ss dd/MM/yyyy") }
                });

                if (pack != null)
                {
                    offlineService.RequestPackProgress(pack);
                }
                else
                {
                    // Download failed
                }
            });
        }
Beispiel #2
0
        async void TapGestureRecognizer_Tapped(object sender, EventArgs e)
        {
            var bounds = new LatLngBounds(
                new LatLng(37.7897, -119.5073),
                new LatLng(37.6744, -119.6815)
                );

            var offlineResion = new OfflinePackRegion
            {
                Bounds           = bounds,
                MinimumZoomLevel = 10,
                MaximumZoomLevel = 20,
                StyleURL         = map.MapStyle.UrlString
            };

            offlineService.OfflinePackProgressChanged += OfflineService_OfflinePackProgressChanged;
            var offlinePack = await offlineService.DownloadMap(offlineResion, new Dictionary <string, string> {
                { "regionName", "SImple Offline Region" }
            });

            if (offlinePack != null)
            {
                offlineService.RequestPackProgress(offlinePack);
            }
        }
        public Task <OfflinePack> DownloadMap(OfflinePackRegion region, Dictionary <string, string> packInfo)
        {
            var tcs          = new TaskCompletionSource <OfflinePack>();
            var latLngBounds = new LatLngBounds.Builder()
                               .Include(region.Bounds.NorthEast.ToLatLng())                          // Northeast
                               .Include(region.Bounds.SouthWest.ToLatLng())                          // Southwest
                               .Build();
            var definition = new OfflineTilePyramidRegionDefinition(
                region.StyleURL,
                latLngBounds,
                region.MinimumZoomLevel,
                region.MaximumZoomLevel,
                Android.App.Application.Context.Resources.DisplayMetrics.Density);

            byte[] metadata = null;
            if (packInfo != null)
            {
                //var binFormatter = new BinaryFormatter();
                //var mStream = new MemoryStream();
                //binFormatter.Serialize(mStream, packInfo);
                //metadata = mStream.ToArray();
                try
                {
                    var jsonObject = new JsonObject();

                    foreach (KeyValuePair <string, string> pair in packInfo)
                    {
                        jsonObject.AddProperty(pair.Key, pair.Value);
                    }
                    var json = new Java.Lang.String(jsonObject.ToString());
                    metadata = json.GetBytes(JSON_CHARSET);
                    System.Diagnostics.Debug.WriteLine("Encoding metadata succeeded: " + metadata.Length.ToString());
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Failed to encode metadata: " + ex.Message);
                }
            }

            offlineManager.CreateOfflineRegion(
                definition,
                metadata,
                new CreateOfflineRegionCallback(
                    (reg) =>
            {
                reg.SetDownloadState(OfflineRegion.StateActive);
                tcs.TrySetResult(reg.ToFormsPack());
            },
                    (msg) =>
            {
                System.Diagnostics.Debug.WriteLine("[ERROR] Couldn't create offline pack: " + msg);
                tcs.TrySetResult(null);
            }
                    )
                );

            return(tcs.Task);
        }
Beispiel #4
0
        public MainPageViewModel()
        {
            DidFinishRenderingCommand = new Command((obj) =>
            {
                if (_IsScaleBarShown == false && CenterLocation != null)
                {
                    _IsScaleBarShown = ToggleScaleBarFunc?.Invoke(true) ?? false;
                    System.Diagnostics.Debug.WriteLine("Did toggle scale bar");
                    //UpdateViewPortAction?.Invoke(new Position(CenterLocation.Lat + 0.001, CenterLocation.Long + 0.001), 16, null, false, () => {
                    //	System.Diagnostics.Debug.WriteLine("Did update center location");
                    //});
                }
                if (forcedRegion != null)
                {
                    UpdateViewPortAction?.Invoke(
                        new Position()
                    {
                        Lat  = forcedRegion.Bounds.SouthWest.Lat / 2 + forcedRegion.Bounds.NorthEast.Lat / 2,
                        Long = forcedRegion.Bounds.SouthWest.Long / 2 + forcedRegion.Bounds.NorthEast.Long / 2
                    },
                        forcedRegion.MaximumZoomLevel / 2 + forcedRegion.MinimumZoomLevel / 2,
                        null,
                        true,
                        null
                        );
                    forcedRegion = null;
                }
            }, (arg) => true);


            offlineService = DependencyService.Get <IOfflineStorageService>();
            offlineService.OfflinePackProgressChanged += (sender, e) =>
            {
                var   progress   = e.OfflinePack.Progress;
                float percentage = 0;
                if (progress.CountOfResourcesExpected > 0)
                {
                    percentage = (float)progress.CountOfResourcesCompleted / progress.CountOfResourcesExpected;
                }
                System.Diagnostics.Debug.WriteLine($"Downloaded resources: {progress.CountOfResourcesCompleted} ({percentage * 100} %)");
                System.Diagnostics.Debug.WriteLine($"Downloaded tiles: {progress.CountOfTilesCompleted}");
                if (progress.CountOfResourcesExpected == progress.CountOfResourcesCompleted)
                {
                    System.Diagnostics.Debug.WriteLine("Download completed");
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        UserDialogs.Instance.HideLoading();
                    });
                }
            };
        }
Beispiel #5
0
        public static OfflinePackRegion ToFormsRegion(this MGLTilePyramidOfflineRegion region)
        {
            if (region == null)
            {
                return(null);
            }
            var output = new OfflinePackRegion();

            output.Bounds           = new Bounds(region.Bounds.sw.toFormsPosition(), region.Bounds.ne.toFormsPosition());
            output.MaximumZoomLevel = region.MaximumZoomLevel;
            output.MinimumZoomLevel = region.MinimumZoomLevel;
            output.StyleURL         = region.StyleURL?.AbsoluteString;
            return(output);
        }
        public static OfflinePackRegion ToFormsRegion(this MGLTilePyramidOfflineRegion region)
        {
            if (region == null)
            {
                return(null);
            }
            var output = new OfflinePackRegion
            {
                Bounds           = region.Bounds.ToLatLngBounds(),
                MaximumZoomLevel = region.MaximumZoomLevel,
                MinimumZoomLevel = region.MinimumZoomLevel,
                StyleURL         = region.StyleURL?.AbsoluteString
            };

            return(output);
        }
        public Task <OfflinePack> DownloadMap(OfflinePackRegion formsRegion, Dictionary <string, string> packInfo, IOfflineStorageDelegate downloadDelegate = null)
        {
            this.downloadDelegate = downloadDelegate;
            var tsc    = new TaskCompletionSource <OfflinePack>();
            var region = new MGLTilePyramidOfflineRegion(
                new NSUrl(formsRegion.StyleURL),
                new MGLCoordinateBounds()
            {
                sw = TypeConverter.FromPositionToCoordinate(formsRegion.Bounds.SouthWest),
                ne = TypeConverter.FromPositionToCoordinate(formsRegion.Bounds.NorthEast)
            },
                formsRegion.MinimumZoomLevel,
                formsRegion.MaximumZoomLevel);
            NSData context = null;

            if (packInfo != null)
            {
                var keys   = new List <NSString>();
                var values = new List <NSString>();
                foreach (string key in packInfo.Keys)
                {
                    keys.Add((NSString)key);
                    values.Add((NSString)packInfo[key]);
                }
                var userInfo = NSDictionary.FromObjectsAndKeys(keys.ToArray(), values.ToArray());
                context = NSKeyedArchiver.ArchivedDataWithRootObject(userInfo);
            }

            MGLOfflineStorage.SharedOfflineStorage().AddPackForRegion(region, context, (pack, error) =>
            {
                if (error != null)
                {
                    System.Diagnostics.Debug.WriteLine("Couldn't create offline pack: " + error.LocalizedFailureReason);
                    tsc.TrySetResult(null);
                }
                else
                {
                    pack.Resume();
                    var formsPack = pack.ToFormsPack();
                    tempPacks.Add(pack.GetNativeHash(), formsPack);
                    tsc.TrySetResult(formsPack);
                }
            });

            return(tsc.Task);
        }
        public static OfflinePackRegion ToFormsRegion(this IMGLOfflineRegion region)
        {
            if (region == null)
            {
                return(null);
            }
            var output = new OfflinePackRegion();

            if (region is MGLTilePyramidOfflineRegion tpoRegion)
            {
                output.Bounds           = tpoRegion.Bounds.ToLatLngBounds();
                output.MaximumZoomLevel = tpoRegion.MaximumZoomLevel;
                output.MinimumZoomLevel = tpoRegion.MinimumZoomLevel;
                output.StyleURL         = tpoRegion.StyleURL?.AbsoluteString;
            }
            return(output);
        }
        public static OfflinePackRegion ToFormsRegion(this MGLTilePyramidOfflineRegion region)
        {
            if (region == null)
            {
                return(null);
            }
            var output = new OfflinePackRegion();

            output.Bounds = new CoordinateBounds()
            {
                SouthWest = TypeConverter.FromCoordinateToPosition(region.Bounds.sw),
                NorthEast = TypeConverter.FromCoordinateToPosition(region.Bounds.ne),
            };
            output.MaximumZoomLevel = region.MaximumZoomLevel;
            output.MinimumZoomLevel = region.MinimumZoomLevel;
            output.StyleURL         = region.StyleURL?.AbsoluteString;
            return(output);
        }