Skip to content

Commit

Permalink
refactor(SuperClusterAlgorithm): code cleanup (#632)
Browse files Browse the repository at this point in the history
  • Loading branch information
vicb committed May 23, 2023
1 parent a91b3a0 commit 50faccf
Showing 1 changed file with 19 additions and 20 deletions.
39 changes: 19 additions & 20 deletions src/algorithms/supercluster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export class SuperClusterAlgorithm extends AbstractAlgorithm {
protected superCluster: SuperCluster;
protected markers: Marker[];
protected clusters: Cluster[];
protected state: { zoom: number };
protected state: { zoom: number | null };

constructor({ maxZoom, radius = 60, ...options }: SuperClusterOptions) {
super({ maxZoom });
Expand All @@ -49,37 +49,34 @@ export class SuperClusterAlgorithm extends AbstractAlgorithm {

this.state = { zoom: null };
}

public calculate(input: AlgorithmInput): AlgorithmOutput {
let changed = false;
const state = { zoom: input.map.getZoom() };

if (!equal(input.markers, this.markers)) {
changed = true;
// TODO use proxy to avoid copy?
this.markers = [...input.markers];

const points = this.markers.map((marker) => {
const position = MarkerUtils.getPosition(marker);
const coordinates = [position.lng(), position.lat()];
return {
type: "Feature" as const,
geometry: {
type: "Point" as const,
coordinates: [
MarkerUtils.getPosition(marker).lng(),
MarkerUtils.getPosition(marker).lat(),
],
coordinates,
},
properties: { marker },
};
});
this.superCluster.load(points);
}

const state = { zoom: input.map.getZoom() };

if (!changed) {
if (this.state.zoom > this.maxZoom && state.zoom > this.maxZoom) {
// still beyond maxZoom, no change
} else {
changed = changed || !equal(this.state, state);
if (this.state.zoom <= this.maxZoom || state.zoom <= this.maxZoom) {
changed = !equal(this.state, state);
}
}

Expand All @@ -95,7 +92,9 @@ export class SuperClusterAlgorithm extends AbstractAlgorithm {
public cluster({ map }: AlgorithmInput): Cluster[] {
return this.superCluster
.getClusters([-180, -90, 180, 90], Math.round(map.getZoom()))
.map(this.transformCluster.bind(this));
.map((feature: ClusterFeature<{ marker: Marker }>) =>
this.transformCluster(feature)
);
}

protected transformCluster({
Expand All @@ -109,15 +108,15 @@ export class SuperClusterAlgorithm extends AbstractAlgorithm {
markers: this.superCluster
.getLeaves(properties.cluster_id, Infinity)
.map((leaf) => leaf.properties.marker),
position: new google.maps.LatLng({ lat, lng }),
});
} else {
const marker = properties.marker;

return new Cluster({
markers: [marker],
position: MarkerUtils.getPosition(marker),
position: { lat, lng },
});
}

const marker = properties.marker;

return new Cluster({
markers: [marker],
position: MarkerUtils.getPosition(marker),
});
}
}

0 comments on commit 50faccf

Please sign in to comment.