Beispiel #1
0
 protected void SetTileSource(ITileSource source)
 {
     tileSource               = source;
     tileFetcher              = new TileFetcher(source, memoryCache, maxRetries);
     tileFetcher.DataChanged += TileFetcherDataChanged;
     OnPropertyChanged("Envelope");
 }
Beispiel #2
0
        private void InitializeLayer()
        {
            var mxdoc = (IMxDocument)_application.Document;

            _map         = mxdoc.FocusMap;
            _cacheDir    = CacheSettings.GetCacheFolder();
            _tileTimeOut = ConfigurationHelper.GetTileTimeOut();

            var spatialReferences = new SpatialReferences();

            _tileSource           = _config.CreateTileSource();
            _schema               = _tileSource.Schema;
            _dataSpatialReference = spatialReferences.GetSpatialReference(_schema.Srs);
            _envelope             = GetDefaultEnvelope();

            if (_map.SpatialReference == null)
            {
                // zet dan de spatial ref...
                _map.SpatialReference = _dataSpatialReference;
            }

            // If there is only one layer in the TOC zoom to this layer...
            if (_map.LayerCount == 0)
            {
                //envelope.Expand(-0.1, -0.1, true);
                _envelope.Project(_map.SpatialReference);
                ((IActiveView)_map).Extent = _envelope;
            }

            _displayFilter = new TransparencyDisplayFilterClass();
        }
 /// <summary>
 /// New instance of Google Maps Disclaimer
 /// </summary>
 public GoogleMapsDisclaimer()
 {
     m_MathTransform = null; //Assuming WGS84
     m_Font = new Font("Arial", (float)Math.Floor((11.0 * 72 / 96)));
     m_Language = System.Threading.Thread.CurrentThread.CurrentCulture.Name;
     m_TileSource = new BruTile.Web.GoogleTileSource(BruTile.Web.GoogleMapType.GoogleMap);
 }
Beispiel #4
0
        public static TileInfos GetTiles(IActiveView activeView, ITileSource tileSource)
        {
            var schema = tileSource.Schema;
            var env    = Projector.ProjectEnvelope(activeView.Extent, schema.Srs);

            if (!env.IsEmpty)
            {
                Logger.Debug("Tilesource schema srs: " + schema.Srs);
                Logger.Debug("Projected envelope: xmin:" + env.XMin +
                             ", ymin:" + env.YMin +
                             ", xmax:" + env.YMax +
                             ", ymax:" + env.YMax
                             );

                var mapWidth   = activeView.ExportFrame.right;
                var mapHeight  = activeView.ExportFrame.bottom;
                var resolution = env.GetMapResolution(mapWidth);
                Logger.Debug("Map resolution: " + resolution);

                var centerPoint = env.GetCenterPoint();

                var transform = new Transform(centerPoint, resolution, mapWidth, mapHeight);
                var level     = Utilities.GetNearestLevel(schema.Resolutions, transform.Resolution);
                Logger.Debug("Current level: " + level);

                var tiles = schema.GetTilesInView(transform.Extent, level);

                var ti = new TileInfos {
                    Level = level, Tiles = tiles.ToList()
                };
                return(ti);
            }
            return(new TileInfos());
        }
Beispiel #5
0
        private static bool IsMatch(ITileSource wmtsTileSource, string capabilityIdentifier, string preferredFormat)
        {
            var schema = (WmtsTileSchema)wmtsTileSource.Schema;

            return(schema.Identifier.Equals(capabilityIdentifier) &&
                   schema.Format.Equals(preferredFormat));
        }
 public SimpleFileFetcher(ITileSource tileSource, FileCache filecache)
 {
     if (tileSource == null) throw new ArgumentNullException("tileSource");
     if (filecache == null) throw new ArgumentNullException("filecache");
     _tileSource = tileSource;
     _fileCache = filecache;
 }
Beispiel #7
0
        private static bool EqualTileSources(ITileSource ts1, ITileSource ts2, out string message)
        {
            if (!ReferenceEquals(ts1, ts2))
            {
                if (ts1 == null)
                {
                    message = "The reference tile source is null!";
                    return(false);
                }
                if (ts2 == null)
                {
                    message = "One of the tile sources is null, and the other not";
                    return(false);
                }

                if (!EqualTileSchemas(ts1.Schema, ts2.Schema, out message))
                {
                    return(false);
                }

                if (!EqualTileProviders(ts1.Schema, (ITileProvider)ts1, (ITileProvider)ts2, out message))
                {
                    return(false);
                }
            }

            message = "Tile sources seem to be equal";
            return(true);
        }
Beispiel #8
0
 /// <summary>
 /// New instance of Google Maps Disclaimer
 /// </summary>
 public GoogleMapsDisclaimer()
 {
     _mathTransform = null; //Assuming WGS84
     _font          = new Font("Arial", (float)Math.Floor((11.0 * 72 / 96)));
     //_language = Thread.CurrentThread.CurrentCulture.Name;
     _tileSource = new BruTile.Web.GoogleTileSource(BruTile.Web.GoogleMapType.GoogleMap);
 }
Beispiel #9
0
 /// <summary>
 /// New instance of Google Maps Disclaimer
 /// </summary>
 public GoogleMapsDisclaimer()
 {
     m_MathTransform = null; //Assuming WGS84
     m_Font          = new Font("Arial", (float)Math.Floor((11.0 * 72 / 96)));
     m_Language      = System.Threading.Thread.CurrentThread.CurrentCulture.Name;
     m_TileSource    = new BruTile.Web.GoogleTileSource(BruTile.Web.GoogleMapType.GoogleMap);
 }
Beispiel #10
0
        // used by WMTS
        public BruTileLayer(IApplication application, ITileSource tileSource)
        {
            LayerWeight       = 110;
            Cached            = true;
            _enumBruTileLayer = EnumBruTileLayer.WMTS;
            _application      = application;

            var mxdoc = (IMxDocument)_application.Document;

            _map         = mxdoc.FocusMap;
            _cacheDir    = CacheSettings.GetCacheFolder();
            _tileTimeOut = ConfigurationHelper.GetTileTimeOut();

            var spatialReferences = new SpatialReferences();

            _tileSource           = tileSource;
            _schema               = _tileSource.Schema;
            _dataSpatialReference = spatialReferences.GetSpatialReference(_schema.Srs);
            _envelope             = GetDefaultEnvelope();

            if (_map.SpatialReference == null)
            {
                // zet dan de spatial ref...
                _map.SpatialReference = _dataSpatialReference;
            }

            // If there is only one layer in the TOC zoom to this layer...
            if (_map.LayerCount == 0)
            {
                _envelope.Project(_map.SpatialReference);
                ((IActiveView)_map).Extent = _envelope;
            }

            _displayFilter = new TransparencyDisplayFilterClass();
        }
Beispiel #11
0
        public FileFetcher(ITileSource tileSource, FileCache filecache)
        {
            _tileSource = tileSource;
            _fileCache  = filecache;

            StartFetchLoop();
        }
Beispiel #12
0
        public MapControl()
        {
            _canvas = new Canvas
            {
                VerticalAlignment = VerticalAlignment.Stretch,
                HorizontalAlignment = HorizontalAlignment.Stretch,
                Background = new SolidColorBrush(Colors.Transparent),
            };

            Children.Add(_canvas);
            _renderer = new Renderer(_canvas);

            _tileSource = TileSource.Create(KnownTileServers.Mapnik); 
            CompositionTarget.Rendering += CompositionTargetRendering;
            SizeChanged += MapControlSizeChanged;
            MouseWheel += MapControlMouseWheel;
            MouseMove += MapControlMouseMove;
            MouseUp += OnMouseUp;
            MouseLeave += OnMouseLeave;

            ClipToBounds = true;
            _fetcher = new Fetcher<Image>(_tileSource, _tileCache);
            _fetcher.DataChanged += FetcherOnDataChanged;
            _invalid = true;
        }
Beispiel #13
0
        public static void MethodOnThread(IAsyncResult ar)
        {
            CreateTileSourceCompleted callback = null;
            Exception   error      = null;
            ITileSource tileSource = null;

            try
            {
                var args = (object[])ar.AsyncState;
                callback = (CreateTileSourceCompleted)args[0];
                var request     = (HttpWebRequest)args[1];
                var overrideUrl = (string)args[2];

                var response = request.EndGetResponse(ar);
                tileSource = CreateTileSource(response.GetResponseStream(), overrideUrl);
            }
            catch (Exception ex)
            {
                error = ex;
            }
            if (callback != null)
            {
                callback(tileSource, error);
            }
        }
Beispiel #14
0
        private void button1_Click(object sender, EventArgs e)
        {
            extent.Add(double.Parse(textBox3.Text));
            extent.Add(double.Parse(textBox4.Text));
            extent.Add(double.Parse(textBox5.Text));
            extent.Add(double.Parse(textBox2.Text));

            var tile = comboBox1.SelectedItem;

            if (tile == null)
            {
                MessageBox.Show("请选择至少一种地图");
                return;
            }
            EnumBruTileLayer enumBruTileLayer = (EnumBruTileLayer)Enum.Parse(typeof(EnumBruTileLayer), tile.ToString());
            IConfig          config           = ConfigHelper.GetConfig(enumBruTileLayer);
            string           cacheDir         = CacheSettings.GetCacheFolder();

            tileSource   = config.CreateTileSource();
            schema       = tileSource.Schema;
            tileProvider = (WebTileProvider)tileSource.Provider;
            fileCache    = CacheDirectory.GetFileCache(cacheDir, config, enumBruTileLayer);

            _tiles = GetTile();


            if (_tiles.ToList().Count > 0)
            {
                DownloadTiles();
            }
        }
Beispiel #15
0
        public static async Task DrawLayerAsync(
            ITileSource source,
            int width,
            int height,
            Models.Bounds boundingBox,
            SKCanvas outputCanvas,
            bool isTransparent,
            uint backgroundColor)
        {
            // TODO: check SRS support in source
            if ((String.Compare(source.Configuration.Type, SourceConfiguration.TypeWms, StringComparison.OrdinalIgnoreCase) == 0) &&
                (source.Configuration.Cache == null))
            {
                // Cascading GetMap request to WMS source as single GetMap request
                var imageData = await((TileSources.HttpTileSource)source).GetWmsMapAsync(width, height, boundingBox, isTransparent, backgroundColor);
                if (imageData != null)
                {
                    WmsHelper.DrawImageUnscaledToRasterCanvas(outputCanvas, imageData);
                }
            }
            else
            {
                var tileCoordinates = WmsHelper.BuildTileCoordinatesList(boundingBox, width);
                var sourceTiles     = await GetSourceTilesAsync(source, tileCoordinates);

                if (sourceTiles.Count > 0)
                {
                    WmsHelper.DrawWebMercatorTilesToRasterCanvas(outputCanvas, width, height, boundingBox, sourceTiles, backgroundColor, U.WebMercator.TileSize);
                }
            }
        }
Beispiel #16
0
        private void LoadMap()
        {
            Map map = new Map();

            ITileSource    tileSource = KnownTileSources.Create(KnownTileSource.OpenStreetMap);
            TileAsyncLayer tileLayer  = new TileAsyncLayer(tileSource, "Basemap");

            map.BackgroundLayer.Add(tileLayer);


            VectorLayer shpLayer = new VectorLayer("Points");

            shpLayer.DataSource                      = new ShapeFile("Data/indian_points.shp", true);
            shpLayer.Style.SymbolScale               = 0.8f;
            shpLayer.CoordinateTransformation        = Wgs84toGoogleMercator; //Here it re-projects our degree decimal data to Google mercator
            shpLayer.ReverseCoordinateTransformation = GoogleMercatorToWgs84;
            shpLayer.SRID = 4326;

            map.Layers.Add(shpLayer);

            mapBox1.Map = map;

            mapBox1.Map.ZoomToExtents();

            mapBox1.Refresh();
        }
Beispiel #17
0
 public BackgroundLayer(ITileSource tileSource, string name, int order)
     : base(tileSource)
 {
     Name  = name;
     Order = order;
     CRS   = tileSource.Schema.Srs;
 }
Beispiel #18
0
 public static ILayer CreateTileLayer(ITileSource tileSource, string name = null)
 {
     return(new TileLayer(tileSource)
     {
         Name = name ?? tileSource.Name
     });
 }
Beispiel #19
0
        private ITileSource CreateTileSource(Source source)
        {
            ITileSource tileSource = null;

            if (source.Tiles == null || source.Tiles.Count == 0)
            {
                return(null);
            }

            if (source.Tiles[0].StartsWith("http"))
            {
                tileSource = new HttpTileSource(new GlobalSphericalMercator(
                                                    source.Scheme == "tms" ? YAxis.TMS : YAxis.OSM,
                                                    minZoomLevel: source.ZoomMin ?? 0,
                                                    maxZoomLevel: source.ZoomMax ?? 30
                                                    ),
                                                source.Tiles[0], //"{s}",
                                                source.Tiles,
                                                name: source.Name,
                                                attribution: new Attribution(source.Attribution)
                                                );
            }
            else if (source.Tiles[0].StartsWith("mbtiles://"))
            {
                // We should get the tile source from someone else
                tileSource = new MbTilesTileSource(new SQLiteConnectionString(source.Tiles[0].Substring(10), false),
                                                   new GlobalSphericalMercator(
                                                       source.Scheme == "tms" ? YAxis.TMS : YAxis.OSM,
                                                       minZoomLevel: source.ZoomMin ?? 0,
                                                       maxZoomLevel: source.ZoomMax ?? 14
                                                       ));
            }

            return(tileSource);
        }
Beispiel #20
0
        public MapControl()
        {
            var canvas = new Canvas
            {
                VerticalAlignment   = VerticalAlignment.Stretch,
                HorizontalAlignment = HorizontalAlignment.Stretch,
                Background          = new SolidColorBrush(Colors.Transparent),
            };

            Children.Add(canvas);
            _renderer = new Renderer(canvas);

            _tileSource = KnownTileSources.Create();
            CompositionTarget.Rendering += CompositionTargetRendering;
            SizeChanged += MapControlSizeChanged;
            MouseWheel  += MapControlMouseWheel;
            MouseMove   += MapControlMouseMove;
            MouseUp     += OnMouseUp;
            MouseLeave  += OnMouseLeave;

            ClipToBounds          = true;
            _fetcher              = new Fetcher <Image>(_tileSource, _tileCache);
            _fetcher.DataChanged += FetcherOnDataChanged;
            _invalid              = true;
        }
Beispiel #21
0
 /// <summary>
 /// Create tile layer for given tile source
 /// </summary>
 /// <param name="source">Tile source to use for this layer</param>
 /// <param name="minTiles">Minimum number of tiles to cache</param>
 /// <param name="maxTiles">Maximum number of tiles to cache</param>
 /// <param name="maxRetries">Unused</param>
 /// <param name="dataFetchStrategy">Strategy to get list of tiles for given extent</param>
 /// <param name="renderFetchStrategy"></param>
 /// <param name="minExtraTiles">Number of minimum extra tiles for memory cache</param>
 /// <param name="maxExtraTiles">Number of maximum extra tiles for memory cache</param>
 // ReSharper disable once UnusedParameter.Local // Is public and won't break this now
 public TileLayer(ITileSource source = null, int minTiles = 200, int maxTiles = 300,
                  IDataFetchStrategy dataFetchStrategy = null, IRenderFetchStrategy renderFetchStrategy = null,
                  int minExtraTiles = -1, int maxExtraTiles = -1, Func <TileInfo, Feature> fetchTileAsFeature = null)
 {
     MemoryCache = new MemoryCache <Feature>(minTiles, maxTiles);
     Style       = new VectorStyle {
         Outline = { Color = Color.FromArgb(0, 0, 0, 0) }
     };                                                                            // initialize with transparent outline
     _tileSource = source;
     if (_tileSource != null)
     {
         if (Attribution == null)
         {
             Attribution = new Hyperlink();
         }
         Attribution.Text = _tileSource.Attribution?.Text;
         Attribution.Url  = _tileSource.Attribution?.Url;
     }
     _envelope                             = _tileSource?.Schema?.Extent.ToBoundingBox();
     dataFetchStrategy                     = dataFetchStrategy ?? new DataFetchStrategy(3);
     _renderFetchStrategy                  = renderFetchStrategy ?? new RenderFetchStrategy();
     _minExtraTiles                        = minExtraTiles;
     _maxExtraTiles                        = maxExtraTiles;
     _tileFetchDispatcher                  = new TileFetchDispatcher(MemoryCache, source.Schema, fetchTileAsFeature ?? ToFeature, dataFetchStrategy);
     _tileFetchDispatcher.DataChanged     += TileFetchDispatcherOnDataChanged;
     _tileFetchDispatcher.PropertyChanged += TileFetchDispatcherOnPropertyChanged;
 }
Beispiel #22
0
        public void ProcessRequest(HttpContext context)
        {
            RuntimeManager.BindLicense(ProductCode.EngineOrDesktop);
            extent  = context.Request.QueryString["Extent"].Split(new[] { ',' }).Select(Convert.ToDouble).ToList();
            level   = double.Parse(context.Request.QueryString["level"]);
            _config = ConfigHelper.GetConfig(EnumBruTileLayer.OSM);

            _tileSource   = _config.CreateTileSource();
            _tileProvider = (WebTileProvider)_tileSource.Provider;


            _cacheDir = CacheSettings.GetCacheFolder();

            _fileCache = CacheDirectory.GetFileCache(_cacheDir, _config, EnumBruTileLayer.OSM);
            Draw();
            //using (Bitmap map = new Bitmap(@"D:\我的文件\天津师大切片解决方案\DownloadTiles\DownloadTiles\bin\Debug\p.png"))
            using (Bitmap map = mosaicImage())
            {
                using (MemoryStream mem = new MemoryStream())
                {
                    map.Save(mem, ImageFormat.Png);
                    mem.Seek(0, SeekOrigin.Begin);

                    context.Response.ContentType = "image/png";

                    mem.CopyTo(context.Response.OutputStream, 4096);
                    context.Response.Flush();
                }
            }
        }
Beispiel #23
0
        // for wmts
        private static string GetCacheDirectory(ITileSource tileSource, EnumBruTileLayer layerType, string baseCacheDir)
        {
            var    name           = (tileSource is BruTile.Web.HttpTileSource ? tileSource.Name : ((WmtsTileSchema)tileSource.Schema).Layer);
            string cacheDirectory = string.Format("{0}{1}{2}{3}{4}", baseCacheDir, Path.DirectorySeparatorChar, layerType, Path.DirectorySeparatorChar, name);

            return(cacheDirectory);
        }
Beispiel #24
0
        public static ITileSource Build(
            string urlToTileMapXml,
            bool overrideTmsUrlWithUrlToTileMapXml)
        {
            var         webRequest = (HttpWebRequest)WebRequest.Create(urlToTileMapXml);
            var         waitHandle = new AutoResetEvent(false);
            ITileSource tileSource = null;
            Exception   error      = null;

            var state = new object[]
            {
                new Action <Exception>(ex =>
                {
                    error = ex;
                    waitHandle.Set();
                }),
                new Action <ITileSource>(ts =>
                {
                    tileSource = ts;
                    waitHandle.Set();
                }),
                webRequest,
                urlToTileMapXml,
                overrideTmsUrlWithUrlToTileMapXml
            };

            webRequest.BeginGetResponse(LoadTmsLayer, state);

            waitHandle.WaitOne();
            if (error != null)
            {
                throw error;
            }
            return(tileSource);
        }
Beispiel #25
0
        /// <summary>
        /// Creates a fully initialized instance of <see cref="WellKnownTileSourceLayerConfiguration"/>.
        /// </summary>
        /// <param name="wellKnownTileSource">The tile provider to be used.</param>
        /// <returns>The new <see cref="WellKnownTileSourceLayerConfiguration"/>.</returns>
        /// <exception cref="NotSupportedException">Thrown when <paramref name="wellKnownTileSource"/>
        /// isn't a supported member.</exception>
        /// <exception cref="CannotCreateTileCacheException">Thrown when creating the file
        /// cache failed.</exception>
        public static WellKnownTileSourceLayerConfiguration CreateInitializedConfiguration(WellKnownTileSource wellKnownTileSource)
        {
            KnownTileSource knownTileSourceEquivalent = WellKnownTileSourceToKnownTileSource(wellKnownTileSource);

            ITileSource tileSource = TileSourceFactory.Instance.GetKnownTileSource(knownTileSourceEquivalent);

            return(new WellKnownTileSourceLayerConfiguration(knownTileSourceEquivalent, tileSource));
        }
Beispiel #26
0
        /// <summary>
        /// Creates a fully initialized instance of <see cref="WmtsLayerConfiguration"/>.
        /// </summary>
        /// <param name="wmtsCapabilitiesUrl">The capabilities URL of the WMTS.</param>
        /// <param name="capabilityIdentifier">The capability name to get tiles from.</param>
        /// <param name="preferredFormat">The preferred tile image format, as MIME-type.</param>
        /// <returns>The new <see cref="WmtsLayerConfiguration"/>.</returns>
        /// <exception cref="ArgumentNullException">Thrown when any input argument is <c>null</c>.</exception>
        /// <exception cref="ArgumentException">Thrown when <paramref name="preferredFormat"/>
        /// is not an image MIME-type.</exception>
        /// <exception cref="CannotFindTileSourceException">Thrown when it has become impossible
        /// to create an <see cref="ITileSource"/> based on the given information (for example:
        /// unable to connect to server).</exception>
        /// <exception cref="CannotReceiveTilesException">Thrown when the configured <see cref="ITileSource"/>
        /// does not allow for tiles to be retrieved.</exception>
        /// <exception cref="CannotCreateTileCacheException">Thrown when a critical error
        /// occurs when creating the tile cache.</exception>
        public static WmtsLayerConfiguration CreateInitializedConfiguration(string wmtsCapabilitiesUrl, string capabilityIdentifier, string preferredFormat)
        {
            ValidateConfigurationParameters(wmtsCapabilitiesUrl, capabilityIdentifier, preferredFormat);

            ITileSource tileSource = GetConfiguredTileSource(wmtsCapabilitiesUrl, capabilityIdentifier, preferredFormat);

            return(new WmtsLayerConfiguration(wmtsCapabilitiesUrl, tileSource));
        }
Beispiel #27
0
 public VectorTileLayer(ITileSource tileSource, RenderGetStrategy renderStrategy = null)
 {
     _tileSource                   = tileSource;
     _tileFetcher                  = new TileFetcher(_tileSource, _tileCache, 1, 4, _fetchStrategy);
     _tileFetcher.DataChanged     += TileFetcherOnDataChanged;
     _tileFetcher.PropertyChanged += TileFetcherOnPropertyChanged;
     _renderStrategy               = renderStrategy ?? new RenderGetStrategy();
 }
Beispiel #28
0
        /// <summary>
        /// Validates an <see cref="ITileSource"/>.
        /// </summary>
        /// <param name="tileSource">The source to be validated.</param>
        /// <returns>Returns <paramref name="tileSource"/>.</returns>
        /// <exception cref="CannotCreateTileCacheException">Thrown when <paramref name="tileSource"/>
        /// doesn't contain a <see cref="WmtsTileSchema"/>.</exception>
        private static ITileSource ValidateTileSource(ITileSource tileSource)
        {
            if (!(tileSource.Schema is WmtsTileSchema))
            {
                throw new CannotCreateTileCacheException(Resources.WmtsLayerConfiguration_ValidateTileSource_TileSource_must_have_WmtsTileSchema);
            }

            return(tileSource);
        }
Beispiel #29
0
        /// <summary>
        /// Creates a new initialized instance of <see cref="WmtsLayerConfiguration"/>.
        /// </summary>
        /// <param name="wmtsCapabilitiesUrl">The capabilities URL of the WMTS.</param>
        /// <param name="tileSource">The tile source.</param>
        /// <exception cref="CannotCreateTileCacheException">Thrown when creating the file
        /// cache failed.</exception>
        /// <exception cref="CannotReceiveTilesException">Thrown when <paramref name="tileSource"/>
        /// does not allow for tiles to be retrieved.</exception>
        /// <exception cref="CannotCreateTileCacheException">Thrown when a critical error
        /// occurs when creating the tile cache.</exception>
        private WmtsLayerConfiguration(string wmtsCapabilitiesUrl, ITileSource tileSource)
            : base(SuggestTileCachePath(ValidateTileSource(tileSource)))
        {
            capabilitiesUri      = wmtsCapabilitiesUrl;
            capabilityIdentifier = ((WmtsTileSchema)tileSource.Schema).Identifier;
            preferredFormat      = tileSource.Schema.Format;

            InitializeFromTileSource(tileSource);
        }
Beispiel #30
0
        /// <summary>
        /// Creates an instance of <see cref="WellKnownTileSourceLayerConfiguration"/>.
        /// </summary>
        /// <param name="knownTileSource">The built-in tile provider to be used.</param>
        /// <param name="persistentCacheDirectoryPath">The directory path to the persistent tile cache.</param>
        /// <exception cref="ArgumentException">Thrown when <paramref name="persistentCacheDirectoryPath"/>
        /// is an invalid folder path.</exception>
        /// <exception cref="NotSupportedException">Thrown when <paramref name="knownTileSource"/>
        /// isn't a supported member.</exception>
        /// <exception cref="CannotCreateTileCacheException">Thrown when creating the file
        /// cache failed.</exception>
        private WellKnownTileSourceLayerConfiguration(string persistentCacheDirectoryPath, KnownTileSource knownTileSource)
            : base(persistentCacheDirectoryPath)
        {
            this.knownTileSource = knownTileSource;

            ITileSource tileSource = TileSourceFactory.Instance.GetKnownTileSource(knownTileSource);

            InitializeFromTileSource(tileSource);
        }
Beispiel #31
0
        /// <summary>
        /// Creates an instance of this class
        /// </summary>
        /// <param name="tileSource">the source to get the tiles from</param>
        /// <param name="layerName">name of the layer</param>
        /// <param name="transparentColor">transparent color off</param>
        /// <param name="showErrorInTile">generate an error tile if it could not be retrieved from source</param>
        /// <param name="fileCache">If the layer should use a file-cache so store tiles, set this to a fileCacheProvider. Set to null to avoid filecache</param>
        /// <param name="imgFormat">Set the format of the tiles to be used</param>
        public TileLayer(ITileSource tileSource, string layerName, Color transparentColor, bool showErrorInTile, FileCache fileCache, ImageFormat imgFormat)
        {
            _source           = tileSource;
            LayerName         = layerName;
            _transparentColor = transparentColor;
            _showErrorInTile  = showErrorInTile;

            _fileCache   = fileCache;
            _ImageFormat = imgFormat;
        }
Beispiel #32
0
        public TileFetcher(ITileSource tileSource, MemoryCache<Feature> memoryCache, int maxRetries = 2)
        {
            if (tileSource == null) throw new ArgumentException("TileProvider can not be null");
            this.tileSource = tileSource;

            if (memoryCache == null) throw new ArgumentException("MemoryCache can not be null");
            this.memoryCache = memoryCache;

            this.maxRetries = maxRetries;
        }
Beispiel #33
0
        public static BruTileLayer GetWmtsLayer(IApplication _application, ITileSource tileSource, string LayerName)
        {
            var brutileLayer = new BruTileLayer(_application, tileSource)
            {
                Name    = LayerName,
                Visible = true
            };

            return(brutileLayer);
        }
Beispiel #34
0
        private void getSampleFileFromInternetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var path    = Path.Combine(Path.GetTempPath(), "mapbox.haiti-terrain.mbtiles");
            var req     = WebRequest.Create("http://a.tiles.mapbox.com/mapbox/download/haiti-terrain.mbtiles");
            var success = true;

            try
            {
                Enabled = false;

                var tmpFile = Path.GetTempFileName();
                using (var response = req.GetResponse())
                {
                    using (var streamWriter = new BinaryWriter(File.OpenWrite(tmpFile)))
                    {
                        using (var stream = response.GetResponseStream())
                        {
                            var buffer = new byte[4 * 8192];
                            while (true)
                            {
                                var read = stream.Read(buffer, 0, buffer.Length);
                                if (read <= 0)
                                {
                                    break;
                                }
                                streamWriter.Write(buffer, 0, read);
                            }
                        }
                    }
                }
                _source = null;
                File.Copy(tmpFile, path, true);
                File.Delete(tmpFile);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                success = false;
                //throw;
            }
            finally
            {
                if (success)
                {
                    _source = new MbTilesTileSource(path);
                    var scale = (float)(1.1 * Math.Max(_source.Schema.Extent.Width / picMap.Width, _source.Schema.Extent.Height / picMap.Height));
                    _mapTransform = new MapTransform(
                        new PointF((float)_source.Schema.Extent.CenterX, (float)_source.Schema.Extent.CenterY),
                        scale, picMap.Width, picMap.Height);

                    RenderToBuffer();
                }
                Enabled = true;
            }
        }
Beispiel #35
0
        public TileManager(string tileServerName, string tileServerUrl, WmsServerInfo wmsServerInfo)
        {
            if (tileServerName == null) throw new ArgumentNullException("tileServerName");

            _tileServerUrl = tileServerUrl;
            _tileServerName = tileServerName;
            WmsServerInfo = wmsServerInfo;
            TileCache = new FileCache(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                "TileCache", _tileServerName), "", new TimeSpan(30, 0, 0, 0));
            _tileSource = InitializeBrutileProvider();
        }
Beispiel #36
0
 public TileFetcher(ITileSource tileSource, MemoryCache<Feature> memoryCache, int maxAttempts = DefaultMaxAttempts, int maxThreads = DefaultMaxThreads, IFetchStrategy strategy = null)
 {
     if (tileSource == null) throw new ArgumentException("TileProvider can not be null");
     if (memoryCache == null) throw new ArgumentException("MemoryCache can not be null");
     
     _tileSource = tileSource;
     _memoryCache = memoryCache;
     _maxAttempts = maxAttempts;
     _maxThreads = maxThreads;
     _strategy = strategy ?? new FetchStrategy();
 }
Beispiel #37
0
 public void SetTileSource(ITileSource source)
 {
     _tileSource = source;
     _tileCache.Clear();
     _fetcher.DataChanged -= FetcherOnDataChanged;
     _fetcher.AbortFetch();
     _fetcher = new Fetcher<Image>(_tileSource, _tileCache);
     _fetcher.DataChanged += FetcherOnDataChanged;
     _fetcher.ViewChanged(_viewport.Extent, _viewport.Resolution);
     _invalid = true;
 }
Beispiel #38
0
 private void lbServices_SelectedIndexChanged(object sender, EventArgs e)
 {
     if (lbServices.SelectedItem != null)
     {
         var name = (String)lbServices.SelectedItem;
         foreach (var tileSource in _tileSources.Where(t => t.Schema.Name == name))
         {
             SelectedTileSource = tileSource;
         }
         btnOk.Enabled = true;
     }
 }
Beispiel #39
0
        /// <summary>
        /// Creates an instance of this class
        /// </summary>
        /// <param name="tileSource">the source to get the tiles from</param>
        /// <param name="layerName">name of the layer</param>
        /// <param name="transparentColor">transparent color off</param>
        /// <param name="showErrorInTile">generate an error tile if it could not be retrieved from source</param>
        /// <remarks>If <see cref="showErrorInTile"/> is set to false, tile source keeps trying to get the tile in every request</remarks>
        public TileLayer(ITileSource tileSource, string layerName, Color transparentColor, bool showErrorInTile)
        {
            _source = tileSource;
            LayerName = layerName;
            if (!transparentColor.IsEmpty)
                _imageAttributes.SetColorKey(transparentColor, transparentColor);
            _showErrorInTile = showErrorInTile;

#if !PocketPC
            _imageAttributes.SetWrapMode(WrapMode.TileFlipXY);
#endif
        }
Beispiel #40
0
 public TileLayer(ITileSource source = null, int minTiles = 200, int maxTiles = 300, int maxRetries = TileFetcher.DefaultMaxAttempts,
     int maxThreads = TileFetcher.DefaultMaxThreads, IFetchStrategy fetchStrategy = null,
     IRenderGetStrategy renderFetchStrategy = null, int minExtraTiles = -1, int maxExtraTiles = -1)
 {
     _memoryCache = new MemoryCache<Feature>(minTiles, maxTiles);
     Style = new VectorStyle { Outline = { Color = Color.FromArgb(0, 0, 0, 0) } }; // initialize with transparent outline
     _maxRetries = maxRetries;
     _maxThreads = maxThreads;
     _fetchStrategy = fetchStrategy ?? new FetchStrategy();
     _renderFetchStrategy = renderFetchStrategy ?? new RenderGetStrategy();
     _minExtraTiles = minExtraTiles;
     _maxExtraTiles = maxExtraTiles;
     SetTileSource(source);
 }
Beispiel #41
0
 /// <summary>
 /// Creates an instance of this class
 /// </summary>
 /// <param name="tileSource">The tile source to use</param>
 /// <param name="tileCache">The tile cache to use</param>
 public BruTileLayer(ITileSource tileSource, ITileCache<byte[]> tileCache)
 {
     TileSource = tileSource;
     TileCache = tileCache;
     int epsgCode;
     if (int.TryParse(TileSource.Schema.Srs.Substring(5), out epsgCode))
     {
         _projection = new ProjectionInfo();
         _projection = ProjectionInfo.FromEpsgCode(epsgCode);
     }
     else
         _projection = KnownCoordinateSystems.Projected.World.WebMercator;
     LegendItemVisible = true;
 }
Beispiel #42
0
        public void SetTileSource(ITileSource source)
        {
            _fetcher.DataChanged -= FetcherOnDataChanged;
            _fetcher.AbortFetch();

            _tileSource = source;
            _viewport.CenterX = source.Schema.Extent.CenterX;
            _viewport.CenterY = source.Schema.Extent.CenterY;
            _viewport.UnitsPerPixel = Math.Max(source.Schema.Extent.Width / ActualWidth, source.Schema.Extent.Height / ActualHeight);
            _tileCache.Clear();
            _fetcher = new Fetcher<Image>(_tileSource, _tileCache);
            _fetcher.DataChanged += FetcherOnDataChanged;
            _fetcher.ViewChanged(_viewport.Extent, _viewport.UnitsPerPixel);
            _invalid = true;
        }
Beispiel #43
0
        protected override void OnLoad(EventArgs e)
        {
            /* http://a.tiles.mapbox.com/mapbox/download/haiti-terrain-grey.mbtiles */
            var path = Path.Combine(Path.GetTempPath(), "mapbox.haiti-terrain-grey.mbtiles");
            if (File.Exists(path))
            {
                _source = new MbTilesTileSource(path);
                var scale = (float)(1.1 * Math.Max(_source.Schema.Extent.Width / picMap.Width, _source.Schema.Extent.Height / picMap.Height));
                _mapTransform = new MapTransform(
                    new PointF((float)_source.Schema.Extent.CenterX, (float)_source.Schema.Extent.CenterY),
                    scale, picMap.Width, picMap.Height);

                RenderToBuffer();
            }
            base.OnLoad(e);
        }
 public ArcGISTileCompactLayer(ITileSource tileSource, string layerName, Color transparentColor, bool showErrorInTile, FileCache fileCache, ImageFormat imgFormat)
     : base(tileSource,layerName,transparentColor,showErrorInTile,fileCache,imgFormat)
 {
     //this._imageAttributes = new ImageAttributes();
     //this._bitmaps = new MemoryCache<Bitmap>(100, 200);
     //this._showErrorInTile = true;
     //this._source = tileSource;
     //base.LayerName = layerName;
     //if (!transparentColor.IsEmpty)
     //{
     //    this._imageAttributes.SetColorKey(transparentColor, transparentColor);
     //}
     //this._showErrorInTile = showErrorInTile;
     //this._fileCache = fileCache;
     //this._ImageFormat = imgFormat;
 }
Beispiel #45
0
        private static byte[] GetTile(ITileSource tileSource, string level, int col, int row)
        {
            try
            {
                var tileInfo = new TileInfo();
                var tileIndex = new TileIndex(col, row, level);
                tileInfo.Index = tileIndex;

                return tileSource.Provider.GetTile(tileInfo);
            }
            catch (WebException)
            {
                // intented: do nothing
                return null;
            }
        }
Beispiel #46
0
        public void Render(Viewport viewport, ITileSource tileSource, ITileCache<Tile<Image>> tileCache)
        {
            _canvas.Children.Clear();

            var level = Utilities.GetNearestLevel(tileSource.Schema.Resolutions, viewport.UnitsPerPixel);
            var tileInfos = tileSource.Schema.GetTileInfos(viewport.Extent, level);
            foreach (var tileInfo in tileInfos)
            {
                var tile = tileCache.Find(tileInfo.Index);
                if (tile != null)
                {
                    _canvas.Children.Add(tile.Image);
                    PositionImage(tile.Image, tileInfo.Extent, viewport);
                }
            }
        }
Beispiel #47
0
        protected void SetTileSource(ITileSource source)
        {
            if (_tileSource != null)
            {
                _tileFetcher.AbortFetch();
                _tileFetcher.DataChanged -= TileFetcherDataChanged;
                _tileFetcher.PropertyChanged -= TileFetcherOnPropertyChanged;
                _tileFetcher = null;
                _memoryCache.Clear();
            }
            _tileSource = source;

            if (source == null) return;
            _tileFetcher = new TileFetcher(source, _memoryCache, _maxRetries, _maxThreads, _fetchStrategy);
            _tileFetcher.DataChanged += TileFetcherDataChanged;
            _tileFetcher.PropertyChanged += TileFetcherOnPropertyChanged;
            OnPropertyChanged("Envelope");
        }
 public ArcGISTileCompactLayer(ITileSource tileSource, string layerName, Color transparentColor, bool showErrorInTile, string fileCacheDir)
     : base(tileSource,layerName,transparentColor,showErrorInTile)
 {
     //this._imageAttributes = new ImageAttributes();
     //this._bitmaps = new MemoryCache<Bitmap>(100, 200);
     //this._showErrorInTile = true;
     //this._source = tileSource;
     //base.LayerName = layerName;
     //if (!transparentColor.IsEmpty)
     //{
     //    this._imageAttributes.SetColorKey(transparentColor, transparentColor);
     //}
     //this._showErrorInTile = showErrorInTile;
     //if (!string.IsNullOrEmpty(fileCacheDir))
     //{
     //    this._fileCache = new FileCache(fileCacheDir, "png");
     //    this._ImageFormat = ImageFormat.Png;
     //}
 }
        public WmtsLayerConfiguration(string fileCacheRoot, string name, ITileSource tileSource)
            :base(BruTileLayerPlugin.Settings.PermaCacheType, fileCacheRoot)
        {
            _fileCacheRoot = fileCacheRoot;

            LegendText = name;

            //var tileSources = GetTileSources(capabilitiesUri);
            //var tileSource = tileSources.FirstOrDefault(ts => ts.Title.Equals(name, StringComparison.InvariantCulture));
            if (tileSource == null)
                throw new ArgumentException("TileSource not found", "capabilitiesUri");

            TileSource = tileSource;
            TileCache = CreateTileCache();

            _tileFetcher = new TileFetcher(ReflectionHelper.Reflect(tileSource), BruTileLayerPlugin.Settings.MemoryCacheMinimum,
                                           BruTileLayerPlugin.Settings.MemoryCacheMaximum, TileCache);
            _initialized = true;
        }
Beispiel #50
0
        private static List<IFeature> TileIndexToFeatures(TileIndex[] tileIndexes, ITileSource tileSource)
        {
            var features = new List<IFeature>();
            foreach (var tileIndex in tileIndexes)
            {
                var tileInfo = new TileInfo
                {
                    Index = tileIndex,
                    Extent = TileTransform.TileToWorld(
                        new TileRange(tileIndex.Col, tileIndex.Row), tileIndex.Level, tileSource.Schema)
                };

                var feature = new Feature
                {
                    Geometry = new Raster(new MemoryStream(
                        tileSource.GetTile(tileInfo)), tileInfo.Extent.ToBoundingBox())
                };

                features.Add(feature);
            }
            return features;
        }
        public void DoMainTask(DateTime time,string _extent,string basePath,string tileDir,string csv)
        {
            this.basePath = basePath;
            this.csv = csv;

            extent = _extent.Split(new[] { ',' }).Select(Convert.ToDouble).ToList();
            _config = ConfigHelper.GetConfig(EnumBruTileLayer.OSM);
            _tileSource = _config.CreateTileSource();
            _tileProvider = (WebTileProvider)_tileSource.Provider;

            _cacheDir = CacheSettings.GetCacheFolder(tileDir);

            while (true)
            {
                try
                {
                    DeleteDirectory(_cacheDir);
                    break;
                }
                catch (Exception ex)
                {
                    LogManager.LogPath = AppDomain.CurrentDomain.BaseDirectory + "\\log\\";
                    LogManager.WriteLog("error", ex.Message);
                }
            }

            _fileCache = CacheDirectory.GetFileCache(_cacheDir, _config, EnumBruTileLayer.OSM);
            Draw();
            var map = mosaicImage();
            DirectoryInfo directory =
                new DirectoryInfo(basePath + time.ToString("yyyy") + "\\" + time.ToString("yyyyMMdd") + "\\" +
                                  time.ToString("yyyyMMddHHmm"));
            if(!directory.Exists)
                directory.Create();
            map.Save(directory.FullName + "\\traffic.png");
            CreateTrafficCsv(directory);
        }
Beispiel #52
0
 public TileProvider(ITileSource tileSource)
 {
     _source = tileSource;
 }
Beispiel #53
0
 public TileAsyncLayer(ITileSource tileSource, string layerName)
     : base(tileSource, layerName, new Color(), true, null)
 {
 }
Beispiel #54
0
        protected void SetTileSource(ITileSource source)
        {
            if (_tileSource != null)
            {
                // Is causing thread leak _tileFetcher.AbortFetch();
                _tileFetcher.DataChanged -= TileFetcherDataChanged;
                _tileFetcher.PropertyChanged -= TileFetcherOnPropertyChanged;
                _tileFetcher = null;
                _memoryCache.Clear();
            }

            _tileSource = source;

            if (_tileSource != null)
            {
                Attribution.Text = _tileSource.Attribution.Text;
                Attribution.Url = _tileSource.Attribution.Url;
                _tileFetcher = new TileFetcher(source, _memoryCache, _maxRetries, _maxThreads, _fetchStrategy);
                _tileFetcher.DataChanged += TileFetcherDataChanged;
                _tileFetcher.PropertyChanged += TileFetcherOnPropertyChanged;
                OnPropertyChanged(nameof(Envelope));
            }
        }
Beispiel #55
0
 public TileAsyncLayer(ITileSource tileSource, string layerName, Color transparentColor, bool showErrorInTile, string fileCacheDir)
     : base(tileSource, layerName, transparentColor, showErrorInTile, fileCacheDir)
 {
 }
Beispiel #56
0
 /// <summary>
 /// Creates an instance of this class
 /// </summary>
 /// <param name="tileSource">the source to get the tiles from</param>
 /// <param name="layerName">name of the layer</param>
 public TileLayer(ITileSource tileSource, string layerName)
     : this(tileSource, layerName, new Color(), true, null)
 {
 }
Beispiel #57
0
        /// <summary>
        /// Creates an instance of this class
        /// </summary>
        /// <param name="tileSource">the source to get the tiles from</param>
        /// <param name="layerName">name of the layer</param>
        /// <param name="transparentColor">transparent color off</param>
        /// <param name="showErrorInTile">generate an error tile if it could not be retrieved from source</param>
        /// <param name="fileCache">If the layer should use a file-cache so store tiles, set this to a fileCacheProvider. Set to null to avoid filecache</param>
        /// <param name="imgFormat">Set the format of the tiles to be used</param>
        public TileLayer(ITileSource tileSource, string layerName, Color transparentColor, bool showErrorInTile, FileCache fileCache, ImageFormat imgFormat)
        {
            _source = tileSource;
            LayerName = layerName;
            _transparentColor = transparentColor;
            _showErrorInTile = showErrorInTile;

            _fileCache = fileCache;
            _ImageFormat = imgFormat;
        }
Beispiel #58
0
        /// <summary>
        /// Creates an instance of this class
        /// </summary>
        /// <param name="tileSource">the source to get the tiles from</param>
        /// <param name="layerName">name of the layer</param>
        /// <param name="transparentColor">transparent color off</param>
        /// <param name="showErrorInTile">generate an error tile if it could not be retrieved from source</param>
        /// <param name="fileCacheDir">If the layer should use a file-cache so store tiles, set this to that directory. Set to null to avoid filecache</param>
        /// <remarks>If <paramref name="showErrorInTile"/> is set to false, tile source keeps trying to get the tile in every request</remarks>
        public TileLayer(ITileSource tileSource, string layerName, Color transparentColor, bool showErrorInTile, string fileCacheDir)
        {
            _source = tileSource;
            LayerName = layerName;
            _transparentColor = transparentColor;
            _showErrorInTile = showErrorInTile;

            if (!string.IsNullOrEmpty(fileCacheDir))
            {
                _fileCache = new FileCache(fileCacheDir, "png");
                _ImageFormat = ImageFormat.Png;
            }
        }
Beispiel #59
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="tileSource">The source to get the tiles from</param>
 /// <param name="layerName">The name of the layer</param>
 /// <param name="transparentColor">The color to be treated as transparent color</param>
 /// <param name="showErrorInTile">Flag indicating that an error tile should be generated for <see cref="WebException"/>s</param>
 public TileLayer(ITileSource tileSource, string layerName, Color transparentColor, bool showErrorInTile)
     : this(tileSource,layerName, transparentColor, showErrorInTile,null)
 {
 }
 public TileProvider(ITileSource tileSource, string layerName)
 {
     this.source = tileSource;
     this.layerName = layerName;
 }