百度地图:地址逆解析

根据经纬度获取当前具体位置

官方地址:http://lbsyun.baidu.com/index.php?title=webapi
项目中有个功能类似美团酒店入住的功能,有个功能:定位当前具体地址,单纯根据API还是有坑的

  • 首先根据浏览器定位拿到当前所在的经纬度
function map() {
           // 百度地图API功能
           var BMap = window.BMap;
           var geoc = new BMap.Geocoder();
           var geolocation = new BMap.Geolocation();
           geolocation.getCurrentPosition(function (r) {
               geoc.getLocation(r.point, function (rs) {
                   var addComp = rs.addressComponents;
                   var cityName = addComp.city;
                   //当前的经纬度以及城市,调用方法去获取具体位置
                   readCurrentAddress(r.point.lat, r.point.lng)
                   // console.log(r.point.lng,r.point.lat,cityName)
               });
           });
       }
  • 然后根据当前的经纬度去拿到所在的具体位置
//读取当前具体地址地址
       function readCurrentAddress(lat, lng) {
           $.ajax({
               url: "http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=" + lat + "," + lng + "&output=json&pois=1&latest_admin=1&ak=SLGho2cIGWRcXLLISz1Dk4YjaO49kdv6",
               type: 'GET',
               async: false,
               dataType: 'jsonp',
               contentType: 'application/json; charset=utf-8',
               success: function (result) {
               //请求到的数据在result.result中,如下图
                   if (result.status === 0) {
                       $('#myAdd').text(result.result.business)  //可替换参数sematic_description、formatted_address
                   } else {
                       alert("请求失败,请重新尝试")
                   }
               }
           })
       }

在这里插入图片描述
坑的位置:dataType: ‘jsonp’,如果不加这个就会出现跨域的情况。报错如下:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/baidu_41604826/article/details/89400895