User:Habst/mapLocations.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// max = 60 -> 250
window.level = '';
window.qids ??= {};
window.locs ??= {};
window.delay = 1000;
window.features = [];
pre=''
window.colors = {Platinum:'blue',Gold:'gold',Silver:'silver',Elite:'silver',Bronze:'bronze',Challenger:'black',Label:'black'};
get = async (url) => {
  console.log(url);
  await new Promise(res => setTimeout(res, window.delay));
  return await (await fetch(url)).json();
}
(async () => {
for (const tr of document.querySelector('.wikitable').querySelectorAll('tbody tr')) {
  const tds = tr.querySelectorAll('td');
  if (tds.length === 1) {
    level = tds[0].innerText.split(' ')[0];
    continue;
  }
  const date = new Date(tds[0].querySelector('span').getAttribute('data-sort-value').replace(/^0+/, '').replace(/-0+$/, ''));
  let loctitle = decodeURIComponent(tds[2].querySelector('a').href.split('/').at(-1));
  loctitle = {Athina:'Athens',Maia:'Maia, Portugal'}[loctitle] ?? loctitle;
  window.qids[loctitle] ??= await get(`https://en.wikipedia.org/w/api.php?${new URLSearchParams({action:'query',prop:'pageprops',ppprop:'wikibase_item',format:'json',titles:loctitle,redirects:''})}`);
  const pid = Object.keys(qids[loctitle].query.pages)[0];
  const qid = qids[loctitle].query.pages[pid].pageprops?.wikibase_item;
  window.locs[qid] ??= await get(pre+`https://www.wikidata.org/w/api.php?${new URLSearchParams({action:'wbgetclaims',format:'json',entity:qid,property:'P625'})}`);
  const { latitude, longitude } = locs[qid].claims.P625[0].mainsnak.datavalue.value;
  console.log(loctitle, qid, latitude, longitude);
  const coord = `{{coord|${latitude}|${longitude}}}`;
  const dt = date.toLocaleString('sv').split('T')[0];
  const matchFt = features.find(ft => ft['mark-coord'] === coord);
  if (matchFt) {
    matchFt['mark-title'] += `, [[${tds[1].innerText}]]`;
    matchFt['mark-description'] += `, ${level} (${dt})`;
    if (colors[level] !== matchFt['shape-color']) matchFt['shape-color'] = 'red';
  } else {
    features.push({
      'mark-coord': coord,
      'mark-title': `[[${tds[1].innerText}]]`,
     'mark-description': `${level} (${dt})`,
      shape: 'n-circle',
      'shape-color': `${colors[level]}`
    });
  }
};
const out = `
{{OSM Location map
| zoom = 0
| float = right
| width = 300
| height = 250
| caption = 
| title = 2024 World Athletics Label Road Races
| mark = Invisible.png

${features.map((ft, i) => Object.entries(ft).map(([k,v]) => `| ${k}${i+1} = ${v}`).join('\n')).join('\n')}
}}
`;
console.log(out);
return out;
})();