XAML-Map-Control/MBTiles/Shared/MBTileSource.cs

88 lines
2.5 KiB
C#
Raw Normal View History

2025-04-01 16:11:53 +02:00
using Microsoft.Extensions.Logging;
using System;
2024-08-20 18:00:04 +02:00
using System.Collections.Generic;
using System.Data.SQLite;
using System.IO;
using System.Threading.Tasks;
2024-05-22 11:25:32 +02:00
#if WPF
using System.Windows.Media;
2021-11-17 23:46:48 +01:00
#elif UWP
using Windows.UI.Xaml.Media;
2024-05-22 11:25:32 +02:00
#elif WINUI
using Microsoft.UI.Xaml.Media;
#elif AVALONIA
using ImageSource = Avalonia.Media.IImage;
#endif
namespace MapControl.MBTiles
{
2025-02-23 18:49:07 +01:00
public sealed class MBTileSource : TileSource, IDisposable
{
2025-04-01 16:11:53 +02:00
private static ILogger logger;
private static ILogger Logger => logger ?? (logger = ImageLoader.LoggerFactory?.CreateLogger<MBTileSource>());
2024-08-20 18:00:04 +02:00
private SQLiteConnection connection;
2024-08-20 18:00:04 +02:00
public IDictionary<string, string> Metadata { get; } = new Dictionary<string, string>();
public async Task OpenAsync(string file)
{
2024-08-20 18:00:04 +02:00
Close();
2024-09-05 20:38:49 +02:00
connection = new SQLiteConnection("Data Source=" + Path.GetFullPath(file) + ";Read Only=True");
2024-08-20 18:00:04 +02:00
await connection.OpenAsync();
using (var command = new SQLiteCommand("select * from metadata", connection))
2021-11-10 22:31:06 +01:00
{
2024-08-20 18:00:04 +02:00
var reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
Metadata[(string)reader["name"]] = (string)reader["value"];
}
}
}
public void Close()
{
if (connection != null)
{
Metadata.Clear();
connection.Dispose();
connection = null;
2021-11-10 22:31:06 +01:00
}
}
public void Dispose()
{
2025-02-23 18:49:07 +01:00
Close();
}
public override async Task<ImageSource> LoadImageAsync(int x, int y, int zoomLevel)
{
2021-11-10 22:31:06 +01:00
ImageSource image = null;
2024-08-20 18:00:04 +02:00
try
2021-11-10 22:31:06 +01:00
{
2025-02-23 18:49:07 +01:00
using (var command = new SQLiteCommand("select tile_data from tiles where zoom_level=@z and tile_column=@x and tile_row=@y", connection))
2021-11-10 22:31:06 +01:00
{
2025-02-23 18:49:07 +01:00
command.Parameters.AddWithValue("@z", zoomLevel);
command.Parameters.AddWithValue("@x", x);
command.Parameters.AddWithValue("@y", (1 << zoomLevel) - y - 1);
2025-03-09 21:40:37 +01:00
var buffer = (byte[])await command.ExecuteScalarAsync();
image = await LoadImageAsync(buffer);
2021-11-10 22:31:06 +01:00
}
}
2024-08-20 18:00:04 +02:00
catch (Exception ex)
{
2025-04-01 16:11:53 +02:00
Logger?.LogError(ex, "LoadImageAsync");
2024-08-20 18:00:04 +02:00
}
2021-11-10 22:31:06 +01:00
return image;
}
}
}