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를 참고하세요.
Claude Code 워크플로우를 한 단계 업그레이드하세요
지금 바로 Claude Code에 복사해 쓸 수 있는 검증된 프롬프트 템플릿 50선.
이 글을 작성한 사람
Masa
Claude Code를 적극 활용하는 엔지니어. 10개 언어, 2,000페이지 이상의 테크 미디어 claudecode-lab.com을 운영 중.
관련 글
Claude Code로 리팩토링을 자동화하는 방법
Claude Code를 활용해 코드 리팩토링을 효율적으로 자동화하는 방법을 알아봅니다. 실전 프롬프트와 구체적인 리팩토링 패턴을 소개합니다.
Claude Code로 사이드 프로젝트 개발 속도를 극대화하는 방법 [예제 포함]
Claude Code를 활용해 개인 프로젝트 개발 속도를 획기적으로 높이는 방법을 알아봅니다. 실전 예제와 아이디어부터 배포까지의 워크플로를 포함합니다.
Complete CORS Configuration Guide: Claude Code 활용 가이드
complete cors configuration guide: Claude Code 활용. 실용적인 팁과 코드 예시를 포함합니다.