-1

I have written a small java program to check whether a lat/long coordinates is included in a generated vector mbtiles.

For instance, if I want to check if Paris is "present" in the mbtiles, this is what I do :

    public class TilesUtils {
  

         public static int longitudeToTileX(double longitude, int zoom) {
           double tileX = (longitude + 180) / 360 * (1 << zoom);
           return (int) Math.floor(tileX);
  }

         public static int latitudeToTileY(double latitude, int zoom) {
           double sinLatitude = Math.sin(Math.toRadians(latitude));
           double tileY = (0.5 - Math.log((1 + sinLatitude) / (1 - sinLatitude)) / (4 * Math.PI)) * (1 << zoom);
           return (int) Math.floor(tileY);
  }

And the unit test :

  @Test
  void should_check_if_Paris_is_included_in_mbtiles(){
    int zoom = 12;

    double latitude = 48.8669846;
    double longitude = 2.3470999;

    int tileX = TilesUtils.longitudeToTileX(longitude, zoom);
    int tileY = TilesUtils.latitudeToTileY(latitude, zoom);

    Assertions.assertTrue(checkTilesIsIncluded(tileX, tileY, zoom, "/path/to/mbtiles"));

}

private boolean checkTilesIsIncluded(int tileX, int tileY, int zoom, String mbTilesFilePath) {
    try(var connection = DriverManager.getConnection("jdbc:sqlite:" + mbTilesFilePath)){
        System.out.printf("Requesting tile x = %d, y = %d, zoom = %d%n", tileX, tileY, zoom);
        PreparedStatement preparedStatement = connection.prepareStatement("SELECT tile_data FROM tiles WHERE zoom_level = ? AND tile_column = ? AND tile_row = ?");
        preparedStatement.setInt(1, zoom);
        preparedStatement.setInt(2, tileX);
        preparedStatement.setInt(3, tileY);
        ResultSet resultSet = preparedStatement.executeQuery();
      return resultSet.next();
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }
  }

The test always returns false.

Just to add that my file is an extract from France. I don't know if this will affect the generation of the x, y coordinates of the tiles.

Dimitri
  • 8,122
  • 19
  • 71
  • 128

1 Answers1

1

Based on this answer https://gis.stackexchange.com/questions/437481/convert-maplibrejs-url-coordinates-to-mbtiles-tile-coumn-and-tile-row,

I had to flip the tileY coordinate because MBtiles files are TMS :

tileY = (1 << zoom) - 1 - tileY;

So I was able to find the tile in the file.

Dimitri
  • 8,122
  • 19
  • 71
  • 128