js 实现经纬度转 城市-区县-街道

原理就是先通过浏览器的navigator.geolocation获取用户经纬度,然后利用百度地图API向百度发送AJAX请求,之后用字符串处理提取出城市街道

然而,下面的代码理论上正确,但实际上似乎不能用(至少在我的win10笔记本上不能用),因为当前大多数电脑似乎不具备GPS定位的功能。也就是说,navigator.geolocation提供的经纬度是错的。

而且这是硬件问题,也就是说,不管你用什么代码,都不能正确获得定位信息。

我觉得手机浏览器或许可以,但没测试。

用promise编程的原因是navigator.geolocation是异步操作。不这样写会导致代码执行顺序混乱。


// 定位当前城市、街道
function getLoc() {
    let lat, lon;
    let rel_lon = 117.491568, rel_lat = 30.6648;
    let rel_x = 13079243.833504178, rel_y = 3567300.9383499795;
    let fac_x = 111320.70, fac_y = 124289.425;
    let x, y;
    new Promise((resolve, reason) => {
        navigator.geolocation.getCurrentPosition((pos) => {
        	// 当前经纬度存入变量 lat、lon
            lat = pos.coords.latitude;
            lon = pos.coords.longitude;
            console.log(lon, lat);
            x = ((lon - rel_lon) * fac_x + rel_x).toFixed(6);
            y = ((lat - rel_lat) * fac_y + rel_y).toFixed(6);
            console.log(x, y);
            resolve();
        });
    }).then(aa => {
        let xhr = new XMLHttpRequest();
        xhr.onload = function () {
            if (xhr.readyState == 4) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    console.log(this.responseText);
                }
            }
        };
        xhr.open('GET', 'https://api.map.baidu.com/?qt=rgc&x=' + x + '&y=' + y + '&dis_poi=100');
        xhr.send();
    });


}

getLoc();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值