Alexey
Alexey

Reputation: 2812

Inverted Y axis of custom tile images names

There is a know problem of Leaflet that when you use a custom tile provider, not with real earth images, set crs: L.CRS.Simple, Leaflet queries for images where Y coordinate is inverted in comparison to the math axis. So the first top-right image's location is 1x-1 instead of 1x1.

In the internet topics about inverting Y axis are rather old, so my question is: nowadays is there a normal short and built-in way to invert queried Y axis?

The only old solutions I've found were rewriting Leaflet internal objects, like extending L.CRS.Simple.

Upvotes: 2

Views: 1548

Answers (1)

IvanSanchez
IvanSanchez

Reputation: 19069

As noted in the Leaflet tutorial for WMS/TMS, the canonical way of inverting the Y coordinate for tile coordinates is using {-y} instead of {y} in the tile URL template. e.g.:

var layer = L.tileLayer('http://base_url/tms/1.0.0/tileset/{z}/{x}/{-y}.png');

Note, however, that (as of Leaflet 1.3.1) that only works for maps with a non-infinite coordinate system.

In your case, you might want to get around this by creating your own subclass of L.TileLayer. There is a complete guide on the Leaflet tutorial about extending layers, but the TL;DR version for a tilelayer that shifts its tile coordinates is:

L.TileLayer.CustomCoords = L.TileLayer.extend({
    getTileUrl: function(tilecoords) {
        tilecoords.x = tilecoords.x + 4;
        tilecoords.y = tilecoords.y - 8;
        tilecoords.z = tilecoords.z + 1;
        return L.TileLayer.prototype.getTileUrl.call(this, tilecoords);
    }
});

var layer = new L.TileLayer.CustomCoords(....);

And the specific case for just inverting the Y coordinate is:

L.TileLayer.InvertedY = L.TileLayer.extend({
    getTileUrl: function(tilecoords) {
        tilecoords.y = -tilecoords.y;
        return L.TileLayer.prototype.getTileUrl.call(this, tilecoords);
    }
});

var layer = new L.TileLayer.InvertedY(....);

Upvotes: 5

Related Questions