Skip to content

Commit d68658f

Browse files
committed
Add MapBox utilities.
1 parent b18b4b5 commit d68658f

File tree

1 file changed

+159
-0
lines changed

1 file changed

+159
-0
lines changed

src/mapbox.ts

Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
export interface MapBoxContextItem {
2+
id: string;
3+
// eslint-disable-next-line @typescript-eslint/naming-convention
4+
mapbox_id: string;
5+
text: string;
6+
wikidata: string;
7+
// eslint-disable-next-line @typescript-eslint/naming-convention
8+
short_code?: string;
9+
}
10+
11+
// The field names here come from MapBox
12+
export interface MapBoxFeature {
13+
// eslint-disable-next-line @typescript-eslint/naming-convention
14+
place_type: string[];
15+
// eslint-disable-next-line @typescript-eslint/naming-convention
16+
place_name: string;
17+
text?: string;
18+
// eslint-disable-next-line @typescript-eslint/naming-convention
19+
properties: { short_code: string; };
20+
center: [number, number];
21+
context: MapBoxContextItem[];
22+
}
23+
24+
export interface MapBoxFeatureCollection {
25+
type: "FeatureCollection";
26+
features: MapBoxFeature[];
27+
}
28+
29+
export type MapBoxFeatureType = "country" | "region" | "postcode" | "district" | "place" | "locality" | "neighborhood" | "street" | "address";
30+
export type MapBoxWorldviewType = "ar" | "cn" | "in" | "jp" | "ma" | "ru" | "tr" | "us";
31+
32+
// For countries, use the ISO 3166-1 alpha-2 country codes:
33+
// https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
34+
interface BaseMapBoxGeocodingOptions {
35+
permanent?: boolean;
36+
language?: string;
37+
limit?: number;
38+
countries?: string[];
39+
types?: MapBoxFeatureType[];
40+
41+
// MapBox API access token
42+
// eslint-disable-next-line @typescript-eslint/naming-convention
43+
access_token: string;
44+
}
45+
46+
interface MapBoxForwardGeocodingOptions extends BaseMapBoxGeocodingOptions {
47+
autocomplete?: boolean;
48+
bbox?: number;
49+
format?: "geojson" | "v5";
50+
proximity?: string;
51+
}
52+
53+
interface MapBoxReverseGeocodingOptions extends BaseMapBoxGeocodingOptions {
54+
worldview?: MapBoxWorldviewType[];
55+
}
56+
57+
interface MapBoxAdjustedGeocodingParams {
58+
countries?: string;
59+
types?: string;
60+
}
61+
62+
type MapBoxQueryOptions<T extends BaseMapBoxGeocodingOptions> = {
63+
[K in keyof Omit<T, "countries" | "types">]: T[K];
64+
} & MapBoxAdjustedGeocodingParams;
65+
66+
const RELEVANT_FEATURE_TYPES = ["postcode", "place", "region", "country"];
67+
const NA_COUNTRIES = ["United States", "Canada", "Mexico"];
68+
const NA_ABBREVIATIONS = ["US-", "CA-", "MX-"];
69+
70+
export function findBestFeature(collection: MapBoxFeatureCollection): MapBoxFeature | null {
71+
const relevantFeatures = collection.features.filter(feature => RELEVANT_FEATURE_TYPES.some(type => feature.place_type.includes(type)));
72+
const placeFeature = relevantFeatures.find(feature => feature.place_type.includes("place")) ?? (relevantFeatures.find(feature => feature.place_type.includes("postcode")) ?? undefined);
73+
if (placeFeature !== undefined) {
74+
return placeFeature;
75+
}
76+
const regionFeature = relevantFeatures.find(feature => feature.place_type.includes("region"));
77+
if (regionFeature !== undefined) {
78+
return regionFeature;
79+
}
80+
const countryFeature = relevantFeatures.find(feature => feature.place_type.includes("country"));
81+
if (countryFeature !== undefined) {
82+
return countryFeature;
83+
}
84+
return null;
85+
}
86+
87+
export function textForMapboxFeature(feature: MapBoxFeature): string {
88+
const pieces: string[] = [];
89+
if (feature.text) {
90+
pieces.push(feature.text);
91+
}
92+
feature.context.forEach(item => {
93+
const itemType = item.id.split(".")[0];
94+
if (!RELEVANT_FEATURE_TYPES.includes(itemType)) {
95+
return;
96+
}
97+
let text = null as string | null;
98+
const shortCode = item.short_code;
99+
if (itemType === "region" && shortCode != null) {
100+
if (NA_ABBREVIATIONS.some(abbr => shortCode.startsWith(abbr))) {
101+
text = shortCode.substring(3);
102+
}
103+
} else if (itemType === "country") {
104+
const itemText = item.text;
105+
if (!NA_COUNTRIES.includes(itemText)) {
106+
text = itemText;
107+
}
108+
}
109+
if (text !== null) {
110+
pieces.push(text);
111+
}
112+
});
113+
return pieces.join(", ");
114+
}
115+
116+
export function textForMapboxResults(results: MapBoxFeatureCollection): string {
117+
const feature = findBestFeature(results);
118+
return feature !== null ? textForMapboxFeature(feature) : "";
119+
}
120+
121+
function convertOptionsToQueryParams<T extends BaseMapBoxGeocodingOptions>(options: T): MapBoxQueryOptions<T> {
122+
const { types, countries, ...params } = options;
123+
const queryParams = params as MapBoxQueryOptions<T>;
124+
queryParams.types = (types ?? ["place", "postcode"]).join(",");
125+
if (countries) {
126+
queryParams.countries = countries.join(",");
127+
}
128+
return queryParams;
129+
}
130+
131+
function searchParams(options: MapBoxForwardGeocodingOptions | MapBoxReverseGeocodingOptions): URLSearchParams {
132+
const search = new URLSearchParams();
133+
const queryParams = convertOptionsToQueryParams(options);
134+
Object.entries(queryParams).forEach(([key, value]) => search.set(key, value.toString()));
135+
return search;
136+
}
137+
138+
export async function textForLocation(longitudeDeg: number, latitudeDeg: number, options: MapBoxReverseGeocodingOptions): Promise<string> {
139+
const search = searchParams(options);
140+
const url = `https://api.mapbox.com/geocoding/v5/mapbox.places/${longitudeDeg},${latitudeDeg}.json?${search.toString()}`;
141+
return fetch(url)
142+
.then(response => response.json())
143+
.then((result: MapBoxFeatureCollection) => {
144+
if (result.features.length === 0) {
145+
const ns = latitudeDeg >= 0 ? 'N' : 'S';
146+
const ew = longitudeDeg >= 0 ? 'E' : 'W';
147+
const lat = Math.abs(latitudeDeg).toFixed(3);
148+
const lon = Math.abs(longitudeDeg).toFixed(3);
149+
return `${lat}° ${ns}, ${lon}° ${ew}`;
150+
}
151+
return textForMapboxResults(result);
152+
});
153+
}
154+
155+
export async function geocodingInfoForSearch(searchText: string, options: MapBoxForwardGeocodingOptions): Promise<MapBoxFeatureCollection> {
156+
const search = searchParams(options);
157+
const url = `https://api.mapbox.com/geocoding/v5/mapbox.places/${searchText}.json?${search.toString()}`;
158+
return fetch(url).then(response => response.json());
159+
}

0 commit comments

Comments
 (0)