How can I ensure that labels align with GeoJSON - leaflet

I have a very large map project which uses labels (and only labels from mapbox. That is, I don't get any boundaries or terrain from mapbox.)
I bring those vector tiles into Leaflet Using mapbox-gl-leaflet.
Generally, everything works great. However as soon as the map is taller than it is wide, the labels no longer align with the countries (which have been drawn as polygons using GeoJSON). Here is a pic of what happens and the relevant code is below.map with labels unaligned
map with labels not alignted
Any thoughts or insights would be helpful. Here is the code that brings in the tiles:
settings.globalVariables.labelTiles = L.mapboxGL({
accessToken: myAccessToken,
style: 'mapbox://styles/markslawton/ckgsqyzhi0diy19rwi98mlt4g',
pane: 'labels',
}).addTo(settings.globalVariables.map);
Here is the code that creates the map:
Window.map = settings.globalVariables.map = new L.map('map', {
zoomControl: false,
zoomDelta: settings.map.zoomDelta,
zoomSnap: settings.map.zoomSnap,
minZoom: settings.map.minZoom,
maxZoom: settings.map.maxZoom,
dragging: true,
trackResize: true,
attributionControl: false,
// maxBounds:[[-90,-180],[90,180]]
});

I'm not 100% sure, but I suspect the issue is with the north/south bounds of your map. Mapbox is constrained to the Web Mercator projection, which tops out at around 85º/-85º latitude. Judging from your image here, you are trying to show latitudes well north of there.
You probably need to constrain the bounds of your map with tighter bounds, or increase the minimum zoom, so this situation doesn't arise.

Related

Why does my Leaflet circle only show as a dot?

I'm trying to add circles to my map, but for some reason the circles only show as dots, irrespective of the radius size.
var circle = L.circle(map.unproject([9541, 7658], map.getMaxZoom()), {
radius: 500
}).addTo(map);
I'm using pixel coordinates, but as you can see I'm converting them, so even though I only get dots on the map, they show at the right coordinates. I would hope this isn't the issue, but...?
I've successfully added circleMarkers, but the radius doesn't grow when zooming. At least not that I could see.
So the question is: how can I get the dots to show as circles?
Using Leaflet 1.9.3
Update
It appears that with pixel coordinates you need to enter a really high value for the radius. Thought I had already tried this before asking the question but apparently not.
var circle = L.circle(map.unproject([9541, 7658], map.getMaxZoom()), {
radius: 50000
}).addTo(map);
Unfortunately they're all showing at different sizes, even with the same radius, but that's a different question...
I originally misread your question and gave an incorrect answer, sorry. Circle radius is static. I think that the best way to change it with zoom level would be to use a zoom event listener:
let currZoom = map.getZoom();
let circles = [/* Store your circles here as you create them */];
map.on("zoomend", () => {
const zoomDiff = map.getZoom() - currZoom;
currZoom = map.getZoom();
for (const circle of circles) {
circle.setRadius(circle.getRadius() * 2 ** zoomDiff);
}
});
It's been a while since I've worked with Leaflet, but I think that will do the trick.
Edited to account for your comment regarding multiple circles.

PNG Overlay not correct using L.CRS.EPSG3857 projection

I am using leaflet and openstreet maps. I created a png using EPSG3857 however the image is not laying correctly on the map.
if you look at the Baja Region and Florida you will see the data on land. The data should be over the water not the land.
var map = L.map('map', { editable: true },{crs: L.CRS.EPSG3857}).setView(initialCoordinates , initialZoom),
tilelayer =
L.tileLayer(url_tile,
{
noWrap: true,
maxZoom: 12, minZoom: 2, attribution: 'Data \u00a9 OpenStreetMap Contributors Tiles \u00a9 HOT'
}).addTo(map);
var overlay_image = 'images/webmercator-google.png';
imageBounds = [[-90, -180], [90, 180]];
L.imageOverlay(overlay_image, imageBounds, { opacity: 0.8 }).addTo(map);
When using EPSG:3857, Leaflet clamps all latitude data to +/-85.05° (or, to be precise, +/-20037508.34 on the EPSG:3857 Y coordinate). This is done to prevent data appearing outside of the coverage area of default EPSG:3857 tiles.
To illustrate this, consider the following bit of code:
for (var i=83; i<90; i+=0.1) {
L.marker([i, i]).addTo(map);
}
That should (naïvely) display a lot of markers in a diagonal-ish line. But when actually doing that, the result looks like:
See how the markers don't go north of the 85.01° parallel, and how that fits the limit of tiles (blue sea versus grey out-of-map background).
Remember, EPSG:3857 and any other (non-traverse, non-oblique) cylindrical projections cannot display the north/south poles because they get projected to an infinite Y coordinate.
OK, so what does this have to do with your problem? You're using:
imageBounds = [[-90, -180], [90, 180]];
But, since Leaflet will clamp latitudes, that's actually the same as doing:
imageBounds = [[-85.01, -180], [85.01, 180]];
Keep this in mind when using L.ImageOverlays that cover areas near the poles. You probably want to recreate your image using a narrower band of latitudes.

Leaflet.js (or other solution) zoom to magnified pixels without blur

I've been using Leaflet to display raster images lately.
What I would like to do for a particular project is be able to zoom in to an image so the pixels become magnified on the screen in a sharply delineated way, such as you would get when zooming in to an image in Photoshop or the like. I would also like to retain, at some zoom level before maximum, a 1:1 correspondence between image pixel and screen pixel.
I tried going beyond maxNativeZoom as described here and here, which works but the interpolation results in pixel blurring.
I thought of an alternative which is to make the source image much larger using 'nearest neighbour' interpolation to expand each pixel into a larger square: when zoomed to maxNativeZoom the squares then look like sharply magnified pixels even though they aren't.
Problems with this are:
image size and tile count get out of hand quickly (original image is 4096 x 4096)
you never get the 'pop' of a 1:1 correspondence between image pixel and screen pixel
I have thought about using two tile sets: the first from the original image up to it's maxNativeZoom, and then the larger 'nearest neighbour' interpolated image past that, following something like this.
But, this is more complex, doesn't avoid the problem of large tile count, and just seems inelegant.
So:
Can Leaflet do what I need it to and if so how?
If not can you point me in the right direction to something that can (for example, it would be interesting to know how this is achieved)?
Many thanks
One approach is to leverage the image-rendering CSS property. This can hint the browser to use nearest-neighbour interpolation on <img> elements, such as Leaflet map tiles.
e.g.:
img.leaflet-tile {
image-rendering: pixelated;
}
See a working demo. Beware of incomplete browser support.
A more complicated approach (but one that works across more browsers) is to leverage WebGL; in particular Leaflet.TileLayer.GL.
This involves some internal changes to Leaflet.TileLayer.GL to support a per-tile uniform, most critically setting the uniform value to the tile coordinate in each tile render...
gl.uniform3f(this._uTileCoordsPosition, coords.x, coords.y, coords.z);
...having a L.TileLayer that "displays" a non-overzoomed tile for overzoomed tile coordinates (instead of just skipping the non-existent tiles)...
var hackishTilelayer = new L.TileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
'attribution': 'Map data © OpenStreetMap contributors',
maxNonPixelatedZoom: 3
});
hackishTilelayer.getTileUrl = function(coords) {
if (coords.z > this.options.maxNonPixelatedZoom) {
return this.getTileUrl({
x: Math.floor(coords.x / 2),
y: Math.floor(coords.y / 2),
z: coords.z - 1
});
}
// Skip L.TileLayer.prototype.getTileUrl.call(this, coords), instead
// apply the URL template directly to avoid maxNativeZoom shenanigans
var data = {
r: L.Browser.retina ? '#2x' : '',
s: this._getSubdomain(coords),
x: coords.x,
y: coords.y,
z: coords.z // *not* this._getZoomForUrl() !
};
var url = L.Util.template(this._url, L.Util.extend(data, this.options));
return url;
}
... plus a fragment shader that rounds down texel coordinates prior to texel fetches (plus a tile-coordinate-modulo-dependant offset), to actually perform the nearest-neighbour oversampling...
var fragmentShader = `
highp float factor = max(1., pow(2., uTileCoords.z - uPixelatedZoomLevel));
vec2 subtileOffset = mod(uTileCoords.xy, factor);
void main(void) {
vec2 texelCoord = floor(vTextureCoords.st * uTileSize / factor ) / uTileSize;
texelCoord.xy += subtileOffset / factor;
vec4 texelColour = texture2D(uTexture0, texelCoord);
// This would output the image colours "as is"
gl_FragColor = texelColour;
}
`;
...all tied together in an instance of L.TileLayer.GL (which syncs some numbers for the uniforms around):
var pixelated = L.tileLayer.gl({
fragmentShader: fragmentShader,
tileLayers: [hackishTilelayer],
uniforms: {
// The shader will need the zoom level as a uniform...
uPixelatedZoomLevel: hackishTilelayer.options.maxNonPixelatedZoom,
// ...as well as the tile size in pixels.
uTileSize: [hackishTilelayer.getTileSize().x, hackishTilelayer.getTileSize().y]
}
}).addTo(map);
You can see everything working together in this demo.

Leaflet disable vertical dragging out of bounds

Is it possible to only have vertical bounds in leaflet to remove grey bands above and below the leaflet map?
Grey bands around map
I still want to keep horizontal wrap but just want to remove the grey areas.
you can simply use the minZoom option, and set it to 3, that's what I do ;)
this.map.setView(new L.LatLng(31.585692323629303, 35.19333585601518), 2);
L.tileLayer(`https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png`, {
maxZoom: 20,
minZoom: 3,
attribution: 'HOT'
}).addTo(this.map);
in my case using angular, hope it help

leaflet editable restrict draw to a specific area

In Leaflet.Editable I want to confine/limit my customers to draw only in a specific area/bounds.
actually im trying to limit them to (90, -90, 180, -180) bounds of map..
maxBounds: [[-90, -180], [90, 180]]
I was not able to find anything anywhere and it seems that i am missing something.
CODEPEN DEMO
please help.
EDIT:
the Y axis is blocking correctly and mouse cannot stretch shape beyond top and bottom.
the problem is in X axis (as seen in pictures)
as for now i solved it with after save check and clear shape if it out of map bounds (BAD USER EXPERIENCE). i need a mouse confinement just like y axis does.
Without knowing your use case (why the whole world map??) Quickest and easiest fix would be to simply set the map's minZoom to something a bit higher, for example, I found that minZoom: 5 was adequate except for cases where the map was both really short and really wide (which is rarely the case in most apps I've seen).
But the real fix involves writing your own custom overrides for dragging markers and shapes.
According to API doc the L.Editable plugin allows you to override a bunch of stuff including the VertexMarker class, via map.editTools.options.vertexMarkerClass.
Fixed codepen: http://codepen.io/anon/pen/GrPpRY?editors=0010
This snippet of code that allows you to constrain the longitude for dragging vertex markers by correcting values under -180 and over 180 is this:
// create custom vertex marker editor
var vertexMarkerClass = L.Editable.VertexMarker.extend({
onDrag: function(e) {
e.vertex = this;
var iconPos = L.DomUtil.getPosition(this._icon),
latlng = this._map.layerPointToLatLng(iconPos);
// fix out of range vertex
if (latlng.lng < -180) {
e.latlng.lng = latlng.lng = -180;
this.setLatLng(latlng);
}
if (latlng.lng > 180) {
e.latlng.lng = latlng.lng = 180;
this.setLatLng(latlng);
}
this.editor.onVertexMarkerDrag(e);
this.latlng.update(latlng);
this._latlng = this.latlng; // Push back to Leaflet our reference.
this.editor.refresh();
if (this.middleMarker) this.middleMarker.updateLatLng();
var next = this.getNext();
if (next && next.middleMarker) next.middleMarker.updateLatLng();
}
});
// attach custom editor
map.editTools.options.vertexMarkerClass = vertexMarkerClass;
I didn't code for dragging the shape as a whole (the rectangle, in this case). While the VertexMarker fix should address all kinds of vertex dragging, you need to override each shape's drag handler to properly constrain the bounds. And if bounds are exceeded, crop the shape appropriately. As was pointed out, Leaflet already does this for latitude, but because Leaflet allows wrapping the map around horizontally you have your essential problem. Using rec.on("drag") to correct the bounds when they cross over your min/max longitude is the only way to address it. It is basically the same solution as I have laid out for the vertexMarkerClass - actual code left as exercise for the diligent reader.