API Usage Guide Geolocation API: Claude Code 활용 가이드
api usage guide geolocation api: Claude Code 활용. 실용적인 팁과 코드 예시를 포함합니다.
位置情報APIでロケーションベースの機能を구현
Geolocation APIを使えば、사용자の現在地を취득してローカル검색や내비게이션機能を提供할 수 있습니다。Claude Codeを활용すると、権限관리や에러 핸들링を含めた堅牢な구현を効率よく구축할 수 있습니다。
位置情報취득の基本
> 사용자の現在位置を취득するReactフック를 생성해줘。
> 権限관리、에러 핸들링、ローディング状態を含めて。
// hooks/useGeolocation.ts
import { useState, useEffect, useCallback } from 'react';
interface GeolocationState {
latitude: number | null;
longitude: number | null;
accuracy: number | null;
loading: boolean;
error: string | null;
timestamp: number | null;
}
interface UseGeolocationOptions {
enableHighAccuracy?: boolean;
timeout?: number;
maximumAge?: number;
}
export function useGeolocation(options: UseGeolocationOptions = {}) {
const [state, setState] = useState<GeolocationState>({
latitude: null,
longitude: null,
accuracy: null,
loading: false,
error: null,
timestamp: null,
});
const getCurrentPosition = useCallback(() => {
if (!navigator.geolocation) {
setState(prev => ({ ...prev, error: 'Geolocation APIは非対応です' }));
return;
}
setState(prev => ({ ...prev, loading: true, error: null }));
navigator.geolocation.getCurrentPosition(
(position) => {
setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
accuracy: position.coords.accuracy,
loading: false,
error: null,
timestamp: position.timestamp,
});
},
(error) => {
const messages: Record<number, string> = {
1: '位置情報の取得が拒否されました',
2: '位置情報を取得できませんでした',
3: '位置情報の取得がタイムアウトしました',
};
setState(prev => ({
...prev,
loading: false,
error: messages[error.code] || '不明なエラー',
}));
},
{
enableHighAccuracy: options.enableHighAccuracy ?? false,
timeout: options.timeout ?? 10000,
maximumAge: options.maximumAge ?? 0,
}
);
}, [options.enableHighAccuracy, options.timeout, options.maximumAge]);
return { ...state, getCurrentPosition };
}
位置情報を활용した컴포넌트
// components/NearbySearch.tsx
import { useGeolocation } from '../hooks/useGeolocation';
export function NearbySearch() {
const { latitude, longitude, loading, error, getCurrentPosition } = useGeolocation({
enableHighAccuracy: true,
});
return (
<div className="rounded-xl border p-6">
<h2 className="mb-4 text-xl font-bold">近くのスポットを検索</h2>
{!latitude && !loading && (
<button
onClick={getCurrentPosition}
className="rounded-lg bg-blue-600 px-4 py-2 text-white hover:bg-blue-700"
>
現在地を取得
</button>
)}
{loading && (
<div className="flex items-center gap-2 text-gray-600">
<span className="animate-spin">⏳</span>
位置情報を取得中...
</div>
)}
{error && (
<div className="rounded-lg bg-red-50 p-3 text-red-600">{error}</div>
)}
{latitude && longitude && (
<div>
<p className="mb-2 text-sm text-gray-600">
現在地: {latitude.toFixed(4)}, {longitude.toFixed(4)}
</p>
<NearbyResults lat={latitude} lng={longitude} />
</div>
)}
</div>
);
}
실시간位置追跡
// hooks/useWatchPosition.ts
import { useState, useEffect, useRef } from 'react';
export function useWatchPosition() {
const [positions, setPositions] = useState<GeolocationPosition[]>([]);
const watchIdRef = useRef<number | null>(null);
const startTracking = () => {
if (!navigator.geolocation) return;
watchIdRef.current = navigator.geolocation.watchPosition(
(position) => {
setPositions(prev => [...prev, position]);
},
(error) => console.error('追跡エラー:', error),
{ enableHighAccuracy: true, maximumAge: 5000 }
);
};
const stopTracking = () => {
if (watchIdRef.current !== null) {
navigator.geolocation.clearWatch(watchIdRef.current);
watchIdRef.current = null;
}
};
useEffect(() => {
return stopTracking;
}, []);
return { positions, startTracking, stopTracking };
}
距離計算ユーティリティ
// utils/geo.ts
export function haversineDistance(
lat1: number, lon1: number,
lat2: number, lon2: number
): number {
const R = 6371; // 地球の半径(km)
const dLat = toRad(lat2 - lat1);
const dLon = toRad(lon2 - lon1);
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
}
function toRad(deg: number): number {
return deg * (Math.PI / 180);
}
// Usage example
const distance = haversineDistance(35.6762, 139.6503, 34.6937, 135.5023);
console.log(`東京〜大阪: ${distance.toFixed(1)}km`); // 約396.9km
プライバシーへの配慮
// 位置情報の精度を意図的に下げる(プライバシー保護)
function coarsenLocation(lat: number, lng: number, precision: number = 2) {
return {
latitude: Number(lat.toFixed(precision)),
longitude: Number(lng.toFixed(precision)),
};
}
// 서버に전송前にぼかす
async function sendLocation(lat: number, lng: number) {
const coarse = coarsenLocation(lat, lng);
await fetch('/api/location', {
method: 'POST',
body: JSON.stringify(coarse),
});
}
정리
Geolocation APIは、ローカル검색や내비게이션など多くのユースケースで활용할 수 있습니다。Claude Code를 활용하면 보안やプライバシーに配慮した구현を효율적으로구축할 수 있습니다。반응형デザインと組み合わせて、モバイルでの使い勝手も최적화합시다。Geolocation APIの상세仕様はMDN Web Docs를 참고하세요.
무료 PDF: 5분 완성 Claude Code 치트시트
이메일 주소만 등록하시면 A4 한 장짜리 치트시트 PDF를 즉시 보내드립니다.
개인정보는 엄격하게 관리하며 스팸은 보내지 않습니다.
이 글을 작성한 사람
Masa
Claude Code를 적극 활용하는 엔지니어. 10개 언어, 2,000페이지 이상의 테크 미디어 claudecode-lab.com을 운영 중.
관련 글
Claude Code 다국어 글을 매일 발행하기 전에 확인할 7가지
누락된 언어, 깨진 CTA, 반영되지 않은 배포를 막기 위해 다국어 Claude Code 글을 매일 발행하기 전에 확인할 체크리스트입니다.
Codex Automations란? 잠자는 동안 AI가 콘텐츠 운영을 처리하게 하는 방법
Codex Automations로 트래픽 분석, 주제 선정, 글 작성, CTA 개선, 배포까지 자동화하는 실전 가이드.
Claude Code × GCP Cloud Functions 완전 가이드 | 서버리스 함수 초고속 개발
Claude Code로 GCP Cloud Functions를 효율화. HTTP/Pub/Sub/Firestore 트리거 구현부터 로컬 테스트·배포 자동화까지, Masa의 실무 경험을 토대로 실제 코드로 해설.