Drafts 앱에서 버튼을 만들어 아래 자바스크립트 코드를 지정하여 현재 위치에서 주소 정보와 날씨 정보를 가져오는 걸 만들어보았다.
클로드와 제미나이와 챗지피티를 동시에 사용했는데, 네이버 api 주소가 바뀌는 부분이 반영되어 있지않아 꽤 시간을 허비했다.
``` JavaScript - Draft Code
// 네이버 API
const clientId = "clientId";
const clientSecret = "clientSecret";
// 위치 정보 가져오기 (좌표)
var lat = draft.processTemplate("[[latitude]]");
var lon = draft.processTemplate("[[longitude]]");
// 역 지오코딩 (좌표 → 주소)
// 네이버 Reverse Geocoding REST API 호출
const coords = `${lon},${lat}`; // 네이버는 "경도,위도" 순서 사용
let http = HTTP.create();
let response = http.request({
"url": `https://maps.apigw.ntruss.com/map-reversegeocode/v2/gc?coords=${coords}&output=json&orders=roadaddr`,
"method": "GET",
"headers": {
"X-NCP-APIGW-API-KEY-ID": clientId,
"X-NCP-APIGW-API-KEY": clientSecret
}
});
if (!response.success) {
alert("데이터를 불러오지 못했습니다." + response.statusCode);
context.fail();
};
const addr_data = JSON.parse(response.responseText);
const res = addr_data.results[0];
let addr = `${res.region.area1.name} ${res.region.area2.name} ${res.region.area3.name} ${res.region.area4.name}`.trim();
if (res.land) {
addr += ` ${res.land.name || ""} ${res.land.number1} ${res.land.addition0.value || ""}`;
}
// openstreetmap 이용시 아래 코드 이용
let locationName = `${lat}, ${lon}`;
const http = HTTP.create();
const geoRes = http.request({
url: `https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lon}&format=json&accept-language=ko`,
method: "GET",
headers: { "User-Agent": "DraftsWeatherScript/1.0" }
});
if (geoRes.success) {
const geo = JSON.parse(geoRes.responseText);
const addr = geo.address;
// 구/동 단위로 표시 (없으면 상위 행정구역으로 대체)
const parts = [
addr.city || addr.town || addr.county || addr.state,
addr.suburb || addr.quarter || addr.neighbourhood || addr.village
].filter(Boolean);
if (parts.length > 0) locationName = parts.join(" ");
}
// ----------------------------------------
// 여기까지 현재 위치 기반으로 주소 변환 과정
// ----------------------------------------
// 날씨 조회 - 좌표로 조회
// app.displayInfoMessage("⛅ 날씨 데이터 불러오는 중...");
const weatherRes = http.request({
url: `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lon}¤t=temperature_2m,relative_humidity_2m,apparent_temperature,weather_code,wind_speed_10m,precipitation&daily=temperature_2m_max,temperature_2m_min,precipitation_sum,uv_index_max&hourly=precipitation_probability&timezone=auto&forecast_days=1`,
method: "GET"
});
if (!weatherRes.success) {
alert("날씨 데이터를 불러오지 못했습니다.");
context.fail();
}
const data = JSON.parse(weatherRes.responseText);
const cur = data.current;
const daily = data.daily;
const hourly = data.hourly;
// 데이터 가공
function getWeatherDesc(code) {
if (code === 0) return "☀️ 맑음";
if (code <= 3) return "🌤 구름 조금";
if (code <= 48) return "🌫 안개";
if (code <= 67) return "🌧 비";
if (code <= 77) return "❄️ 눈";
if (code <= 82) return "🌦 소나기";
if (code <= 99) return "⛈ 뇌우";
return "🌡";
}
function getUVLevel(uv) {
if (uv <= 2) return "낮음";
if (uv <= 5) return "보통";
if (uv <= 7) return "높음";
if (uv <= 10) return "매우 높음";
return "위험";
}
// 시간대별 강수 확률
const morning = Math.max(...hourly.precipitation_probability.slice(6, 12));
const afternoon = Math.max(...hourly.precipitation_probability.slice(12, 18));
const evening = Math.max(...hourly.precipitation_probability.slice(18, 24));
const today = new Date().toLocaleDateString("ko-KR", {
year: "numeric", month: "long", day: "numeric", weekday: "long"
});
// 현재 시간을 "2026-04-10 06:33" 형식으로 가져오기
var timestamp = strftime(new Date(), "%Y-%m-%d %H:%M");
// 텍스트 생성 (Markdown 형식)
const weatherText =
`
> [!info] **${addr}**
> 📅 ${timestamp}
> ${getWeatherDesc(cur.weather_code)}
>
> 🌡 **기온**
> - 현재: **${cur.temperature_2m} °C** (체감 ${cur.apparent_temperature} °C)
> - 최고 / 최저: **${daily.temperature_2m_max[0]} °C / ${daily.temperature_2m_min[0]} °C**
>
> 🌧 **기상 정보**
> - 💧 습도: ${cur.relative_humidity_2m} %
> - 🌬 풍속: ${cur.wind_speed_10m} km/h
> - ☀ 자외선: ${daily.uv_index_max[0]} (${getUVLevel(daily.uv_index_max[0])})
> - ☔ 강수량: ${daily.precipitation_sum[0]} mm
>
> ☔ **강수 확률**
> - 오전: ${morning} %
> - 오후: ${afternoon} %
> - 저녁: ${evening} %
---
`;
// Draft에 삽입
editor.setText(weatherText + editor.getText());
editor.setSelectedRange(weatherText.length, 0);
// app.displayInfoMessage("✅ 날씨 정보가 입력되었습니다!");
let content = draft.content;
app.setClipboard(content);
```