Repository navigation
Expand file tree
/
Copy pathgeocode.ts
More file actions
252 lines (251 loc) · 9.12 KB
/
Copy pathgeocode.ts
File metadata and controls
252 lines (251 loc) · 9.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import { fetchJson } from './http.js';
import { createGeocodeFetch } from './geocodeFetch.js';
import { searchNaverLocalPlaces } from '../services/places/client.js';
export interface GeocodeOptions {
kakaoRestApiKey?: string;
naverClientId?: string;
naverClientSecret?: string;
googleMapsApiKey?: string;
fetchImpl?: typeof fetch;
timeout?: number;
timeoutMs?: number;
}
export interface GeocodedLocation {
latitude: number;
longitude: number;
formattedAddress: string | null;
}
interface KakaoDocument {
x?: string;
y?: string;
place_name?: string;
address_name?: string;
road_address_name?: string;
}
function validKakaoDocument(value: unknown): value is KakaoDocument {
if (!value || typeof value !== 'object') return false;
const document = value as Record<string, unknown>;
return ['place_name', 'address_name', 'road_address_name'].every(
(field) => document[field] === undefined || typeof document[field] === 'string',
);
}
export function readGeocodeEnvironment(): GeocodeOptions {
const env = typeof process === 'undefined' ? {} : process.env;
return {
kakaoRestApiKey: env.KAKAO_REST_API_KEY,
naverClientId: env.NAVER_CLIENT_ID,
naverClientSecret: env.NAVER_CLIENT_SECRET,
};
}
export function geocodeBindings(bindings?: {
KAKAO_REST_API_KEY?: string;
NAVER_CLIENT_ID?: string;
NAVER_CLIENT_SECRET?: string;
}): GeocodeOptions {
return {
kakaoRestApiKey: bindings?.KAKAO_REST_API_KEY,
naverClientId: bindings?.NAVER_CLIENT_ID,
naverClientSecret: bindings?.NAVER_CLIENT_SECRET,
};
}
export function validKoreanCoordinates(latitude: number, longitude: number): boolean {
return (
Number.isFinite(latitude) &&
Number.isFinite(longitude) &&
latitude >= 33 &&
latitude <= 39 &&
longitude >= 124 &&
longitude <= 132
);
}
const normalize = (value: string) =>
value
.replace(/특별자치시|특별자치도|특별시|광역시/gu, '')
.replace(/경기도/gu, '경기')
.replace(/충청북도/gu, '충북')
.replace(/충청남도/gu, '충남')
.replace(/전라북도|전북특별자치도/gu, '전북')
.replace(/전라남도/gu, '전남')
.replace(/경상북도/gu, '경북')
.replace(/경상남도/gu, '경남')
.replace(/강원도/gu, '강원')
.replace(/제주도/gu, '제주')
.replace(/[^0-9a-z가-힣]/giu, '')
.toLowerCase();
function matches(query: string, value: string, placeName: string): boolean {
// 역 이름의 숫자가 주소나 다른 역의 출구 번호와 대신 일치하는 것을 막습니다.
const station = query.match(/([0-9a-z가-힣]+역)$/iu)?.[1];
if (
station &&
!new RegExp(`${station}(?:[0-9]+호선|$|[^가-힣])`, 'iu').test(placeName)
)
return false;
const tokens =
query
.replace(/^대한민국\s*/u, '')
.match(/[0-9]+(?:-[0-9]+)?|[a-z가-힣]+/giu)
?.map((token) => (/^\d/u.test(token) ? token : normalize(token))) || [];
const normalized = normalize(value);
return (
tokens.length > 0 &&
tokens.every((token) =>
/^\d+(?:-\d+)?$/u.test(token)
? value.match(/\d+(?:-\d+)?/gu)?.includes(token)
: token.endsWith('역')
? new RegExp(`${token}(?:[0-9]+호선|$|[^가-힣])`, 'u').test(value)
: normalized.includes(token),
)
);
}
function matchesAddress(query: string, address: string): boolean {
// 지역과 도로명은 독립 토큰으로, 도로 번호와 건물 번호는 순서까지 검증합니다.
const tokens = (value: string) =>
value
.replace(/^대한민국\s*/u, '')
.match(/[0-9]+(?:-[0-9]+)?|[a-z가-힣]+/giu)
?.map(normalize) ?? [];
const expected = tokens(query);
const actual = tokens(address);
return (
query.match(/\d+(?:-\d+)?/gu)!.join(',') ===
(address.match(/\d+(?:-\d+)?/gu)?.join(',') ?? '') &&
expected.every((token) => actual.includes(token))
);
}
function kakaoLocation(
query: string,
documents: KakaoDocument[],
isAddress: boolean,
): GeocodedLocation | null {
for (const document of documents) {
if (!isAddress && !document.place_name?.trim()) continue;
const latitude = Number(document.y);
const longitude = Number(document.x);
if (
!validKoreanCoordinates(latitude, longitude) ||
!(isAddress
? matchesAddress(query, document.address_name || '') ||
matchesAddress(query, document.road_address_name || '')
: matches(
query,
`${document.place_name} ${document.address_name || ''} ${document.road_address_name || ''}`,
document.place_name!,
))
)
continue;
return {
latitude,
longitude,
formattedAddress: document.road_address_name || document.address_name || null,
};
}
return null;
}
export async function searchKakaoPlaces(
query: string,
options: GeocodeOptions,
coordinates?: { latitude: number; longitude: number },
): Promise<KakaoDocument[]> {
const key = (options.kakaoRestApiKey ?? readGeocodeEnvironment().kakaoRestApiKey)?.trim();
if (!key) return [];
const endpoint = new URL('https://dapi.kakao.com/v2/local/search/keyword.json');
endpoint.searchParams.set('query', query);
endpoint.searchParams.set('size', '15');
if (coordinates) {
endpoint.searchParams.set('x', String(coordinates.longitude));
endpoint.searchParams.set('y', String(coordinates.latitude));
endpoint.searchParams.set('radius', '20000');
endpoint.searchParams.set('sort', 'distance');
}
const body = await fetchJson<{ documents?: KakaoDocument[] }>(endpoint.toString(), {
fetchImpl: createGeocodeFetch(options.fetchImpl, options.timeout ?? options.timeoutMs ?? 10000),
headers: { Authorization: `KakaoAK ${key}` },
timeout: options.timeout ?? options.timeoutMs ?? 10000,
});
return Array.isArray(body.documents) ? body.documents.filter(validKakaoDocument) : [];
}
export async function geocodeLocation(
query: string,
input: GeocodeOptions = {},
): Promise<GeocodedLocation | null> {
const keyword = query.trim();
if (!keyword) return null;
const env = readGeocodeEnvironment();
const options = {
...input,
kakaoRestApiKey: input.kakaoRestApiKey ?? env.kakaoRestApiKey,
naverClientId: input.naverClientId ?? env.naverClientId,
naverClientSecret: input.naverClientSecret ?? env.naverClientSecret,
};
// 대체 공급자도 최초 요청의 남은 시간만 사용합니다.
const deadline = Date.now() + (options.timeout ?? options.timeoutMs ?? 10000);
const remaining = () => deadline - Date.now();
// '을지로3가역'처럼 숫자가 든 역 이름은 주소가 아니라 장소로 검색합니다.
const isAddress = !keyword.endsWith('역') && /(?:로|길|동|읍|면|리)\s*\d/u.test(keyword);
let documents: KakaoDocument[] = [];
const kakaoTimeout = remaining();
if (options.kakaoRestApiKey?.trim() && kakaoTimeout > 0) {
try {
if (isAddress) {
const endpoint = new URL('https://dapi.kakao.com/v2/local/search/address.json');
endpoint.searchParams.set('query', keyword);
const body = await fetchJson<{ documents?: KakaoDocument[] }>(endpoint.toString(), {
fetchImpl: createGeocodeFetch(
options.fetchImpl,
kakaoTimeout,
),
headers: { Authorization: `KakaoAK ${options.kakaoRestApiKey.trim()}` },
timeout: kakaoTimeout,
});
documents = Array.isArray(body.documents) ? body.documents.filter(validKakaoDocument) : [];
} else documents = await searchKakaoPlaces(keyword, { ...options, timeout: kakaoTimeout });
} catch {
// 오류나 빈 결과는 정확하게 일치하는 대체 검색으로 보완합니다.
}
}
const location = kakaoLocation(keyword, documents, isAddress);
if (location) return location;
const keywordTimeout = remaining();
if (isAddress && options.kakaoRestApiKey?.trim() && keywordTimeout > 0) {
try {
const fallback = kakaoLocation(
keyword, await searchKakaoPlaces(keyword, { ...options, timeout: keywordTimeout }), true,
);
if (fallback) return fallback;
} catch {
// 주소가 정확하게 일치하는 네이버 결과가 있으면 보완합니다.
}
}
const naverTimeout = remaining();
if (options.naverClientId && options.naverClientSecret && naverTimeout > 0) {
try {
const result = await searchNaverLocalPlaces({
...options,
keyword,
fetchImpl: createGeocodeFetch(
options.fetchImpl,
naverTimeout,
),
timeoutMs: naverTimeout,
});
const place = result.places.find(
(item) =>
item.latitude !== null &&
item.longitude !== null &&
validKoreanCoordinates(item.latitude, item.longitude) &&
(isAddress
? matchesAddress(keyword, item.address) || matchesAddress(keyword, item.roadAddress)
: matches(keyword, `${item.name} ${item.address} ${item.roadAddress}`, item.name)),
);
if (place)
return {
latitude: place.latitude as number,
longitude: place.longitude as number,
formattedAddress: place.roadAddress || place.address || null,
};
} catch {
return null;
}
}
return null;
}