# Voronoi delivery districts

Move office A and the boundaries between all four offices update. A dotted line connects the fixed envelope to its nearest office.

## Try it

Choose Bring A to the envelope. The nearest office changes from B to A. Move A west to return the envelope to B’s district.

## Interaction details

Each location belongs to its nearest office by straight-line distance. Only A can move. The other three offices and the envelope remain fixed. With reduced motion, presets move A immediately.

## Platform controls

- iOS · Tap anywhere on the map or drag A. Use the two position buttons to compare which office serves the envelope.
- Android · Tap anywhere on the map or drag A. Use the two position buttons to compare which office serves the envelope.
- PC · Focus the map and move A with the arrow keys, or select a position button. You can also click or drag on the map.

## Where to use it

Show which facility is closest to each address as a facility location changes.

## Implementation prompt

> Recompute the four nearest-site districts whenever one office moves. Find the site closest to a fixed address and update both its name and the connecting line.

## Sources and credits

[D3 · Voronoi diagrams](<https://d3js.org/d3-delaunay/voronoi>)

## Standalone HTML

Save the code below as an HTML file and open it in your browser. The example works offline.

```html
<!doctype html>
<html lang="en" data-motion-locales="inline"><head><script>if(new URLSearchParams(location.search).get('reduce')==='1')document.documentElement.classList.add('motion-reduced');</script><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>우편 배달 구역 · MotionLab</title>
<style>
*{box-sizing:border-box}:root{color-scheme:light;background:#f1ebda;color:#233e3d;font:15px/1.45 system-ui,sans-serif}body{margin:0;min-height:100svh;display:grid;align-content:center;padding:clamp(10px,2.5vw,24px)}main{width:min(100%,700px);margin:0 auto}header{display:flex;align-items:end;justify-content:space-between;gap:8px;flex-wrap:wrap;margin-bottom:9px}h1{font:700 clamp(21px,4vw,30px)/1.15 Georgia,serif;margin:0;letter-spacing:-.02em}.label{font-size:12px;font-weight:650;color:#4e5c51}
.plate{overflow:hidden;border:1px solid #50605a;border-radius:7px;background:#fffbeb}svg{display:block;width:100%;height:auto;touch-action:none;user-select:none;cursor:crosshair}svg:focus-visible{outline:4px solid #1b5755;outline-offset:-5px}.district{stroke:#515f57;stroke-width:1.3;stroke-linejoin:round}.roads{fill:none;stroke:#fff8d3;stroke-width:3.7;opacity:.65;pointer-events:none}.station text{font:700 13px/1 system-ui,sans-serif;fill:white;text-anchor:middle;dominant-baseline:central}
.legend{display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:8px 11px;font:650 12px/1.35 system-ui,sans-serif;background:#274841;color:#fff9e9}.badge{display:inline-grid;place-content:center;width:23px;height:23px;border-radius:100%;background:#fff9e9;color:#24413c;font-weight:800}
.controls{display:flex;align-items:center;gap:7px;flex-wrap:wrap;margin-top:10px}button{border:1px solid #98a494;color:#213e37;background:#faf9eb;font:650 13px/1.3 system-ui,sans-serif;cursor:pointer;min-height:38px;border-radius:22px;padding:7px 13px}button:focus-visible{outline:3px solid #1a6963;outline-offset:2px}.hint{font-size:13px;margin:7px 0 0;color:#3e514a}
@media(min-width:600px) and (max-height:560px){body{padding:8px 16px}main{width:min(100%,640px)}}
</style></head><body><main>
<header><h1 data-t="title"></h1><span class="label" data-t="tech"></span></header>
<div class="plate"><svg tabindex="0" id="map" viewBox="0 0 460 220" role="group" aria-labelledby="mapTitle" aria-describedby="hint">
<title id="mapTitle" data-t="label"></title>
<defs><pattern id="dots" width="7" height="7" patternUnits="userSpaceOnUse"><circle cx="2" cy="3" r=".65" fill="#314a3e" opacity=".22"/></pattern></defs>
<g id="cells"></g><rect width="460" height="220" fill="url(#dots)" pointer-events="none"/>
<g class="roads"><path d="M-5 16Q67 47 125 30T261 51 465 34M-7 105l108 9 68-53 90 17 54-41 151 9M-8 164l83-13 65 17 80-33 65 12 62-25 116 15M24 222l43-132-13-93m158 224l12-38 72-54 15-48-4-78m74 218l-21-85 53-78 20-60M140 220l23-90-14-59 8-75"/></g>
<path d="M-8 202Q49 192 95 204T210 183Q271 164 301 175T389 180Q424 166 466 168" fill="none" stroke="#f7f4d7" stroke-width="9" opacity=".75"/><path d="M-8 202Q49 192 95 204T210 183Q271 164 301 175T389 180Q424 166 466 168" fill="none" stroke="#74a9a4" stroke-width="4"/>
<line id="delivery" stroke="#273f3c" stroke-width="1.8" stroke-dasharray="5 4"/><g id="stations"></g>
<g transform="translate(244 105)" fill="#fff8dd" stroke="#2b4540" stroke-width="1.6" pointer-events="none"><circle r="14.8"/><path d="M-9-5h18V6H-9z"/><path d="m-9-5 9 7 9-7" fill="none"/></g>
</svg><div class="legend"><span data-t="owner"></span><output class="badge" aria-live="polite" id="owner"></output></div></div>
<div class="controls"><button id="west" data-t="west"></button><button id="center" data-t="center"></button></div>
<p class="hint" id="hint" data-t="hint"></p></main><script>
const copy={
 ko:{title:"골목 우편 배달 구역",tech:"보로노이 영역",label:"우체국 A를 움직이는 배달 지도",owner:"봉투에 가장 가까운 우체국",west:"A를 서쪽으로",center:"A를 봉투 곁으로",hint:"지도 위를 누르거나 A를 끌어 보세요. 지도에 초점을 두면 방향키로 옮길 수 있습니다."},
 en:{title:"The postal districts",tech:"Voronoi regions",label:"Delivery map with movable post office A",owner:"Nearest office to the envelope",west:"Move A west",center:"Bring A to the envelope",hint:"Tap the map or drag A. Focus the map and use the arrow keys to move the office."},
 es:{title:"El mapa postal",tech:"Regiones de Voronói",label:"Mapa de reparto con la oficina móvil A",owner:"Oficina más cercana al sobre",west:"Llevar A al oeste",center:"Acercar A al sobre",hint:"Toca el mapa o arrastra A. Con el foco en el mapa, utiliza las flechas para mover la oficina."},
 "zh-Hans":{title:"街区邮递图",tech:"沃罗诺伊区域",label:"可移动邮局 A 的投递地图",owner:"离信封最近的邮局",west:"将 A 移到西边",center:"将 A 移至信封旁",hint:"点按地图或拖动 A。选中地图后，也可以使用方向键移动邮局。"}
};
const query=new URLSearchParams(location.search),lang=query.get('lang')||document.documentElement.lang||'ko',t=copy[lang]||copy.ko;
document.documentElement.lang=copy[lang]?lang:'ko';document.title=t.title+' · MotionLab';
for(const el of document.querySelectorAll('[data-t]'))el.textContent=t[el.dataset.t];
const byId=id=>document.getElementById(id),map=byId('map'),svgNS='http://www.w3.org/2000/svg';
const sites=[[94,68],[325,59],[113,176],[371,171]],colors=['#dcad77','#b7c696','#a8c5b5','#d5a499'],address=[244,105];
const media=matchMedia('(prefers-reduced-motion: reduce)'),reduce=()=>query.get('reduce')==='1'||document.documentElement.classList.contains('motion-reduced')||media.matches;
let frame=0,drag=null;
function el(name,attrs,parent){
 const n=document.createElementNS(svgNS,name);for(const [k,v] of Object.entries(attrs))n.setAttribute(k,v);parent.append(n);return n;
}
const cells=sites.map((s,i)=>el('polygon',{class:'district',fill:colors[i]},byId('cells')));
const dots=sites.map((s,i)=>{
 const n=el('g',{class:'station','data-site':i},byId('stations'));
 if(!i)el('circle',{r:16,fill:'none',stroke:'#29433d','stroke-dasharray':'3 3'},n);
 el('circle',{r:11,fill:i===0?'#78492b':'#36534b',stroke:'#fff8dd','stroke-width':1.7},n);
 el('text',{x:0,y:-.2},n).textContent='ABCD'[i];return n;
});
// Clip the board against every perpendicular bisector, retaining the side nearest the site.
function clip(poly,a,b){
 const nx=b[0]-a[0],ny=b[1]-a[1],c=(b[0]*b[0]+b[1]*b[1]-a[0]*a[0]-a[1]*a[1])/2;
 const result=[];let prev=poly[poly.length-1];if(!prev)return result;
 let dp=prev[0]*nx+prev[1]*ny-c;
 for(const next of poly){
   const dn=next[0]*nx+next[1]*ny-c;
   if((dp<=0)!==(dn<=0)){const w=dp/(dp-dn);result.push([prev[0]+(next[0]-prev[0])*w,prev[1]+(next[1]-prev[1])*w]);}
   if(dn<=0)result.push(next);prev=next;dp=dn;
 }
 return result;
}
function render(x,y){
 x=Math.max(17,Math.min(443,x));y=Math.max(17,Math.min(203,y));
 for(const [sx,sy] of sites.slice(1)){
   const dx=x-sx,dy=y-sy,len=Math.hypot(dx,dy);
   if(len<15){x=sx+(len?dx/len:1)*15;y=sy+(len?dy/len:0)*15;}
 }
 sites[0]=[x,y];let nearest=0,min=Infinity;
 sites.forEach((a,i)=>{
   let poly=[[0,0],[460,0],[460,220],[0,220]];
   sites.forEach((b,j)=>{if(i!==j)poly=clip(poly,a,b);});
   cells[i].setAttribute('points',poly.map(p=>p.map(n=>n.toFixed(3)).join(',')).join(' '));
   dots[i].setAttribute('transform','translate('+a.join(' ')+')');
   const d=(a[0]-address[0])**2+(a[1]-address[1])**2;
   if(d<min){nearest=i;min=d;}
 });
 const line=byId('delivery');line.setAttribute('x1',address[0]);line.setAttribute('y1',address[1]);line.setAttribute('x2',sites[nearest][0]);line.setAttribute('y2',sites[nearest][1]);
 const name='ABCD'[nearest];if(byId('owner').textContent!==name)byId('owner').textContent=name;
 map.dataset.owner=name;map.dataset.siteA=x.toFixed(2)+','+y.toFixed(2);
}
function preset(x,y){
 cancelAnimationFrame(frame);if(reduce()){render(x,y);return;}
 const a=sites[0].slice(),start=performance.now();
 function tick(now){const u=Math.min(1,(now-start)/450);if(reduce()||u>=1){render(x,y);return;}
   const w=u*u*(3-2*u);render(a[0]+(x-a[0])*w,a[1]+(y-a[1])*w);frame=requestAnimationFrame(tick);}
 frame=requestAnimationFrame(tick);
}
function locate(event){const p=new DOMPoint(event.clientX,event.clientY).matrixTransform(map.getScreenCTM().inverse());render(p.x,p.y);}
map.addEventListener('pointerdown',e=>{if(!e.isPrimary||e.button!==0)return;cancelAnimationFrame(frame);drag=e.pointerId;map.setPointerCapture(drag);locate(e);});
map.addEventListener('pointermove',e=>{if(drag===e.pointerId)locate(e);});
for(const type of ['pointerup','pointercancel','lostpointercapture'])map.addEventListener(type,e=>{if(drag===e.pointerId)drag=null;});
const directions={ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1],ArrowDown:[0,1]};
map.addEventListener('keydown',e=>{const v=directions[e.key];if(!v)return;e.preventDefault();cancelAnimationFrame(frame);render(sites[0][0]+v[0]*6,sites[0][1]+v[1]*6);});
byId('west').onclick=()=>preset(94,68);byId('center').onclick=()=>preset(214,95);render(...sites[0]);
</script></body></html>
```
