admin管理员组文章数量:1389750
Is it possible to recreate the click to zoom on clustering like Craigslist Mapview does with MapBox? When you click, it zooms to the area those location dots are contained in.
Here's my clustering code:
map.on('load', function() {
map.addSource("location", {
type: "geojson",
data: ".cdpn.io/73873/test.geojson",
cluster: true,
clusterMaxZoom: 14,
clusterRadius: 100
});
map.addLayer({
id: "clusters",
type: "circle",
source: "location",
filter: ["has", "point_count"],
paint: {
"circle-color": {
property: "point_count",
type: "interval",
stops: [
[0, "#71AAC6"],
[100, "#71AAC6"],
[750, "#71AAC6"],
]
},
"circle-radius": {
property: "point_count",
type: "interval",
stops: [
[0, 20],
[100, 30],
[750, 40]
]
}
}
});
Here's my demo
Codepen Demo
Is it possible to recreate the click to zoom on clustering like Craigslist Mapview does with MapBox? When you click, it zooms to the area those location dots are contained in.
Here's my clustering code:
map.on('load', function() {
map.addSource("location", {
type: "geojson",
data: "https://s3-us-west-2.amazonaws./s.cdpn.io/73873/test.geojson",
cluster: true,
clusterMaxZoom: 14,
clusterRadius: 100
});
map.addLayer({
id: "clusters",
type: "circle",
source: "location",
filter: ["has", "point_count"],
paint: {
"circle-color": {
property: "point_count",
type: "interval",
stops: [
[0, "#71AAC6"],
[100, "#71AAC6"],
[750, "#71AAC6"],
]
},
"circle-radius": {
property: "point_count",
type: "interval",
stops: [
[0, 20],
[100, 30],
[750, 40]
]
}
}
});
Here's my demo
Codepen Demo
Share Improve this question asked Jan 12, 2018 at 18:32 meow-meow-meowmeow-meow-meow 5282 gold badges10 silver badges26 bronze badges 1- possible duplicate mapbox-gl-cluster-zoom answer here – Denis Tsoi Commented Jan 24, 2018 at 11:22
3 Answers
Reset to default 2I don't think that you can do it in pure Mapbox, at least not easily.
But for those cluster specific usages there is Supercluster (an official Mapbox geospatial point clustering library) which has exactly what you want:
getClusterExpansionZoom(clusterId)
Returns the zoom on which the cluster expands into several children (useful for "click to zoom" feature) given the cluster's
cluster_id
.
Edit: actually you could do it without Supercluster:
Using this JsFiddle example you can retrieve the points of the cluster you clicked.
map.on('click', function(e) { const cluster = map.queryRenderedFeatures(e.point, { layers: ["cluster"] }); if (cluster[0]) { // features: from the added source that are clustered const pointsInCluster = features.filter(f => { const pointPixels = map.project(f.geometry.coordinates) const pixelDistance = Math.sqrt( Math.pow(e.point.x - pointPixels.x, 2) + Math.pow(e.point.y - pointPixels.y, 2) ); return Math.abs(pixelDistance) <= clusterRadius; }); console.log(cluster, pointsInCluster); } });
Then you can create a
mapboxgl.LngLatBounds
andextend
it with all those points.You will obtain a LngLatBounds wrapping all your points so you can just call
fitBounds
on it and you are good to go.
As @MeltedPenguin said. You can do it without SuperCluster
. I search for several answers and finally did my own solution using coffeescript (you can convert it back to JS with tools like http://js2.coffee/):
@clusterRadius = 30
@map.on 'click', (e) =>
features = @map.queryRenderedFeatures(e.point, { layers: ['markers_layer'] });
if features && features.length > 0
if features[0].properties.cluster
cluster = features[0].properties
allMarkers = @map.queryRenderedFeatures(layers:['markers_layer_dot']);
self = @ #just a way to use 'this' un a function, its more verbose then =>
#Get all Points of a Specific Cluster
pointsInCluster = allMarkers.filter((mk) ->
pointPixels = self.map.project(mk.geometry.coordinates) #get the point pixel
#Get the distance between the Click Point and the Point we are evaluating from the Matrix of All point
pixelDistance = Math.sqrt((e.point.x - (pointPixels.x)) ** 2 + (e.point.y - (pointPixels.y)) ** 2)
#If the distant is greater then the disance that define a cluster, then the point si in the cluster
# add it to the boundaries
Math.abs(pixelDistance) <= self.clusterRadius
)
#build the bounding box with the selected points coordinates
bounds = new (mapboxgl.LngLatBounds)
pointsInCluster.forEach (feature) ->
bounds.extend feature.geometry.coordinates
return
#Move the map to fit the Bounding Box (BBox)
@map.fitBounds bounds, {padding:45, maxZoom: 16}
else
window.open('/en/ad/' + features[0].properties.propertyId)
On my page I have 2 layers based on the same source of data but with different attributes. One that define all dots (without clusters) and another one which define dots and clusters. For my display I use the "markers_layer" with clusters, and for calculate distance and stuff I use the other, as a DB of dots.
SOURCE:
@map.addSource "markers_source_wo_cluster",
type: "geojson"
data:
type: "FeatureCollection"
features: []
cluster: false
clusterMaxZoom: 10
clusterRadius: @clusterRadius
@map.addSource "markers_source",
type: "geojson"
data:
type: "FeatureCollection"
features: []
cluster: true
clusterMaxZoom: 60
clusterRadius: @clusterRadius
LAYER:
##============================================================##
## Add marker layer (Layer for QueryRender all dot without cluster)
##============================================================##
@map.addLayer
id: 'markers_layer_dot'
source: 'markers_source_wo_cluster'
type: "circle"
paint:
"circle-radius": 0 #This are 1 pixel dot for ref only
##============================================================##
## Add marker layer
##============================================================##
@map.addLayer
id: 'markers_layer'
source: 'markers_source'
type: 'symbol'
layout:
'icon-allow-overlap': true
'icon-image':'pin_map'
'icon-size':
stops: [[0,0.4], [40,0.4]]
I solved it like this https://github./mapbox/mapbox-gl-js/issues/9707
const handleClusterClick = React.useCallback(
(event: LayerMouseEvent, sourceId: string) => {
if (event && mapRef.current) {
const properties = getFeaturePropertiesFromMapEvent(event);
const coordinates = event.lngLat.toArray() as [number, number];
// skip cluster logic, clicked no point
if (properties?.type && coordinates) {
handlePointClick(event);
return;
}
const feature = event?.features?.[0];
const source = mapRef.current.getSource(sourceId);
if (
feature &&
feature.properties !== null &&
// @ts-expect-error typings
typeof source.getClusterExpansionZoom === "function"
) {
source
// @ts-expect-error typings
.getClusterExpansionZoom(
feature.properties.cluster_id,
(err: Error, expansionZoom: number) => {
if (!err && mapRef.current) {
mapRef.current.flyTo({
// @ts-expect-error typings
center: feature.geometry.coordinates,
zoom: expansionZoom,
maxDuration: MAX_FLY_TO_DURATION_MS,
});
}
},
);
} else {
mapRef.current.flyTo({
maxDuration: MAX_FLY_TO_DURATION_MS,
center: event.lngLat,
zoom: mapRef.current.getZoom() + 3, // This is bad UX, requires multiple clicks
});
}
}
},
[handlePointClick],
);
本文标签: javascriptMapBoxCluster ZoomingStack Overflow
版权声明:本文标题:javascript - MapBox - Cluster Zooming - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744674487a2619027.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论