PlotDirector/PlotLine/wwwroot/js/maps-geography-engine.js

41 lines
4.2 KiB
JavaScript

/* Spherical azimuthal equidistant projection, north up at the centre.
Refuse large extents: no flat projection preserves all worldwide distances/directions. */
(function(root){
'use strict';
function position(features,states,bounds){
const rad=Math.PI/180,R=6371008.8,wrap=a=>Math.atan2(Math.sin(a),Math.cos(a));
if(![bounds.x,bounds.y,bounds.w,bounds.h].every(Number.isFinite)||bounds.w<=0||bounds.h<=0)throw Error('Map area is unavailable.');
const skipped=[],points=[],output=JSON.parse(JSON.stringify(features));
for(const f of output){
if(!f.locationID)continue;
const state=states.find(s=>s.locationID===f.locationID);
let match=null;try{match=JSON.parse(state?.matchJson||'null');}catch{}
const pendingLabel=state?.status==='Pending'?({'Awaiting hierarchy request':'Not requested','Queued':state.attempts?'Retry scheduled':'Queued','Processing':'Looking up','Waiting configuration':'Lookup disabled'}[state.jobState]||'Pending'):state?.status;
const reason=f.isLocked?'Locked':f.geometryClass!=='Marker'?'Only location markers can be positioned':state?.status!=='Resolved'?(pendingLabel||'Pending'):!match?'Unresolved':null;
if(reason){skipped.push({name:f.name,reason,locationID:f.locationID,message:state?.message,canRequest:reason==='Not requested'});continue;}
if(!Number.isFinite(match.Latitude)||!Number.isFinite(match.Longitude)||Math.abs(match.Latitude)>90||Math.abs(match.Longitude)>180){skipped.push({name:f.name,reason:'Invalid geographical coordinates'});continue;}
points.push({feature:f,lat:match.Latitude*rad,lon:match.Longitude*rad,attribution:match.Attribution});
}
const positioned=points.map(p=>({name:p.feature.name,locationID:p.feature.locationID,featureID:p.feature.featureID,attribution:p.attribution}));
if(new Set(positioned.map(p=>p.locationID)).size<2)return {features:output,positioned,skipped,canApply:false,message:'At least two different resolved, unlocked locations are required. Request unsubmitted lookups or confirm matches in Location Details, then refresh status.'};
const sin=points.reduce((s,p)=>s+Math.sin(p.lon),0),cos=points.reduce((s,p)=>s+Math.cos(p.lon),0);
if(Math.hypot(sin,cos)<1e-9)throw Error('These locations span too much of the world. Use separate regional maps.');
const lon0=Math.atan2(sin,cos),lat0=points.reduce((s,p)=>s+p.lat,0)/points.length;
for(const p of points){
const dl=wrap(p.lon-lon0),cosc=Math.max(-1,Math.min(1,Math.sin(lat0)*Math.sin(p.lat)+Math.cos(lat0)*Math.cos(p.lat)*Math.cos(dl))),c=Math.acos(cosc);
if(c>15*rad)throw Error('These locations cover too large an area for reliable local positioning. Use separate regional maps (within about 1,650 km of their centre).');
const k=c<1e-10?1:c/Math.sin(c);
p.x=R*k*Math.cos(p.lat)*Math.sin(dl);
p.y=-R*k*(Math.cos(lat0)*Math.sin(p.lat)-Math.sin(lat0)*Math.cos(p.lat)*Math.cos(dl));
}
const xs=points.map(p=>p.x),ys=points.map(p=>p.y),left=Math.min(...xs),right=Math.max(...xs),top=Math.min(...ys),bottom=Math.max(...ys);
const pad=Math.min(80,bounds.w*.12,bounds.h*.12),w=bounds.w-2*pad,h=bounds.h-2*pad;
const scale=Math.min(right-left>1e-6?w/(right-left):Infinity,bottom-top>1e-6?h/(bottom-top):Infinity);
for(const p of points){p.feature.x=bounds.x+bounds.w/2+(p.x-(left+right)/2)*(Number.isFinite(scale)?scale:0);p.feature.y=bounds.y+bounds.h/2+(p.y-(top+bottom)/2)*(Number.isFinite(scale)?scale:0);p.feature.isPlaced=true;}
const changes=points.filter(p=>{const before=features.find(f=>f.featureID===p.feature.featureID);return Math.abs(before.x-p.feature.x)>1e-6||Math.abs(before.y-p.feature.y)>1e-6||!before.isPlaced;}).length;
return {features:output,positioned,skipped,canApply:changes>0,message:changes?`${changes} location markers will move. Other map objects retain their positions.`:'These places are already in the proposed positions. No changes are needed.'};
}
root.PlotDirectorGeography={position};
if(typeof module!=='undefined')module.exports={position};
})(typeof window!=='undefined'?window:globalThis);