很常见的一个需求:在 web 端获取到当前位置的省市区信息
这里使用百度地图来实现
准备
去百度地图开放平台 申请密钥ak,代码里需要用到。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>地图</title> <style> body { margin: 0; padding: 0; height: 100vw; width: 100vh; }
#map { width: 100%; height: 100%; }
.anchorBL { display: none; } </style> <script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=您的密钥" > </script> </head>
<body> <div id="map"></div>
<script> (function () { const map = new BMap.Map('map');
if (!navigator.geolocation) { alert('您的浏览器不支持地图定位!'); return; }
navigator.geolocation.getCurrentPosition( onLocationSuccess, onLocationError, { timeout: 10000, enableHighAccuracy: true } );
async function onLocationSuccess(position) { let { longitude, latitude } = position.coords; let geoLocation = await getGeoLocation(longitude, latitude); let { address, addressComponents } = geoLocation; console.log(geoLocation.addressComponents); alert(`您当前的位置是:${address}`); }
async function onLocationError(err) { let codeZh; switch (err.code) { case err.PERMISSION_DENIED: codeZh = '用户拒绝了获取地理位置的请求!'; break;
case err.POSITION_UNAVAILABLE: codeZh = '位置信息不可用!'; break;
case err.TIMEOUT: codeZh = '请求超时!'; break;
case err.UNKNOWN_ERROR: codeZh = '未知错误!'; break; } alert(`${codeZh};code=${err.code};${err.message}`); }
async function getGeoLocation(longitude, latitude) { let geo = new BMap.Geocoder(); return new Promise((resolve) => { geo.getLocation( new BMap.Point(longitude, latitude), (result) => { resolve(result); } ); }); } })(); </script> </body> </html>
|