처음에는 puppeteer npm 으로 크롤링을 해올까 했는데
주소만 있으면 간단하게 카카오맵으로 검색후 좌표를 가져올수 있을듯 해서 코드를 만들어봤습니다
여기서도 몇가지 착오가 있었지만 저의 부주의한 실수와 기록은 바로바로 못해서 결과물만 올려 보겠습니다
컨트롤러
@Post('update-coordinates')
async updateCoordinates(): Promise<string> {
await this.storesService.updateCoordinates();
return 'Coordinates updated successfully';
}
서비스
async updateCoordinates(): Promise<void> {
try {
const stores = await this.storesRepository.getStoreAddressId();
for (const store of stores) {
const {address, storeId} = store;
try {
const coordinates = await this.storesRepository.getCoordinate(address);
const La = coordinates[0];
const Ma = coordinates[1];
await this.storesRepository.updateCoord(La,Ma,storeId);
console.log(`Updated coordinates for address: ${address}`, La,Ma, storeId);
} catch (error) {
console.error(`Error updating coordinates for address: ${address}`, error);
}
}
} catch (error) {
console.error('Error occurred during database operation:', error);
}
}
리포지토리
async getStoreAddressId() {
return await this.find({ select: ['storeId', 'address'] })
}
async getCoordinate(address: string): Promise<any> {
const url =
'https://dapi.kakao.com/v2/local/search/address.json?query=' + encodeURIComponent(address);
const restApiKey = '************************';
const headers = { Authorization: 'KakaoAK ' + restApiKey };
try {
const response = await axios.get(url, { headers });
const result = response.data;
if (result.documents.length !== 0) {
const resultAddress = result.documents[0].address;
const coordinates = [resultAddress.y, resultAddress.x];
return coordinates;
} else {
return null;
}
} catch (error) {
throw new Error('Error fetching coordinates from Kakao API: ' + error.message);
}
}
async updateCoord(La: number, Ma: number, storeId: number): Promise<any> {
await this.update(storeId, { La, Ma });
}
참고:entity가 notnull이라서 저번에 csv에서 가져올떄 0으로 넣어줬고 여기서 업데이트 한 것입니다.