Skip to content

Instantly share code, notes, and snippets.

@geobabbler
Created February 25, 2014 17:13
Show Gist options
  • Save geobabbler/9213392 to your computer and use it in GitHub Desktop.
Save geobabbler/9213392 to your computer and use it in GitHub Desktop.
Simple class to access MBTiles in C#
public class MBTilesProvider
{
public GeoExtent Bounds { get; private set; }
public CoordinatePair Center { get; private set; }
public int MinZoom { get; private set; }
public int MaxZoom { get; private set; }
public string Name { get; private set; }
public string Description { get; private set; }
public string MBTilesVersion { get; private set; }
public string Path { get; private set; }
private GlobalMercator gmt = new GlobalMercator();
public MBTilesProvider(string path)
{
this.Path = path;
loadMetadata();
}
private void loadMetadata()
{
try
{
using (SQLiteConnection conn = new SQLiteConnection(String.Format("Data Source={0};Version=3;", this.Path)))
{
conn.Open();
using (SQLiteCommand cmd = new SQLiteCommand() { Connection = conn, CommandText = "SELECT * FROM metadata;"})
{
SQLiteDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string name = reader["name"].ToString();
switch (name.ToLower())
{
case "bounds":
string val = reader["value"].ToString();
string[] vals = val.Split(new char[] { ',' });
this.Bounds = new GeoExtent() { West = Convert.ToDouble(vals[0]), South = Convert.ToDouble(vals[1]), East = Convert.ToDouble(vals[2]), North = Convert.ToDouble(vals[3]) };
break;
case "center":
val = reader["value"].ToString();
vals = val.Split(new char[] { ',' });
this.Center = new CoordinatePair() { X = Convert.ToDouble(vals[0]), Y = Convert.ToDouble(vals[1]) };
break;
case "minzoom":
this.MinZoom = Convert.ToInt32(reader["value"]);
break;
case "maxzoom":
this.MaxZoom = Convert.ToInt32(reader["value"]);
break;
case "name":
this.Name = reader["value"].ToString();
break;
case "description":
this.Description = reader["value"].ToString();
break;
case "version":
this.MBTilesVersion = reader["value"].ToString();
break;
}
}
}
}
}
catch
{
}
}
public Image GetTile(double latitude, double longtiude, int zoom)
{
Image retval = null;
var llt = gmt.LatLonToTile(latitude, longtiude, zoom);
try
{
using (SQLiteConnection conn = new SQLiteConnection(String.Format("Data Source={0};Version=3;", Path)))
{
conn.Open();
using (SQLiteCommand cmd = new SQLiteCommand() { Connection = conn, CommandText = String.Format("SELECT * FROM tiles WHERE tile_column = {0} and tile_row = {1} and zoom_level = {2};", llt.X, llt.Y, zoom) })
{
SQLiteDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
byte[] bytes = reader["tile_data"] as byte[];
using (MemoryStream stream = new MemoryStream(bytes))
{
retval = Image.FromStream(stream);
}
}
}
}
}
catch
{
retval = null;
}
return retval;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment