public MapToolStripMenuItem(HttpTileSource tileSource, LinkLabelType linkLabelType) : base() { TileSource = tileSource; LinkLabelType = linkLabelType; Tag = linkLabelType; }
public static async Task <byte[][]> GetTilesAsync(this HttpTileSource tileSource, HttpClient httpClient, IEnumerable <TileInfo> tileInfos) { var tasks = tileInfos.Select(t => tileSource.GetTileAsync(httpClient, t)).ToArray(); var result = Task.WhenAll(tasks); return(await result); }
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); }
static void Main() { // Dear BruTile maintainer, // If the code in this file does not compile and needs changes you // also need to update the 'getting started' sample in the wiki. // 1) Create a tile source // This is an example that creates the OpenStreetMap tile source: var tileSource = new HttpTileSource(new GlobalSphericalMercator(0, 18), "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", new[] { "a", "b", "c" }, "OSM"); // 2) Calculate which tiles you need // the extent of the visible map changes but lets start with the whole world var extent = new Extent(-20037508, -20037508, 20037508, 20037508); var screenWidthInPixels = 400; // The width of the map on screen in pixels var resolution = extent.Width / screenWidthInPixels; var tileInfos = tileSource.Schema.GetTileInfos(extent, resolution); // 3) Fetch the tiles from the service Console.WriteLine("Show tile info"); foreach (var tileInfo in tileInfos) { var tile = tileSource.GetTile(tileInfo); Console.WriteLine( $"tile col: {tileInfo.Index.Col}, " + $"tile row: {tileInfo.Index.Row}, " + $"tile level: {tileInfo.Index.Level} , " + $"tile size {tile.Length}"); } // 4) Try some of the known tile sources // You can easily create an ITileSource for a number of predefined tile servers // with single line statements like: var tileSource1 = KnownTileSources.Create(); // The default is OpenStreetMap var tileSource2 = KnownTileSources.Create(KnownTileSource.BingAerial); var tileSource3 = KnownTileSources.Create(KnownTileSource.BingHybrid); var tileSource4 = KnownTileSources.Create(KnownTileSource.StamenTonerLite); var tileSource5 = KnownTileSources.Create(KnownTileSource.EsriWorldShadedRelief); // 6) Use MBTiles, the sqlite format for tile data, to work with tiles stored on your device. var mbtilesTilesource = new MbTilesTileSource(new SQLiteConnectionString("Resources/world.mbtiles", false)); var mbTilesTile = mbtilesTilesource.GetTile(new TileInfo { Index = new TileIndex(0, 0, 0) }); Console.WriteLine(); Console.WriteLine("MBTiles"); Console.WriteLine($"This is a byte array of an image file loaded from MBTiles with size: {mbTilesTile.Length}"); }
private void OnLayerSegmentSelected(object sender, SegmentSelectEventArgs e) { foreach (var layer in layers) { layer.Enabled = false; } layers[e.NewValue].Enabled = true; selectedSource = sources[e.NewValue]; mapView.Refresh(); }
public static ITileSource GetOSMBasemap(string cacheFilename) { if (mbTileCache == null) { mbTileCache = new MbTileCache(cacheFilename, "png"); } HttpTileSource src = new HttpTileSource(new GlobalSphericalMercator(), "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", new[] { "a", "b", "c" }, name: "OpenStreetMap", persistentCache: mbTileCache, userAgent: "OpenStreetMap in Mapsui (hajk)", attribution: new Attribution("(c) OpenStreetMap contributors", "https://www.openstreetmap.org/copyright")); return(src); }
public static async Task <byte[]> GetTileAsync(this HttpTileSource tileSource, HttpClient httpClient, TileInfo tileInfo) { var bytes = tileSource.PersistentCache.Find(tileInfo.Index); if (bytes != null) { return(bytes); } bytes = await httpClient.GetByteArrayAsync(tileSource.GetUri(tileInfo)).ConfigureAwait(false); if (bytes != null) { tileSource.PersistentCache.Add(tileInfo.Index, bytes); } return(bytes); }
private void OsmClick(object sender, RoutedEventArgs e) { MapControl.Map.Layers.Clear(); var tileSource = new HttpTileSource(new GlobalSphericalMercator(0, 20), "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", new[] { "a", "b", "c" }, name: "OSM"); var tileLayer = new TileLayer(tileSource) { Name = "OSM" }; MapControl.Map.Layers.Add(tileLayer); LayerList.Initialize(MapControl.Map.Layers); MapControl.ZoomToFullEnvelope(); MapControl.Refresh(); }
private void AddSources() { var norgeskart = KartverketSources.Create( KartverketTileSource.NorgeskartBakgrunn, FetchFactory.CreateRetryFetcher(httpClient)); norgeskart.PersistentCache = new ReadOnlyFileCache(GetCacheFolder(norgeskart.Name), "png"); var norgeskartLayer = new TileLayer(norgeskart) { Name = norgeskart.Name, Enabled = true }; mapView.Map.Layers.Add(norgeskartLayer); var sjøkart = KartverketSources.Create( KartverketTileSource.SjøkartRaster, FetchFactory.CreateRetryFetcher(httpClient)); sjøkart.PersistentCache = new ReadOnlyFileCache(GetCacheFolder(sjøkart.Name), "png"); var sjøkartLayer = new TileLayer(sjøkart) { Name = sjøkart.Name, Enabled = false }; mapView.Map.Layers.Add(sjøkartLayer); var osm = KnownTileSources.Create( KnownTileSource.OpenStreetMap, tileFetcher: FetchFactory.CreateRetryFetcher(httpClient)); osm.PersistentCache = new ReadOnlyFileCache(GetCacheFolder(osm.Name), "png"); var osmLayer = new TileLayer(osm) { Name = osm.Name, Enabled = false }; mapView.Map.Layers.Add(osmLayer); selectedSource = norgeskart; sources.Add(norgeskart); sources.Add(sjøkart); sources.Add(osm); layers.Add(norgeskartLayer); layers.Add(sjøkartLayer); layers.Add(osmLayer); }
static void Main(string[] args) { Mapsui.Logging.Logger.LogDelegate += (level, message, ex) => { Console.WriteLine($"[{level}]: {message}"); }; using var httpClient = new HttpClient(); var fileCache = new FileCache(Path.Combine(Path.GetTempPath(), "tilecache"), "png"); HttpTileSource tileSource = KartverketSources.Create( KartverketTileSource.SjøkartRaster, FetchFactory.CreateRetryFetcher(httpClient), fileCache); var southWest = SphericalMercator.FromLonLat(22.7962, 70.0910); var northEast = SphericalMercator.FromLonLat(22.8618, 70.1205); var extent = new Extent(southWest.X, southWest.Y, northEast.X, northEast.Y); Console.WriteLine($"Getting tiles for extent {extent}"); var fetchStrategy = new DataFetchStrategy(); var tileInfos = fetchStrategy.Get(tileSource.Schema, extent, 15); //var tileInfos = tileSource.Schema.GetTileInfos(extent, 7); Console.WriteLine($"Show tile info ({tileInfos.Count} tiles)"); int tileCounter = 0; foreach (var tileInfo in tileInfos) { tileCounter++; double progress = Math.Round(tileCounter / (float)tileInfos.Count * 100.0f, 2); var tile = tileSource.GetTile(tileInfo); Console.WriteLine( $"{progress}% ({tileCounter}/{tileInfos.Count}) - " + $"tile col: {tileInfo.Index.Col}, " + $"tile row: {tileInfo.Index.Row}, " + $"tile level: {tileInfo.Index.Level}, " + $"tile size {tile.Length}"); } }
public void CreateInitializedConfiguration_CannotCreateCache_ThrowCannotCreateCacheException() { // Setup WmtsMapData targetMapData = WmtsMapDataTestHelper.CreateDefaultPdokMapData(); var tileSource = new HttpTileSource(TileSchemaFactory.CreateWmtsTileSchema(targetMapData), (IRequest)null); var mocks = new MockRepository(); var factory = mocks.Stub <ITileSourceFactory>(); factory.Stub(f => f.GetWmtsTileSources(targetMapData.SourceCapabilitiesUrl)) .Return(new[] { tileSource }); mocks.ReplayAll(); using (new UseCustomSettingsHelper(testSettingsHelper)) using (new UseCustomTileSourceFactoryConfig(factory)) { directoryDisposeHelper.LockDirectory(FileSystemRights.Write); // Call TestDelegate call = () => WmtsLayerConfiguration.CreateInitializedConfiguration(targetMapData.SourceCapabilitiesUrl, targetMapData.SelectedCapabilityIdentifier, targetMapData.PreferredFormat); try { // Assert string message = Assert.Throws <CannotCreateTileCacheException>(call).Message; const string expectedMessage = "Een kritieke fout is opgetreden bij het aanmaken van de cache."; Assert.AreEqual(expectedMessage, message); } finally { directoryDisposeHelper.UnlockDirectory(); } } mocks.VerifyAll(); }
public MapView() { InitializeComponent(); var map = new Mapsui.Map { CRS = "EPSG:3857", Transformation = new MinimalTransformation() }; var tileLayer = new HttpTileSource(new GlobalSphericalMercator(), "https://api.maptiler.com/maps/hybrid/{z}/{x}/{y}.jpg?key=UNzmzzs5vM5fHNT7gBDM", new[] { "a", "b", "c" }, name: "OpenStreetMap", attribution: OpenStreetMapAttribution); map.Layers.Add(new TileLayer(tileLayer)); map.Home = n => n.NavigateTo(SphericalMercator.FromLonLat(-2.32624, 51.37795), mapView.Map.Resolutions[14]); mapView.IsMyLocationButtonVisible = false; mapView.IsNorthingButtonVisible = false; mapView.Map = map; mapView.MyLocationLayer.UpdateMyLocation(new Mapsui.UI.Forms.Position(51.37795, -2.32624)); var pin = new Pin() { Position = new Position(51.38019, -2.33172), Label = "Target", } ; pin.Callout.Anchor = new Point(0, pin.Height * pin.Scale); pin.Callout.RectRadius = 5; pin.Callout.ArrowHeight = 5; pin.Callout.ArrowWidth = 5; pin.Callout.ArrowAlignment = 0; pin.Callout.ArrowPosition = 0.5; pin.Callout.StrokeWidth = 5; pin.Callout.BackgroundColor = Color.Transparent; pin.Callout.RotateWithMap = true; pin.Callout.Type = CalloutType.Detail; pin.Callout.TitleFontSize = 15; pin.Callout.TitleTextAlignment = TextAlignment.Center; pin.Callout.TitleFontColor = Color.Black; mapView.Pins.Add(pin); pin.ShowCallout(); }
/// <summary> /// Create the TileSource, that provides the data for the IDrawableTileSource /// </summary> /// <param name="source"></param> /// <returns></returns> private static ITileSource CreateTileSource(JsonSource 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 var filename = source.Tiles[0].Substring(10); filename = Path.Combine(DirectoryForFiles, filename); if (!File.Exists(filename)) { return(null); } tileSource = new MbTilesTileSource(new SQLiteConnectionString(filename, false), //new GlobalSphericalMercator( // source.Scheme == "tms" ? YAxis.TMS : YAxis.OSM, // minZoomLevel: source.ZoomMin ?? 0, // maxZoomLevel: source.ZoomMax ?? 30) null ); } return(tileSource); }
public HttpTileSourceRef(SerializationInfo info, StreamingContext context) { var name = info.GetString("name"); // Schema var type = (Type)info.GetValue("schemaType", typeof(Type)); var schema = (ITileSchema)info.GetValue("schema", type); // Attribution var attribution = new Attribution(info.GetString("attText"), info.GetString("attUrl")); // Provider var tp = (HttpTileProvider)info.GetValue("provider", typeof(HttpTileProvider)); _httpTileSource = new HttpTileSource(schema, "http://localhost", attribution: attribution) { Name = name }; object obj = _httpTileSource; Utility.SetFieldValue(ref obj, "_provider", BindingFlags.NonPublic | BindingFlags.Instance, tp); }
public void CreateInitializedConfiguration_MatchingLayerAvailable_ReturnConfiguration() { // Setup WmtsMapData targetMapData = WmtsMapDataTestHelper.CreateAlternativePdokMapData(); var tileSource1 = new HttpTileSource(TileSchemaFactory.CreateWmtsTileSchema(WmtsMapDataTestHelper.CreateDefaultPdokMapData()), (IRequest)null); var tileSource2 = new HttpTileSource(TileSchemaFactory.CreateWmtsTileSchema(targetMapData), (IRequest)null); var tileSources = new ITileSource[] { tileSource1, tileSource2 }; var mocks = new MockRepository(); var factory = mocks.Stub <ITileSourceFactory>(); factory.Stub(f => f.GetWmtsTileSources(targetMapData.SourceCapabilitiesUrl)).Return(tileSources); mocks.ReplayAll(); using (new UseCustomSettingsHelper(testSettingsHelper)) using (new UseCustomTileSourceFactoryConfig(factory)) { // Call using (WmtsLayerConfiguration configuration = WmtsLayerConfiguration.CreateInitializedConfiguration(targetMapData.SourceCapabilitiesUrl, targetMapData.SelectedCapabilityIdentifier, targetMapData.PreferredFormat)) { // Assert Assert.IsTrue(configuration.Initialized); Assert.IsTrue(configuration.TileFetcher.IsReady()); Assert.AreSame(tileSource2.Schema, configuration.TileSchema); } } mocks.VerifyAll(); }
public void Clone_FromFullyInitializedConfiguration_CreateNewUninitializedInstance() { // Setup WmtsMapData targetMapData = WmtsMapDataTestHelper.CreateAlternativePdokMapData(); var tileSource = new HttpTileSource(TileSchemaFactory.CreateWmtsTileSchema(targetMapData), (IRequest)null); var tileSources = new ITileSource[] { tileSource }; var mocks = new MockRepository(); var factory = mocks.Stub <ITileSourceFactory>(); factory.Stub(f => f.GetWmtsTileSources(targetMapData.SourceCapabilitiesUrl)).Return(tileSources); mocks.ReplayAll(); using (new UseCustomSettingsHelper(testSettingsHelper)) using (new UseCustomTileSourceFactoryConfig(factory)) using (WmtsLayerConfiguration configuration = WmtsLayerConfiguration.CreateInitializedConfiguration(targetMapData.SourceCapabilitiesUrl, targetMapData.SelectedCapabilityIdentifier, targetMapData.PreferredFormat)) { // Call IConfiguration clone = configuration.Clone(); // Assert Assert.IsInstanceOf <WmtsLayerConfiguration>(clone); Assert.AreNotSame(configuration, clone); Assert.IsFalse(clone.Initialized); Assert.IsNull(clone.TileFetcher, "TileFetcher should be null because the clone hasn't been initialized yet."); Assert.IsNull(clone.TileSchema, "TileSchema should be null because the clone hasn't been initialized yet."); } mocks.VerifyAll(); }
static void Main() { // 1) Create a tile source //This is an example of the open street map tile source: var tileSource = new HttpTileSource(new GlobalSphericalMercator(0, 18), "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", new[] { "a", "b", "c" }, "OSM"); // 2) Calculate which tiles you need // the extent of the visible map changes but lets start with the whole world var extent = new Extent(-20037508, -20037508, 20037508, 20037508); const int screenWidthInPixels = 400; // The width of the map on screen in pixels var unitsPerPixel = extent.Width / screenWidthInPixels; var tileInfos = tileSource.Schema.GetTileInfos(extent, unitsPerPixel); // 3) Fetch the tiles from the service var tiles = new Dictionary <TileInfo, byte[]>(); foreach (var tileInfo in tileInfos) { tiles[tileInfo] = tileSource.GetTile(tileInfo); } // Show that something actually happended: foreach (var tile in tiles) { System.Console.WriteLine("Column: {0}, Row: {1}, level: {2}, bytes: {3}", tile.Key.Index.Col, tile.Key.Index.Row, tile.Key.Index.Level, tile.Value.Length); } System.Console.ReadKey(); }
public void GivenFullyInitializedConfiguration_WhenClonedAndInitialized_ConfigurationAreEqual() { // Given WmtsMapData targetMapData = WmtsMapDataTestHelper.CreateAlternativePdokMapData(); var tileSource = new HttpTileSource(TileSchemaFactory.CreateWmtsTileSchema(targetMapData), (IRequest)null); var tileSources = new ITileSource[] { tileSource }; var mocks = new MockRepository(); var factory = mocks.Stub <ITileSourceFactory>(); factory.Stub(f => f.GetWmtsTileSources(targetMapData.SourceCapabilitiesUrl)).Return(tileSources); mocks.ReplayAll(); using (new UseCustomSettingsHelper(testSettingsHelper)) using (new UseCustomTileSourceFactoryConfig(factory)) using (WmtsLayerConfiguration configuration = WmtsLayerConfiguration.CreateInitializedConfiguration(targetMapData.SourceCapabilitiesUrl, targetMapData.SelectedCapabilityIdentifier, targetMapData.PreferredFormat)) { // When IConfiguration clone = configuration.Clone(); clone.Initialize(); // Assert Assert.IsTrue(clone.Initialized); Assert.IsTrue(clone.TileFetcher.IsReady()); Assert.AreSame(configuration.TileSchema, clone.TileSchema); } mocks.VerifyAll(); }
public void Initialize_ConfigurationDisposed_ThrowsObjectDisposedException() { // Setup WmtsMapData targetMapData = WmtsMapDataTestHelper.CreateAlternativePdokMapData(); var tileSource = new HttpTileSource(TileSchemaFactory.CreateWmtsTileSchema(targetMapData), (IRequest)null); var tileSources = new ITileSource[] { tileSource }; var mocks = new MockRepository(); var factory = mocks.Stub <ITileSourceFactory>(); factory.Stub(f => f.GetWmtsTileSources(targetMapData.SourceCapabilitiesUrl)).Return(tileSources); mocks.ReplayAll(); using (new UseCustomSettingsHelper(testSettingsHelper)) using (new UseCustomTileSourceFactoryConfig(factory)) { WmtsLayerConfiguration configuration = WmtsLayerConfiguration.CreateInitializedConfiguration(targetMapData.SourceCapabilitiesUrl, targetMapData.SelectedCapabilityIdentifier, targetMapData.PreferredFormat); configuration.Dispose(); // Call TestDelegate call = () => configuration.Initialize(); // Assert string objectName = Assert.Throws <ObjectDisposedException>(call).ObjectName; Assert.AreEqual("WmtsLayerConfiguration", objectName); } mocks.VerifyAll(); }
public Lobby() { hours = 0; minutes = 0; seconds = 12; InitializeComponent(); var map = new Mapsui.Map { CRS = "EPSG:3857", Transformation = new MinimalTransformation() }; var tileLayer = new HttpTileSource(new GlobalSphericalMercator(), "https://api.maptiler.com/maps/hybrid/{z}/{x}/{y}.jpg?key=UNzmzzs5vM5fHNT7gBDM", new[] { "a", "b", "c" }, name: "OpenStreetMap", attribution: OpenStreetMapAttribution); map.Layers.Add(new TileLayer(tileLayer)); map.Home = n => n.NavigateTo(SphericalMercator.FromLonLat(-2.32624, 51.37795), mapView.Map.Resolutions[14]); mapView.IsMyLocationButtonVisible = false; mapView.IsNorthingButtonVisible = false; mapView.Map = map; mapView.Drawables.Add(CreatePolygon()); Device.StartTimer(TimeSpan.FromSeconds(1), () => { if (seconds == 0 && hours == 0 && minutes == 0) { StartGame(); } if (seconds == 0) { seconds = 60; minutes -= 1; } ; if (minutes == -1) { minutes = 59; hours -= 1; } ; seconds -= 1; string labelText; labelText = hours.ToString(); labelText += ":"; if (minutes < 10) { labelText += "0" + minutes.ToString(); } else { labelText += minutes.ToString(); } labelText += ":"; if (seconds < 10) { labelText += "0" + seconds.ToString(); } else { labelText += seconds.ToString(); } Device.BeginInvokeOnMainThread(() => { TimerLabel.Text = labelText; }); return(true); // True = Repeat again, False = Stop the timer }); }
public HttpClientTileSource(HttpClient httpClient, ITileSchema tileSchema, string urlFormatter, IEnumerable <string> serverNodes = null, string apiKey = null, string name = null, BruTile.Cache.IPersistentCache <byte[]> persistentCache = null, Attribution attribution = null) { _HttpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); _WrappedSource = new HttpTileSource(tileSchema, urlFormatter, serverNodes, apiKey, name, persistentCache, ClientFetch, attribution); }
/// <summary> /// Method to extract all image layers from a wmts capabilities document. /// </summary> /// <param name="capabilties">The capabilities document</param> /// <param name="tileSchemas">A set of</param> /// <returns></returns> private static IEnumerable <HttpTileSource> GetLayers(Capabilities capabilties, List <WmtsTileSchema> tileSchemas) { var tileSources = new List <HttpTileSource>(); foreach (var layer in capabilties.Contents.Layers) { var identifier = layer.Identifier.Value; var title = layer.Title?[0].Value; string @abstract = layer.Abstract != null ? layer.Abstract[0].Value : string.Empty; foreach (var tileMatrixLink in layer.TileMatrixSetLink) { foreach (var style in layer.Style) { foreach (var format in layer.Format) { if (!format.StartsWith("image/")) { continue; } var tileMatrixSet = tileMatrixLink.TileMatrixSet; var tileSchema = tileSchemas.First(s => Equals(s.Name, tileMatrixSet)); IRequest wmtsRequest; if (layer.ResourceURL == null) { var resourceUrls = CreateResourceUrlsFromOperations( capabilties.OperationsMetadata.Operation, format, capabilties.ServiceIdentification.ServiceTypeVersion.First(), layer.Identifier.Value, style.Identifier.Value, tileMatrixLink.TileMatrixSet); wmtsRequest = new WmtsRequest(resourceUrls, tileSchema.LevelToIdentifier); } else { var resourceUrls = CreateResourceUrlsFromResourceUrlNode( layer.ResourceURL, style.Identifier.Value, tileMatrixLink.TileMatrixSet); wmtsRequest = new WmtsRequest(resourceUrls, tileSchema.LevelToIdentifier); } //var layerName = layer.Identifier.Value; var styleName = style.Identifier.Value; var schema = tileSchema.CreateSpecific(title, identifier, @abstract, tileMatrixSet, styleName, format); var tileSource = new HttpTileSource(schema, wmtsRequest, name: title); tileSources.Add(tileSource); } } } } return(tileSources); }