Skip to content

Instantly share code, notes, and snippets.

@alfiankan
Created April 25, 2022 02:40
Show Gist options
  • Save alfiankan/36138b1843f16abcaea1150fd9b37bba to your computer and use it in GitHub Desktop.
Save alfiankan/36138b1843f16abcaea1150fd9b37bba to your computer and use it in GitHub Desktop.
render icon for cluster marker
const loading = document.getElementById('loading')
let isLoading = false
function getJSON(url, callback) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.onload = function () {
if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 300 && xhr.response) {
callback(xhr.response);
}
};
xhr.send();
}
const map = L.map('map').setView([0, 0], 2);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
const markers = L.geoJson(null, {
pointToLayer: createClusterIcon
}).addTo(map);
function update() {
if (isLoading) {
return
}
isLoading = true
const bounds = map.getBounds();
console.log(bounds)
console.log({
bbox: [bounds.getWest(), bounds.getSouth(), bounds.getEast(), bounds.getNorth()],
zoom: map.getZoom()
});
console.log(bounds.getWest(), bounds.getSouth(), bounds.getEast(), bounds.getNorth(), map.getZoom())
loading.innerHTML = `Processing ...`
const before = new Date();
getJSON(`http://localhost:3000/points?west=${bounds.getWest()}&south=${bounds.getSouth()}&east=${bounds.getEast()}&north=${bounds.getNorth()}&zoom=${map.getZoom()}`, (geojson) => {
console.log(geojson);
markers.clearLayers();
markers.addData(geojson);
const now = new Date();
const diff = now - before;
loading.innerHTML = `Took ${diff} milliseconds`
isLoading = false
});
}
map.on('moveend', update);
map.whenReady(update);
function createClusterIcon(feature, latlng) {
if (!feature.properties.cluster) {
const tweetIcon = L.icon({
iconUrl: 'http://localhost:3000/twitter.svg',
iconSize: [40, 40], // size of the icon
});
let singleMarker = L.marker(latlng, { icon: tweetIcon }).bindPopup(feature.properties.name);
singleMarker.on('mouseover', function (e) {
this.openPopup();
});
singleMarker.on('mouseout', function (e) {
this.closePopup();
});
return singleMarker
}
const count = feature.properties.point_count;
const size =
count < 100 ? 'small' :
count < 1000 ? 'medium' : 'large';
const icon = L.divIcon({
html: `<div><span>${feature.properties.point_count_abbreviated}</span></div>`,
className: `marker-cluster marker-cluster-${size}`,
iconSize: L.point(40, 40)
});
return L.marker(latlng, { icon });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment