Last active
June 7, 2022 04:12
-
-
Save matsubo/144f1e95f24f8534eda4551d82428bef to your computer and use it in GitHub Desktop.
最寄りの駅情報をJavascriptで取得するコード
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="form-control w-full max-w-full" data-controller="doc"> | |
<label class="label"> | |
<span class="label-text">経度</span> | |
</label> | |
<input type="text" data-doc-target="lon" name="lon" id="lon" placeholder="139.738999" value="" | |
class="input input-bordered w-full max-w-xs" /> | |
<label class="label"> | |
<span class="label-text">緯度</span> | |
</label> | |
<input type="text" data-doc-target="lat" name="lat" id="lat" placeholder="35.62876" value="" | |
class="input input-bordered w-full max-w-xs" /> | |
<button type="button" data-action="click->doc#getLocation" class="btn btn-outline my-3"> | |
ブラウザから位置情報を取得 | |
</button> | |
<button type="button" data-action="click->doc#search" class="btn btn-outline my-3 btn-primary"> | |
最寄りの駅を検索 | |
</button> | |
<div class="mockup-code bg-primary"> | |
<pre><code data-doc-target="output">ここに出力されます。</code></pre> | |
</div> | |
</div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Controller } from "@hotwired/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; }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment