|
|
|
@@ -0,0 +1,71 @@
|
|
|
|
|
import {Map as LibreMap,Marker,NavigationControl,ScaleControl,AttributionControl,setWorkerUrl,setWorkerCount} from 'maplibre-gl'
|
|
|
|
|
import workerUrl from 'maplibre-gl/dist/maplibre-gl-worker.mjs?worker&url'
|
|
|
|
|
import 'maplibre-gl/dist/maplibre-gl.css'
|
|
|
|
|
import {layers,namedFlavor} from '@protomaps/basemaps'
|
|
|
|
|
import {visiblePeople,accuracyCircle,regionAt,trackCollection} from './model.mjs'
|
|
|
|
|
import './map.css'
|
|
|
|
|
setWorkerUrl(workerUrl)
|
|
|
|
|
setWorkerCount(2)
|
|
|
|
|
|
|
|
|
|
export function createFamilyMap(container,{onSelect=()=>{},onStatus=()=>{},night=false}={}){
|
|
|
|
|
let map,disposed=false,people=[],track=[],selected='',markers=new globalThis.Map(),initialFit=false,available=false,theme=night,catalog={regions:[]},expiry,poll,resize,styleKey='',loadingCatalog=false
|
|
|
|
|
const abort=new AbortController()
|
|
|
|
|
const origin=location.origin
|
|
|
|
|
const chosen=(lon,lat)=>regionAt(catalog.regions||[],lon,lat)
|
|
|
|
|
const style=()=>{
|
|
|
|
|
const flavor={...namedFlavor(theme?'dark':'light'),...(theme?{earth:'#192725',background:'#15211f',water:'#173747',minor_a:'#33483e',minor_b:'#33483e',major:'#496354',highway:'#6f7160',roads_label_minor:'#b1c3b9',roads_label_major:'#c8d8ce',subplace_label:'#adbbb3',city_label:'#d0ddcf',state_label:'#d0ddcf',country_label:'#d0ddcf',roads_label_minor_halo:'#192725',roads_label_major_halo:'#192725',subplace_label_halo:'#192725',city_label_halo:'#192725'}:{earth:'#f3f0e7',water:'#bad8e6',park_a:'#d7e4cf'})}
|
|
|
|
|
const center=map?.getCenter()||{lng:117.8,lat:36.6},zoom=map?.getZoom()||6
|
|
|
|
|
let region=chosen(center.lng,center.lat)
|
|
|
|
|
if(zoom<=6)region=catalog.regions.find(r=>r.id==='world')||region
|
|
|
|
|
else if(zoom<9&®ion?.id.startsWith('cn-'))region=catalog.regions.find(r=>r.id==='china')||region
|
|
|
|
|
region=region||catalog.regions[0];styleKey=region.id+theme+region.revision
|
|
|
|
|
return {version:8,glyphs:`${origin}/maps/assets/fonts/{fontstack}/{range}.pbf`,sprite:`${origin}/maps/assets/sprites/v4/${theme?'dark':'light'}`,
|
|
|
|
|
sources:{base:{type:'vector',tiles:[`${origin}/maps/tiles/${region.id}/{z}/{x}/{y}.mvt`],minzoom:0,maxzoom:region.maxZoom,bounds:region.bounds}},layers:layers('base',flavor,{lang:'zh'})}
|
|
|
|
|
}
|
|
|
|
|
const maximum=r=>r?.id.startsWith('cn-')?18:r?.id==='china'?11:6
|
|
|
|
|
function report(){if(!map||!available)return;const c=map.getCenter(),r=chosen(c.lng,c.lat);onStatus(r?.id.startsWith('cn-')?`${r.name}详细地图 · 道路与建筑`:`${r?.name||'概览'} · 进入省份后后台准备详细地图,完成后自动可用`)}
|
|
|
|
|
function refreshStyle(){if(!map||!available||disposed)return;const old=styleKey,next=style();if(old!==styleKey){map.setStyle(next);map.once('style.load',paint)}const c=map.getCenter(),max=maximum(chosen(c.lng,c.lat));if(map.getMaxZoom()!==max)map.setMaxZoom(max);report()}
|
|
|
|
|
function clearMarkers(){for(const m of markers.values())m.remove();markers.clear()}
|
|
|
|
|
function paint(){
|
|
|
|
|
if(!map||disposed)return
|
|
|
|
|
const valid=visiblePeople(people),ids=new Set(valid.map(p=>p.id))
|
|
|
|
|
for(const [id,marker] of markers)if(!ids.has(id)){marker.remove();markers.delete(id)}
|
|
|
|
|
for(const p of valid){
|
|
|
|
|
if(markers.has(p.id)){const marker=markers.get(p.id),el=marker.getElement();marker.setLngLat([p.position.longitude,p.position.latitude]);el.classList.toggle('selected',p.id===selected);el.firstChild.textContent=String(p.name||'家人').slice(0,1);el.lastChild.textContent=String(p.name||'家人');el.setAttribute('aria-label',`查看${p.name||'家人'}的位置`);continue}
|
|
|
|
|
const el=document.createElement('button');el.type='button';el.className='family-map-pin'+(p.id===selected?' selected':'')
|
|
|
|
|
el.setAttribute('aria-label',`查看${p.name||'家人'}的位置`)
|
|
|
|
|
const avatar=document.createElement('span');avatar.textContent=String(p.name||'家人').slice(0,1)
|
|
|
|
|
const label=document.createElement('b');label.textContent=String(p.name||'家人');el.append(avatar,label)
|
|
|
|
|
el.onclick=()=>{selected=p.id;onSelect(p.id);focus(p.id)}
|
|
|
|
|
markers.set(p.id,new Marker({element:el,anchor:'bottom'}).setLngLat([p.position.longitude,p.position.latitude]).addTo(map))
|
|
|
|
|
}
|
|
|
|
|
if(map.isStyleLoaded()){
|
|
|
|
|
const data={type:'FeatureCollection',features:valid.filter(p=>!selected||p.id===selected).map(accuracyCircle)}
|
|
|
|
|
if(map.getSource('family-accuracy'))map.getSource('family-accuracy').setData(data)
|
|
|
|
|
else {map.addSource('family-accuracy',{type:'geojson',data});map.addLayer({id:'family-accuracy-fill',type:'fill',source:'family-accuracy',paint:{'fill-color':'#238e79','fill-opacity':.12}});map.addLayer({id:'family-accuracy-line',type:'line',source:'family-accuracy',paint:{'line-color':'#238e79','line-width':1,'line-opacity':.6}})}
|
|
|
|
|
const history=trackCollection(track)
|
|
|
|
|
if(map.getSource('family-track'))map.getSource('family-track').setData(history)
|
|
|
|
|
else{map.addSource('family-track',{type:'geojson',data:history});map.addLayer({id:'family-track-line',type:'line',source:'family-track',filter:['==',['geometry-type'],'LineString'],paint:{'line-color':'#e49a26','line-width':4,'line-opacity':.85}});map.addLayer({id:'family-track-points',type:'circle',source:'family-track',filter:['==',['geometry-type'],'Point'],paint:{'circle-radius':['case',['get','edge'],6,3],'circle-color':'#217d6b','circle-stroke-color':'#fff','circle-stroke-width':1}})}
|
|
|
|
|
}
|
|
|
|
|
if(!initialFit&&valid.length){initialFit=true;fit()}
|
|
|
|
|
}
|
|
|
|
|
function fit(){if(!map)return;if(track.length){const pts=trackCollection(track).features.filter(f=>f.geometry.type==='Point').map(f=>f.geometry.coordinates);if(pts.length){map.setMaxZoom(18);map.fitBounds([[Math.min(...pts.map(p=>p[0])),Math.min(...pts.map(p=>p[1]))],[Math.max(...pts.map(p=>p[0])),Math.max(...pts.map(p=>p[1]))]],{padding:55,maxZoom:14,duration:400});return}}const valid=visiblePeople(people);if(valid.length===1){focus(valid[0].id);return}if(!valid.length){map.easeTo({center:[105,35],zoom:4,duration:400});return}
|
|
|
|
|
const xs=valid.map(p=>p.position.longitude),ys=valid.map(p=>p.position.latitude)
|
|
|
|
|
map.setMaxZoom(18)
|
|
|
|
|
map.fitBounds([[Math.min(...xs),Math.min(...ys)],[Math.max(...xs),Math.max(...ys)]],{padding:65,maxZoom:13,duration:500})
|
|
|
|
|
}
|
|
|
|
|
function focus(id){const p=visiblePeople(people).find(p=>p.id===id);if(!map||!p)return;selected=id;const pos=p.position,max=maximum(chosen(pos.longitude,pos.latitude));map.setMaxZoom(max);map.easeTo({center:[pos.longitude,pos.latitude],zoom:Math.min(14,max),duration:450});paint()}
|
|
|
|
|
const controller={setItems(items){people=Array.isArray(items)?items:[];if(!people.length){initialFit=false;selected=''}paint()},setTrack(points){track=Array.isArray(points)?points:[];paint();if(track.length)fit()},focus,fit,setNight(value){if(theme===value)return;theme=value;refreshStyle()},resize(){map?.resize()},destroy(){disposed=true;abort.abort();clearInterval(expiry);clearInterval(poll);resize?.disconnect();clearMarkers();map?.remove();map=null;people=[];track=[]},ready:Promise.resolve()}
|
|
|
|
|
controller.ready=(async()=>{try{
|
|
|
|
|
const timeout=setTimeout(()=>abort.abort(),10000);let response;try{response=await fetch('/maps/catalog.json',{signal:abort.signal})}finally{clearTimeout(timeout)}if(!response.ok)throw Error();catalog=await response.json();if(disposed)return;if(!catalog.regions?.length){onStatus('地图数据尚未就绪,家人位置可查看列表');return}
|
|
|
|
|
map=new LibreMap({container,style:style(),center:[117.8,36.6],zoom:6,maxZoom:18,minZoom:1,attributionControl:false,renderWorldCopies:false,dragRotate:false,touchPitch:false,localIdeographFontFamily:'sans-serif'})
|
|
|
|
|
map.addControl(new NavigationControl({showCompass:false}),'top-right');map.addControl(new ScaleControl({unit:'metric'}),'bottom-left')
|
|
|
|
|
map.addControl(new AttributionControl({compact:true,customAttribution:'<a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noreferrer">© OpenStreetMap</a> · <a href="https://protomaps.com" target="_blank" rel="noreferrer">Protomaps</a>'}),'bottom-right')
|
|
|
|
|
map.on('load',()=>{available=true;paint();if(track.length)fit();report()})
|
|
|
|
|
map.on('error',()=>onStatus('部分地图未能加载,可重试;家人信息仍可查看列表'))
|
|
|
|
|
map.on('moveend',refreshStyle)
|
|
|
|
|
resize=new ResizeObserver(()=>map?.resize());resize.observe(container);expiry=setInterval(paint,15000)
|
|
|
|
|
poll=setInterval(async()=>{if(disposed||loadingCatalog)return;loadingCatalog=true;try{const r=await fetch('/maps/catalog.json',{signal:abort.signal,cache:'no-store'});if(r.ok){const next=await r.json();if(next.regions?.length&&next.revision!==catalog.revision){catalog=next;refreshStyle()}}}catch{}finally{loadingCatalog=false}},20000)
|
|
|
|
|
}catch{if(!disposed)onStatus('此设备暂时无法绘制地图,请查看家人列表或更新系统 WebView')}})()
|
|
|
|
|
return controller
|
|
|
|
|
}
|