const x_pi = 3.14159265358979324 * 3000.0 / 180.0;
const pi = 3.1415926535897932384626;
const EARTH_RADIUS = 6378.137;//地球半径

const rad = (e) => {
    return e * pi / 180;
}

const geo = {
    bd09_gcj02(lon, lat) {
        const x = lon - 0.0065;
        const y = lat - 0.006;
        const z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
        const theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
        const gg_lng = z * Math.cos(theta)
        const gg_lat = z * Math.sin(theta)
        return [gg_lng, gg_lat];
    },
    getDistance(lon1, lat1, lon2, lat2) {
        const radLat1 = rad(lat1);
        const radLat2 = rad(lat2);
        const a = radLat1 - radLat2;
        const b = rad(lon1) - rad(lon2);
        let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s *= EARTH_RADIUS;
        return s.toFixed(2);
    },
    // // 北京
    // defaultPos: {
    //     lon: 116.413383,
    //     lat: 39.910924,
    // },
    // 义乌
    defaultPos: {
        lon: 120.070380,
        lat: 29.309300,
    },
    getWebGeo(timeout) {
        return new Promise((resolve, reject) => {
            navigator.geolocation.getCurrentPosition(e => {
                resolve({
                    lon: e.coords.longitude,
                    lat: e.coords.latitude,
                });
            }, e => {
                resolve(this.defaultPos);
            }, {
                enableHighAccuracy: false,
                timeout: timeout || 5000,
                maximumAge: 0
            });
        });
    },
}

export default geo;