document.addEventListener("DOMContentLoaded", ()=> { // ここまでに変数 mymap にLeaflet地図オブジェクトが入っているとする。 var locmarker = L.marker(mymap.getCenter()).addTo(mymap); locmarker.bindPopup("取得中...").openPopup(); // マーカを作り、取得に関する情報をポップアップ表示する用途に用いる。 function tryLocate() {// 取得を開始する処理を行なう関数の定義 mymap.locate({ watch: false, setView: true, timeout: 4000, maximumAge: 8000, enableHighAccuracy: true }); } function onSuccess(pos) { // 成功時のコールバック。関数名は何でもよい。 // pos.coords に位置情報が入る。LeafletのLatLngに変換する。 locmarker.setPopupContent( // ポップアップ表示を "ここは "+pos.latlng+"です." // 更新後の緯度経度に変え、 ).openPopup().setLatLng(pos.latlng);// ポップアップし、ポイントも変更する } var nTrial = 10;// 最大試行回数を決めておく function onError(err) { // 失敗時のコールバック let restN = "あと"+(--nTrial)+"回試行します。"; locmarker.setPopupContent("取得失敗:"+restN).openPopup(); if (nTrial > 0) { // 残り回数があれば tryLocate(); // 再度取得を試行する } } mymap.on('locationfound', onSuccess) mymap.on('locationerror', onError) tryLocate(); }, false);