313 文字
2 分
現在位置情報から最寄り駅の一覧を取得する
概要
- 経度緯度から、最寄り駅の一覧を取得します。
- ブラウザから経度緯度情報は Javscript で取得できます。
利用するAPI
駅情報・路線情報 REST APIを利用します。
REST API のサンプル。東京タワーからの最寄り駅一覧を出力してみます。distance の単位は km です。
% curl 'https://train.teraren.com/stations/near_by_stations.json?lon=139.7454316&lat=35.658584' | jq 'limit(5; .[])'{ "station_cd": 9930122, "station_name": "赤羽橋", "station_g_cd": 9930122, "distance": 0.4293522820451477}{ "station_cd": 2800317, "station_name": "神谷町", "station_g_cd": 2800317, "distance": 0.48968747581839894}{ "station_cd": 9930306, "station_name": "御成門", "station_g_cd": 9930306, "distance": 0.6242133516473801}{ "station_cd": 9930305, "station_name": "芝公園", "station_g_cd": 9930305, "distance": 0.639515764707121}{ "station_cd": 9930209, "station_name": "大門", "station_g_cd": 9930121, "distance": 0.8574239732003268}Webから利用する場合のサンプルコード
スクリーンショット

Stimulusによるサンプルコード。ブラウザから位置情報を取得して、駅の一覧を表示するだけのスクリプトです。 サーバのCORSの設定はGETをどこのサイトからでもできるようにしてあるのでご自由に利用ください。
import { Controller } from 'stimulus';
export default class extends Controller { static targets = ['lon', 'lat', 'output'];
getLocation() { if (!('geolocation' in navigator)) { alert('Allow browser to acquire location.'); }
navigator.geolocation.getCurrentPosition((position) => { this.latTarget.value = position.coords.latitude; this.lonTarget.value = position.coords.longitude; }, (error) => { alert(error.message); }); }
search() { const url = `https://train.teraren.com/stations/near_by_stations.json?lon=${this.lonTarget.value}&lat=${this.latTarget.value}&limit=5`; fetch(url) .then((response) => response.json()) .then((json) => JSON.stringify(json, null, 2)) .then((json_string) => { this.outputTarget.textContent = json_string }); }} 現在位置情報から最寄り駅の一覧を取得する
https://blog.teraren.com/posts/qiita-20220607-cc3f69aa42a61ab654f2/ 関連記事
この記事が役に立ったら
GitHub Sponsorsで応援できます