首先需要引入百度地图api 和jq
<script type="text/javascript" src="https://api./api?v=2.0&ak=你的秘钥&s=1"></script><script src="/jquery/1.9.0/jquery.js"></script>
获取经纬度和省市区
$(function () {// 页面加载时执行getLocation函数window.onload = getLocation;if (supportsGeoLocation()) {//alert("你的浏览器支持 GeoLocation.");} else {alert("不支持 GeoLocation.")}// 检测浏览器是否支持HTML5function supportsGeoLocation() {return !!navigator.geolocation;}// 单次位置请求执行的函数 function getLocation() {navigator.geolocation.getCurrentPosition(mapIt, locationError);}//定位成功时,执行的函数function mapIt(position) {lon = position.coords.longitude;lat = position.coords.latitude;// latlon = latlon = lon + "," + lat;// console.log(latlon, 'jingweidu');// alert("您位置的经度是:" + lon + " 纬度是:" + lat);// 创建地理编码(地理解析器)实例var myGeo = new BMap.Geocoder();// 根据坐标得到地址描述 下面输入坐标。myGeo.getLocation(new BMap.Point(lon, lat), function (result) {if (result) {console.log(result);alert(JSON.stringify(result.addressComponents));}});}// 定位失败时,执行的函数function locationError(error) {console.log(error);switch (error.code) {case error.PERMISSION_DENIED:alert("无法定位.");break;case error.POSITION_UNAVAILABLE:alert("位置信息不可用.");break;case error.TIMEOUT:alert("请求超时.");break;case error.UNKNOWN_ERROR:alert("未知错误.");break;}}})
注意new BMap()是2.0版本的 new BMapGL()是1.0版本的 如果用new BMapGL()会报错BMapGL is not defined
因为一开始就写错了 这个问题困扰了好久。。。引以为戒