原理就是先通过浏览器的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 = 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();