end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

navigator.geolocation.getCurrentPosition() の Promise, async, await による同期関数化

javascriptによるブラウザの位置情報(緯度経度)取得が 非同期関数で扱いづらい為、以下のような感じへ

'use strict';
class AppBase {
    
    constructor() {}
    
    error_to_server =(err_msg)=> {
        // console.log(err_msg);
        const xhr = new XMLHttpRequest();
        const url = `/error_js.html?msg=` + encodeURI(err_msg);
        xhr.open("GET", url, true);
        xhr.send();
    }

    // refer to https://stackoverflow.com/questions/51843227
    get_latlng=()=>{
        return new Promise( (resolve, reject) => {
            navigator.geolocation.getCurrentPosition(
                position => resolve(position),
                error => reject(error)
            )
        })
    }
}


class NewBuild extends AppBase {
    constructor() {
        super(); // 仕様上 thisを使う前にsuper()を呼ぶ要あり
    }
    
    // refer to https://stackoverflow.com/questions/51843227
    init_window =async()=> {
        try {
            let position = await this.get_latlng();
            console.log(position);
        } catch(err) {
            console.log(err)
        }
    }
}

let new_build = new NewBuild();
new_build.init_window();