Replace Google Maps with Esri (ArcGIS) basemaps

Swaps the map provider behind the existing provider-neutral JobMapProps
interface: EsriJobMap.tsx (ArcGIS Maps SDK) replaces GoogleJobMap.tsx,
loaded via esri-loader's CDN script rather than bundled through webpack —
next dev's inline source-mapping of a library this size was OOM-killing
the whole host on first compile. Also fixes a bug in the fit-bounds camera
call: view.goTo() needs real Graphic/Geometry instances, not plain point
literals, so the map was never zooming to the plotted points.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
ulhub
2026-08-16 21:06:05 +00:00
parent 5de7b4d7a2
commit 9eefe50401
8 changed files with 2231 additions and 314 deletions

View File

@@ -1,10 +1,9 @@
import dynamic from 'next/dynamic';
import type { JobMapProps } from './types';
// Provider dispatcher. Google is the only implementation for now; an Esri
// implementation would be selected here (e.g. via NEXT_PUBLIC_MAP_PROVIDER).
const GoogleJobMap = dynamic(() => import('./google/GoogleJobMap'), { ssr: false });
// Provider dispatcher. Esri (ArcGIS) is the only implementation.
const EsriJobMap = dynamic(() => import('./esri/EsriJobMap'), { ssr: false });
export default function JobMap(props: JobMapProps) {
return <GoogleJobMap {...props} />;
return <EsriJobMap {...props} />;
}

View File

@@ -0,0 +1,291 @@
import { useEffect, useRef, useState } from 'react';
import { loadModules, setDefaultOptions } from 'esri-loader';
import type EsriConfigModule from '@arcgis/core/config.js';
import type CircleConstructor from '@arcgis/core/geometry/Circle.js';
import type GraphicConstructor from '@arcgis/core/Graphic.js';
import type GraphicsLayerConstructor from '@arcgis/core/layers/GraphicsLayer.js';
import type EsriMapConstructor from '@arcgis/core/Map.js';
import type MapViewConstructor from '@arcgis/core/views/MapView.js';
import { JobMapProps, LiveStatus, liveStatusToMapPoint, MapPoint, pointDetailRows, UTILITY_COLORS } from '../types';
const API_KEY = process.env.NEXT_PUBLIC_ARCGIS_API_KEY || '';
const LIVE_COLOR = '#1a73e8';
const DEFAULT_CENTER: [number, number] = [-98.35, 39.5]; // continental US, [lng, lat]
const DEFAULT_ZOOM = 4;
// Keep in sync with @arcgis/core's version in package.json (major.minor —
// js.arcgis.com is keyed by major.minor only, the full patch version 404s).
const CDN_VERSION = '4.34';
// Loaded via Esri's CDN (esri-loader), not bundled through webpack: the SDK
// is large enough that having Next's dev-mode compiler process it — full
// inline source maps for every vendored module — pegged CPU/memory badly
// enough to OOM the whole host on a first compile. The browser parses/runs
// the CDN script directly, so the dev server never touches it. @arcgis/core
// stays a devDependency purely for its .d.ts types (import type below is
// fully erased, never bundled or evaluated at runtime).
setDefaultOptions({ version: CDN_VERSION, css: true });
interface EsriModules {
EsriMap: typeof EsriMapConstructor;
MapView: typeof MapViewConstructor;
Graphic: typeof GraphicConstructor;
GraphicsLayer: typeof GraphicsLayerConstructor;
Circle: typeof CircleConstructor;
esriConfig: typeof EsriConfigModule;
}
let modulesPromise: Promise<EsriModules> | null = null;
// Cached at module scope (not per-mount) so navigating between pages that
// each render a map doesn't re-trigger the CDN load — esri-loader caches
// the underlying script tag globally too, but this also skips re-running
// the loadModules() round trip on every mount.
function loadEsriModules(): Promise<EsriModules> {
if (!modulesPromise) {
modulesPromise = loadModules([
'esri/Map',
'esri/views/MapView',
'esri/Graphic',
'esri/layers/GraphicsLayer',
'esri/geometry/Circle',
'esri/config',
]).then(([EsriMap, MapView, Graphic, GraphicsLayer, Circle, esriConfig]: any[]) => {
esriConfig.apiKey = API_KEY;
return { EsriMap, MapView, Graphic, GraphicsLayer, Circle, esriConfig } as EsriModules;
});
}
return modulesPromise;
}
function colorFor(utilityType: string): string {
return UTILITY_COLORS[utilityType] ?? UTILITY_COLORS.UNKNOWN;
}
function orderKey(p: MapPoint): number {
return p.sequence ?? new Date(p.recordedAt).getTime();
}
// Identifies whether the set of points (including each one's own position)
// has actually changed, so a moving point re-fits bounds even when the
// count doesn't change (e.g. a device's single "current location" point).
function pointsSignature(points: MapPoint[]): string {
return points.map((p) => `${p.id}:${p.lat.toFixed(7)}:${p.lng.toFixed(7)}`).join('|');
}
function popupHtml(point: MapPoint): string {
const rows = pointDetailRows(point)
.map(
([label, value]) =>
`<tr><td style="color:#666;padding-right:0.75rem;white-space:nowrap;">${label}</td><td style="font-weight:600;">${value}</td></tr>`,
)
.join('');
return `<table style="border-collapse:collapse;font-family:sans-serif;">${rows}</table>`;
}
// Esri opens/closes/dismisses-on-outside-click popups natively via each
// graphic's popupTemplate — no hand-rolled "selected point" state needed.
function pointGraphic(mods: EsriModules, point: MapPoint, color: string) {
return new mods.Graphic({
geometry: { type: 'point', longitude: point.lng, latitude: point.lat },
symbol: {
type: 'simple-marker',
style: 'circle',
color,
size: 10,
outline: { color: '#ffffff', width: 1.5 },
},
popupTemplate: {
title: `${point.utilityType} · ${point.fixType}`,
content: popupHtml(point),
},
} as ConstructorParameters<typeof GraphicConstructor>[0]);
}
function lineGraphic(mods: EsriModules, points: MapPoint[], color: string) {
return new mods.Graphic({
geometry: {
type: 'polyline',
paths: [points.map((p) => [p.lng, p.lat])],
},
symbol: {
type: 'simple-line',
color,
width: 3,
opacity: 0.8,
},
} as ConstructorParameters<typeof GraphicConstructor>[0]);
}
function liveMarkerGraphics(mods: EsriModules, status: LiveStatus) {
const position = { type: 'point' as const, longitude: status.lng, latitude: status.lat };
const marker = new mods.Graphic({
geometry: position,
symbol: {
type: 'simple-marker',
style: 'circle',
color: LIVE_COLOR,
size: 16,
outline: { color: '#ffffff', width: 2 },
},
popupTemplate: {
title: `Live · ${status.serial}`,
content: popupHtml(liveStatusToMapPoint(status)),
},
} as ConstructorParameters<typeof GraphicConstructor>[0]);
const halo = new mods.Graphic({
geometry: new mods.Circle({
center: [status.lng, status.lat],
radius: status.hAccuracy ?? 5,
radiusUnit: 'meters',
geodesic: true,
}),
symbol: {
type: 'simple-fill',
color: [...hexToRgb(LIVE_COLOR), 0.15],
outline: { color: [...hexToRgb(LIVE_COLOR), 0.3], width: 1 },
},
} as ConstructorParameters<typeof GraphicConstructor>[0]);
return [halo, marker];
}
function hexToRgb(hex: string): [number, number, number] {
const n = parseInt(hex.slice(1), 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
export default function EsriJobMap({ points, liveStatus = null, fitBounds = true, heightPx = 480 }: JobMapProps) {
const containerRef = useRef<HTMLDivElement>(null);
const viewRef = useRef<InstanceType<typeof MapViewConstructor> | null>(null);
const pointsLayerRef = useRef<InstanceType<typeof GraphicsLayerConstructor> | null>(null);
const liveLayerRef = useRef<InstanceType<typeof GraphicsLayerConstructor> | null>(null);
const modsRef = useRef<EsriModules | null>(null);
const fittedSignatureRef = useRef('');
const [ready, setReady] = useState(false);
useEffect(() => {
if (!containerRef.current || !API_KEY) {
return;
}
let cancelled = false;
let view: InstanceType<typeof MapViewConstructor> | undefined;
loadEsriModules().then((mods) => {
if (cancelled || !containerRef.current) {
return;
}
const pointsLayer = new mods.GraphicsLayer();
const liveLayer = new mods.GraphicsLayer();
const map = new mods.EsriMap({ basemap: 'hybrid', layers: [pointsLayer, liveLayer] });
view = new mods.MapView({
container: containerRef.current,
map,
center: DEFAULT_CENTER,
zoom: DEFAULT_ZOOM,
});
modsRef.current = mods;
pointsLayerRef.current = pointsLayer;
liveLayerRef.current = liveLayer;
viewRef.current = view;
setReady(true);
});
return () => {
cancelled = true;
view?.destroy();
viewRef.current = null;
pointsLayerRef.current = null;
liveLayerRef.current = null;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
const view = viewRef.current;
const layer = pointsLayerRef.current;
const mods = modsRef.current;
if (!view || !layer || !mods) {
return;
}
layer.removeAll();
const byUtility = new Map<string, MapPoint[]>();
for (const p of points) {
const group = byUtility.get(p.utilityType) ?? [];
group.push(p);
byUtility.set(p.utilityType, group);
}
for (const [utility, group] of byUtility) {
const sorted = [...group].sort((a, b) => orderKey(a) - orderKey(b));
const color = colorFor(utility);
layer.add(lineGraphic(mods, sorted, color));
for (const p of sorted) {
layer.add(pointGraphic(mods, p, color));
}
}
const signature = pointsSignature(points);
if (fitBounds && signature !== fittedSignatureRef.current && points.length > 0) {
fittedSignatureRef.current = signature;
view.when(() => {
const target =
points.length === 1 ? { center: [points[0].lng, points[0].lat] } : layer.graphics.toArray();
view.goTo(target).catch((err: Error) => {
if (err.name !== 'view:goTo-aborted') {
console.error('EsriJobMap: goTo failed', err);
}
});
});
}
}, [points, fitBounds, ready]);
useEffect(() => {
const view = viewRef.current;
const layer = liveLayerRef.current;
const mods = modsRef.current;
if (!view || !layer || !mods) {
return;
}
layer.removeAll();
if (!liveStatus) {
return;
}
liveMarkerGraphics(mods, liveStatus).forEach((g) => layer.add(g));
view.when(() => {
view.goTo({ center: [liveStatus.lng, liveStatus.lat] }).catch((err: Error) => {
if (err.name !== 'view:goTo-aborted') {
console.error('EsriJobMap: goTo failed', err);
}
});
});
}, [liveStatus, ready]);
if (!API_KEY) {
return (
<div
style={{
height: heightPx,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
border: '1px dashed #999',
borderRadius: 8,
color: '#666',
}}
>
Set NEXT_PUBLIC_ARCGIS_API_KEY in .env to enable the map.
</div>
);
}
return (
<div style={{ height: heightPx, borderRadius: 8, overflow: 'hidden' }}>
<div ref={containerRef} style={{ height: '100%' }} />
</div>
);
}

View File

@@ -1,264 +0,0 @@
/// <reference types="google.maps" />
import { APIProvider, InfoWindow, Map as GoogleMap, useMap } from '@vis.gl/react-google-maps';
import { useEffect, useRef, useState } from 'react';
import { JobMapProps, LiveStatus, liveStatusToMapPoint, MapPoint, pointDetailRows, UTILITY_COLORS } from '../types';
const API_KEY = process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY || '';
const LIVE_COLOR = '#1a73e8';
const DEFAULT_CENTER = { lat: 39.5, lng: -98.35 }; // continental US
const DEFAULT_ZOOM = 4;
function colorFor(utilityType: string): string {
return UTILITY_COLORS[utilityType] ?? UTILITY_COLORS.UNKNOWN;
}
function orderKey(p: MapPoint): number {
return p.sequence ?? new Date(p.recordedAt).getTime();
}
// Identifies whether the set of points (including each one's own position)
// has actually changed, so a moving point re-fits bounds even when the
// count doesn't change (e.g. a device's single "current location" point).
function pointsSignature(points: MapPoint[]): string {
return points.map((p) => `${p.id}:${p.lat.toFixed(7)}:${p.lng.toFixed(7)}`).join('|');
}
// Draws points as colored circles plus one polyline per utility run.
// Imperative overlays (google.maps.Marker/Polyline) are used because
// @vis.gl/react-google-maps has no polyline component.
function PointsLayer({
points,
fitBounds,
onSelect,
}: {
points: MapPoint[];
fitBounds: boolean;
onSelect: (point: MapPoint) => void;
}) {
const map = useMap();
const overlaysRef = useRef<{ setMap: (m: google.maps.Map | null) => void }[]>([]);
const fittedSignatureRef = useRef('');
const onSelectRef = useRef(onSelect);
onSelectRef.current = onSelect;
useEffect(() => {
if (!map) {
return;
}
overlaysRef.current.forEach((o) => o.setMap(null));
overlaysRef.current = [];
if (points.length === 0) {
return;
}
const byUtility = new Map<string, MapPoint[]>();
for (const p of points) {
const group = byUtility.get(p.utilityType) ?? [];
group.push(p);
byUtility.set(p.utilityType, group);
}
for (const [utility, group] of byUtility) {
const sorted = [...group].sort((a, b) => orderKey(a) - orderKey(b));
const color = colorFor(utility);
const line = new google.maps.Polyline({
path: sorted.map((p) => ({ lat: p.lat, lng: p.lng })),
strokeColor: color,
strokeOpacity: 0.8,
strokeWeight: 3,
map,
});
overlaysRef.current.push(line);
for (const p of sorted) {
const marker = new google.maps.Marker({
position: { lat: p.lat, lng: p.lng },
map,
cursor: 'pointer',
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 5,
fillColor: color,
fillOpacity: 1,
strokeColor: '#ffffff',
strokeWeight: 1.5,
},
});
marker.addListener('click', () => onSelectRef.current(p));
overlaysRef.current.push(marker);
}
}
const signature = pointsSignature(points);
if (fitBounds && signature !== fittedSignatureRef.current) {
fittedSignatureRef.current = signature;
if (points.length === 1) {
// A single (often moving) point has no useful bounds to fit — just
// recenter on it, preserving the current zoom.
map.panTo({ lat: points[0].lat, lng: points[0].lng });
} else {
const bounds = new google.maps.LatLngBounds();
points.forEach((p) => bounds.extend({ lat: p.lat, lng: p.lng }));
map.fitBounds(bounds, 48);
}
}
}, [map, points, fitBounds]);
return null;
}
// Renders the transmitter's current position as a "blue dot" (marker + soft
// accuracy halo), updated in place as new status messages arrive.
function LiveMarker({ status, onSelect }: { status: LiveStatus | null; onSelect: (point: MapPoint) => void }) {
const map = useMap();
const markerRef = useRef<google.maps.Marker | null>(null);
const haloRef = useRef<google.maps.Circle | null>(null);
const statusRef = useRef(status);
statusRef.current = status;
const onSelectRef = useRef(onSelect);
onSelectRef.current = onSelect;
useEffect(() => {
if (!map) {
return;
}
if (!status) {
markerRef.current?.setMap(null);
haloRef.current?.setMap(null);
markerRef.current = null;
haloRef.current = null;
return;
}
const position = { lat: status.lat, lng: status.lng };
if (!markerRef.current) {
markerRef.current = new google.maps.Marker({
map,
position,
zIndex: 999,
cursor: 'pointer',
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 8,
fillColor: LIVE_COLOR,
fillOpacity: 1,
strokeColor: '#ffffff',
strokeWeight: 2,
},
});
markerRef.current.addListener('click', () => {
if (statusRef.current) {
onSelectRef.current(liveStatusToMapPoint(statusRef.current));
}
});
haloRef.current = new google.maps.Circle({
map,
center: position,
radius: status.hAccuracy ?? 5,
fillColor: LIVE_COLOR,
fillOpacity: 0.15,
strokeColor: LIVE_COLOR,
strokeOpacity: 0.3,
strokeWeight: 1,
clickable: false,
});
} else {
markerRef.current.setPosition(position);
haloRef.current?.setCenter(position);
haloRef.current?.setRadius(status.hAccuracy ?? 5);
}
// Follow the transmitter as its position updates.
map.panTo(position);
}, [map, status]);
useEffect(
() => () => {
markerRef.current?.setMap(null);
haloRef.current?.setMap(null);
},
[],
);
return null;
}
function PointDetails({ point, onClose }: { point: MapPoint; onClose: () => void }) {
return (
<InfoWindow position={{ lat: point.lat, lng: point.lng }} onCloseClick={onClose}>
<div style={{ fontFamily: 'sans-serif', minWidth: 200 }}>
<table style={{ borderCollapse: 'collapse' }}>
<tbody>
{pointDetailRows(point).map(([label, value]) => (
<tr key={label}>
<td style={{ color: '#666', paddingRight: '0.75rem', whiteSpace: 'nowrap' }}>{label}</td>
<td style={{ fontWeight: 600 }}>{value}</td>
</tr>
))}
</tbody>
</table>
</div>
</InfoWindow>
);
}
export default function GoogleJobMap({ points, liveStatus = null, fitBounds = true, heightPx = 480 }: JobMapProps) {
const [selected, setSelected] = useState<MapPoint | null>(null);
if (!API_KEY) {
return (
<div
style={{
height: heightPx,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
border: '1px dashed #999',
borderRadius: 8,
color: '#666',
}}
>
Set NEXT_PUBLIC_GOOGLE_MAPS_API_KEY in .env to enable the map.
</div>
);
}
// A point can be re-fetched (new object identity) between renders; keep the
// InfoWindow anchored to the latest copy of the same point by id. The
// liveStatus marker's "point" is synthesized fresh from liveStatus each
// time — but only for the id it actually owns. Other callers (e.g. the
// devices page's single current-position point) may also use a "live-"
// prefixed id without ever passing a liveStatus prop, so that id alone
// can't be used to decide which source to read from.
const selectedCurrent = (() => {
if (!selected) {
return null;
}
if (liveStatus && selected.id === `live-${liveStatus.deviceId}`) {
return liveStatusToMapPoint(liveStatus);
}
return points.find((p) => p.id === selected.id) ?? selected;
})();
return (
<div style={{ height: heightPx, borderRadius: 8, overflow: 'hidden' }}>
<APIProvider apiKey={API_KEY}>
<GoogleMap
defaultCenter={points[0] ? { lat: points[0].lat, lng: points[0].lng } : DEFAULT_CENTER}
defaultZoom={points[0] ? 18 : DEFAULT_ZOOM}
mapTypeId="hybrid"
gestureHandling="greedy"
onClick={() => setSelected(null)}
>
<PointsLayer points={points} fitBounds={fitBounds} onSelect={setSelected} />
<LiveMarker status={liveStatus} onSelect={setSelected} />
{selectedCurrent && <PointDetails point={selectedCurrent} onClose={() => setSelected(null)} />}
</GoogleMap>
</APIProvider>
</div>
);
}

View File

@@ -1,6 +1,5 @@
// Provider-neutral mapping types. Pages import only these and <JobMap>;
// swapping Google for Esri later means adding a new provider implementation
// of JobMapProps under components/map/esri/ and switching the dispatcher.
// Provider-neutral mapping types. Pages import only these and <JobMap>; the
// active provider implementation lives under components/map/esri/.
export interface MapPoint {
id: string;

1953
web/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -9,13 +9,13 @@
"lint": "next lint"
},
"dependencies": {
"@vis.gl/react-google-maps": "^1.4.0",
"esri-loader": "^3.7.0",
"next": "14.2.5",
"react": "18.3.0",
"react-dom": "18.3.0"
},
"devDependencies": {
"@types/google.maps": "^3.58.1",
"@arcgis/core": "^4.31.0",
"@types/node": "^20.11.0",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",