I have an application that serves vector tiles. The features in the tiles are clickable. When a user clicks the map, I pass mapbox-gl's queryRenderedFeatures a 5 x 5px bounding box around the clicked point.
Is there a way to ascertain the lat-lon bounding box that mapbox uses to query its cached tiles? I would like to have this bounding box so I can query the database for the features around the clicked point. I can use the ids of the features in the vector tiles, but this becomes cumbersome/untenable when there are 1000s of features.
Here's how I am getting features near point, where:
map is the mapbox map object
mapboxLayers are the names of the layers I want to query
point is point property of the click event
export const getMapFeaturesNearPoint = ({ map, mapboxLayers, point }) => {
const { x, y } = point;
const halfPixels = 5;
// set bbox as 5px rectangle around clicked point
const bbox = [
[x - halfPixels, y - halfPixels],
[x + halfPixels, y + halfPixels],
];
const features = map.queryRenderedFeatures(bbox, { layers: [...mapboxLayers] })
return features;
};
Note: I have tried doing the following with the bbox defined above: bbox.map(pt => map.unproject(pt)) to get the lat lon bounding box. From my examination of the mapboxgl source code, it seems the process to unproject queryRenderedFeatures coordinates is a bit more complex than that.
Not very clear to me what you are trying to get, but conceptually speaking, what any queryRenderedFeatures is doing with no filters, is basically find all the tiles in the cache (the ones cached are in the viewport), then per tile, get all the features on them, and merge them all into the result. So, if you use queryRenderedFeatures with no arguments or with only a options argument is equivalent to passing a bounding box encompassing the entire map viewport.
You can check the source code of query_features.js file in Mapbox github repo
With those features in the viewport, it would be easy to reduce them to a lnglat bounding box through a .reduce function that you can use, for instance, as a bounding box to use map.fitBounds.
var coordinates = points;
var bounds = coordinates.reduce(function(bounds, coord) {
return bounds.extend(coord);
}, new mapboxgl.LngLatBounds(coordinates[0], coordinates[0]));
map.fitBounds(bounds, {
padding: { top: 50, bottom: 50, left: 50, right: 50 },
easing(t) {
return t * (2 - t);
}
});
But as said, not sure if that's what you are looking for.
Other option would be to use the canvas width and height and unproject them... I found this code while ago,
const canvas = map.getCanvas()
const w = canvas.width
const h = canvas.height
const cUL = map.unproject ([0,0]).toArray()
const cUR = map.unproject ([w,0]).toArray()
const cLR = map.unproject ([w,h]).toArray()
const cLL = map.unproject ([0,h]).toArray()
const coordinates = [cUL,cUR,cLR,cLL,cUL]
Related
In Leaflet docs, L.Circle Radius is based on meters, but how can I draw a Circle based on coordinates instead?
More specifically, I want to draw a circle that encompasses a specific bounding box
const myCenter = [37, -122];
const myBoundingBox = {
northEast: [myCenter[0]+2, myCenter[1]+2],
southWest: [myCenter[0]-2, myCenter[1]-2]
};
const circle = L.circle(myCenter, {radius: ??}).addTo(map);
I've figured it out, use map.distance function to get distance in meters between the diagonal points of the bounds
const circleRadius = map.distance(myBoundingBox[northEast], myBoundingBox[southWest])/2
Then just create the circle normally using the radius in meters
I have created Multi polygons using h3SetToMultiPolygon from the list of H3 cell ids as shown below:
Now I want to get the center (I know it's not a perfect shape to get the center, but a rough one should be fine) of the Multi Polygon which I am unable to get using any H3 or leaflet methods.
I want to show a marker at the center of the boundary of the multi polygons as shown below roughly:
Any help would be appreciated.
Here is my code:
const clusterBoundaryCoordinates = [];
clusters?.forEach((element) => {
clusterBoundaryCoordinates.push(
h3.h3SetToMultiPolygon(element.cellIdsArr, true)
);
});
This isn't really specific to H3 - in general, you want an algorithm that can give you the centroid of a polygon, e.g. #turf/centroid. There are different centroid algorithms based on the use case - e.g. you may or may not require the centroid to be inside a concave polygon (think a C shape) or within one of many small polygons in a multipolygon (think an archipelago).
There's an interesting H3-based option here as well, though I don't know offhand how to make it performant. You can find the center cell by finding the cell whose mean distance to all other cells is lowest, e.g.
let min = Infinity;
let center = null;
for (const cell of cells) {
let total = 0;
for (const neighbor of cells) {
total += h3.h3Distance(cell, neighbor);
}
if (total < min) {
min = total;
center = cell;
}
}
This will always give you a cell in your set, so it will always be within your area, and should give a reasonable value even for pathological shapes. But, because the algorithm is O(n^2), it's going to be very slow for large sets of cells.
I found the solution. I didn't notice earlier that to find the center, I can utilize the lat longs which I receive when I do h3SetToMultiPolygon (it returns the lat long in reverse order).
const clusterBoundaryCoordinates = [];
clusters?.forEach((element) => {
clusterBoundaryCoordinates.push(
h3.h3SetToMultiPolygon(element.cellIdsArr, true); //it returns the latlong in reverse order, so need to reverse it
);
});
const getCentroid = (arr) => {
return arr.reduce(
(x, y) => {
return [x[0] + y[0] / arr.length, x[1] + y[1] / arr.length];
},
[0, 0]
);
};
const centroid = getCentroid(clusterBoundaryCoordinates);
I am trying to get the latlng coordinates of the bottom left and top right corners of an svg element (orange box in the picture) I overlayed on top of the map. However, the latlng coordinates I am getting from transforming the pixel coordinates is off by a wide margin.
Coordinates I should be getting from this view:
BL: [-18.9, -39.1],
TR: [48.8, 39.3]
Coordinates I am actually getting:
BL: [-30.3, 127.0],
TR: [40.9, 205.9]
This is the code I am using to determine the pixel position:
this.navigation.on('moveend zoomend', () => {
const bounds = L.DomUtil.get("compBorder")!.getBoundingClientRect();
const bl1 = L.point(bounds.left, bounds.bottom)
const tr1 = L.point(bounds.right, bounds.top)
const bl = this.navigation.layerPointToLatLng(bl1);
const tr = this.navigation.layerPointToLatLng(tr1);
this.cs.setBlTr([bl.lat, bl.lng], [tr.lat, tr.lng]);
this.cs.setCenter(this.navigation.getCenter());
this.cs.setZoom(this.navigation.getZoom());
});
From what I am seeing it doesn't seem to make a difference whether I use the layerPointToLatlng() or the containerPointToLatlng() function.
Using this example from OS Data Hub - https://labs.os.uk/public/os-data-hub-examples/os-maps-api/zxy-27700-basic-map
I can get a list of tiles displayed on the map, I would like to get the coordinates of the tile without drawing the map.
Starting from a single point in WGS84 (lat/long) I can convert this to EPSG:27700 using Proj4js
var source = new proj4.Proj('EPSG:4326');
proj4.defs("EPSG:27700","+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +datum=OSGB36 +units=m +no_defs");
var dest = new proj4.Proj('EPSG:27700');
var coords=proj4.transform(source, dest, [X,Y]);
I then need to translate this into coordinates for the raster tile, which is done in the leaflet example with this code:
var crs = new L.Proj.CRS('EPSG:27700', '+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +towgs84=446.448,-125.157,542.06,0.15,0.247,0.842,-20.489 +units=m +no_defs', {
resolutions: [ 896.0, 448.0, 224.0, 112.0, 56.0, 28.0, 14.0, 7.0, 3.5, 1.75 ],
origin: [ -238375.0, 1376256.0 ]
});
How can i replicate this step to produce the tile coordinates, without having to draw the leaflet map?
I ultimately want to use the coordinates to grab & save a single tile from the OS Data Hub with this format:
https://api.os.uk/maps/raster/v1/zxy/layer/%7Bz%7D/%7Bx%7D/%7By%7D.png?key=
Using the EPSG:27700 coords calculated using proj4, and the zoom level resolutions (which are meters per pixel) and tile grid origin coordinates used in the definition you can calculate the {x} and {y} values in https://api.os.uk/maps/raster/v1/zxy/layer/{z}/{x}/{y}.png?key= for any zoom level {z} based on the standard tile size of 256 pixels as
x = Math.floor((coords[0] - origin[0]) / (resolutions[z] * 256));
y = Math.floor((origin[1] - coords[1]) / (resolutions[z] * 256));
Does anyone know a way to make overlapping circles in mapbox show the same color and only have the border around the outer edge display?
I have this:
And I made this in photoshop for what I want:
While I don't think there is a way to style all the circles to show their group outline, you can achieve the effect you want by creating a union of all the circle geometries and applying your style to that. Unfortunately, Leaflet's L.circle class offers no way to access a circle's geometry beyond the center point, and to perform a union, you need the path of the circle itself. Fortunately, there is Leaflet Geodesy and its LGeo.circle class, which produces circular polygons with a given radius and number of segments. Once you have these polygon representations of your circles, you can use turf.union to produce the outline you want.
Say you are starting with a layer of points called pointLayer (this can be a L.geoJson, L.mapbox.featureLayer, or any other class that inherits the .eachLayer method). You can then iterate over the features, creating a circular polygon for each of them and adding it to a temporary layer group, like this:
var circleLayer = L.layerGroup();
var radius = 5000
var opts = {
parts: 144
};
pointLayer.eachLayer(function(layer) {
LGeo.circle(layer.getLatLng(), radius, opts).addTo(circleLayer);
});
where radius is in meters and the parts option is the number of segments you want your polygons to have. Next, use the .getLayers method to get an array of all the layers in the temporary group, then iterate over that to create a union of all the features:
var circleUnion = unify(circleLayer.getLayers()).addTo(map);
function unify(polyList) {
for (var i = 0; i < polyList.length; ++i) {
if (i == 0) {
var unionTemp = polyList[i].toGeoJSON();
} else {
unionTemp = turf.union(unionTemp, polyList[i].toGeoJSON());
}
}
return L.geoJson(unionTemp, {style: unionStyle});
}
where unionStyle is whatever style you want to apply to your newly-combined circles. Here is an example fiddle showing all this with some random data:
http://fiddle.jshell.net/nathansnider/L2d626hn/