<!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>百度地图地理定位</title> </head> <body> <p id="map"></p> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=FPMfDA2HhXG1IiZPIxslDAPgLx3VUAcT"></script> <script> $(function(){ getLocation(); }) function getLocation() { // 创建查询对象 var geolocation = new BMap.Geolocation(); //调用getCurrentPosition函数 geolocation.getCurrentPosition(function(r){ console.log(this.getStatus()); // 如果查询成功 if(this.getStatus() == 0){ // 地理位置逆解析 var geoc = new BMap.Geocoder(); geoc.getLocation(r.point,function(rs){ var address = rs.addressComponents; var addComp = rs.addressComponents; var currentCity,currentLocation; currentCity = addComp.province.slice(0,-1) + "," + addComp.city + "," + addComp.district ; console.log(currentCity); $('#map').html(currentCity); if(rs.surroundingPois.length!==0){ currentLocation = rs.surroundingPois[0].title; }else if(rs.surroundingPois.length==0){ if(rs.business!==''){ currentLocation = rs.business.split(',')[0]; }else if(rs.business==''){ currentLocation = addComp.city; } } console.log(currentLocation); }); }else{ console.log("定位失败"); }; },{enableHighAccuracy: true}); } </script> </body> </html>