I am working with this Leaflet plugin: Leaflet-tilelayer-mask and I want to specify the mask center coordinate as opposed to it picking the base map's center coordinate. Tips on how to achieve this?

let map = L.map("map", {
    zoom: 16,
    center: [35.9734, 117.7926]

// background layer -- color filter plugin
let myTileLayer = L.tileLayer.colorFilter('https://{s}.tile.thunderforest.com/pioneer/{z}/{x}/{y}.png?apikey=xxxxxxxxxxxxxxxx', {
    attribution: ''

// mask layer -- tileLayer mask plugin
let mask = L.tileLayer.mask('https://{s}.tile.thunderforest.com/pioneer/{z}/{x}/{y}.png?apikey=xxxxxxxxxxxxxxxx', {
    maskSize: 512,
    maxZoom: 18,
    maxNativeZoom: 17

map.on("load", function(e) {
    // mask.setCenter(e.containerPoint);
    mask.setCenter({ lat: 35.9665, lng: 117.8089 }); // this doesn't work


  • 1
    If you look at the plugin docs at github.com/frogcat/leaflet-tilelayer-mask, you'll se that .setCenter method parameters should be in pixels relative to map container. – TomazicM Jun 15 at 5:49
  • @TomazicM that's correct but the mask will move when panning since its position, in pixels, is relative to the map's center and I intend that the mask is at a single exact position everytime. I guess I'll have to set a fixed viewing bounds to the map then. – b_jugger Jun 15 at 7:31
  • 1
    I didn't try it, but since .setCenter method pertains to L.tileLayer.mask, I would say only layer mask will be affected by it. It won't hurt if you try it. – TomazicM Jun 15 at 10:04
  • Sure, I did and work for a first draft of the task at hand. Thank you! @TomazicM . Maybe you post as the solution and I mark as same? – b_jugger Jun 15 at 11:06

There are two reasons why your code cannot work. If you looks at the plugin docs at https://github.com/frogcat/leaflet-tilelayer-mask, you'll see that .setCenter method parameter should be in pixels relative to map container, so you have to use map.map.latLngToContainerPoint method to convert geographical coordinates to pixel coordinates.

The second problem is that you are setting map's load event processing too late. This event is fired when map's center and zoom are set for the first time: Since in your case this happens at the time of map creation, your event never gets fired.

Code should then look something like this:

let map = L.map('map');
map.on('load', function(e) {
  var point = map.latLngToContainerPoint(L.latLng(35.9665, 117.8089));

map.setView([35.9734, 117.7926], 16);
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.