位置情報の取得(Geolocation)
navigator.geolocation getCurrentPosition watchPosition
デバイスのGPS・Wi-Fi・携帯基地局から現在位置を取得します。HTTPS環境とユーザー許可が必要です。
デモ:現在位置の取得
コード例
js
// 一度だけ取得
navigator.geolocation.getCurrentPosition(
// 成功時
(position) => {
const { latitude, longitude, accuracy } = position.coords;
console.log(`緯度: ${latitude}, 経度: ${longitude}`);
console.log(`精度: ±${accuracy}m`);
console.log(`高度: ${position.coords.altitude}`);
console.log(`速度: ${position.coords.speed} m/s`);
},
// エラー時
(error) => {
switch (error.code) {
case error.PERMISSION_DENIED: // 1
console.error('許可拒否');
break;
case error.POSITION_UNAVAILABLE: // 2
console.error('位置取得不可');
break;
case error.TIMEOUT: // 3
console.error('タイムアウト');
break;
}
},
// オプション
{
enableHighAccuracy: true, // GPS優先(バッテリー消費増)
timeout: 10000, // タイムアウト ms
maximumAge: 60000, // キャッシュの有効期限 ms
}
);
// 継続的に追跡(移動中など)
const watchId = navigator.geolocation.watchPosition(
(pos) => updateMap(pos.coords),
(err) => console.error(err)
);
// 追跡停止
navigator.geolocation.clearWatch(watchId);
// 対応確認
if ('geolocation' in navigator) {
// Geolocation API が使える
}⚠️ プライバシーとセキュリティ
- HTTPS環境のみ動作(HTTP では使用不可)
- ユーザーの明示的な許可が必要
- 位置情報は極めてセンシティブ — サーバーには必要な精度でのみ送信
watchPositionは使わないときは必ず停止する- バックグラウンド追跡は Service Worker + Push API が必要
NEWGeolocationSensor API(Web Sensors API)
より細かな制御が可能な新しいGeolocation APIです(実験的)。
js
// GeolocationSensor(実験的)
const sensor = new GeolocationSensor({ frequency: 1 }); // 1Hz
sensor.addEventListener('reading', () => {
console.log(sensor.latitude, sensor.longitude);
console.log(sensor.accuracy);
});
sensor.addEventListener('error', (e) => {
if (e.error.name === 'NotAllowedError') {
console.error('許可が必要');
}
});
sensor.start(); // 開始
sensor.stop(); // 停止
// Permissions Policy で制限
// Feature-Policy: geolocation 'self'🤖 AIプロンプトテンプレート
以下の要件を満たすTypeScript + Reactコンポーネントを作成してください。 - navigator.geolocation.getCurrentPositionを使った現在位置取得のサンプルを示す - 緯度・経度・精度情報の取得と表示の例を含める - watchPosition()を使ったリアルタイム位置追跡のサンプルを含める - 位置情報の権限リクエストとエラーハンドリング(拒否・タイムアウト)の例を示す - 取得した座標をGoogle MapsやOpenStreetMapのURLに変換するサンプルを含める - コメントは日本語で記述する
⚠️ このプロンプトはあくまでたたき台です。AIの回答はモデルやバージョン、会話の文脈によって毎回異なります。意図通りに動かない場合は、条件を追記・修正してお使いください。