前段時間恰好使用了百度地圖的js api定位獲取用戶當前經緯度並獲取當前詳細位置和經過當前用戶詳細地理位置換取用戶當前經緯度座標的功能,爲了方便下次找起來方便一些本身在這裏記錄一下,但願也可以幫助到有須要的童鞋們!javascript
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=您的密鑰"></script>
<div id="allmap"></div>html
避免頁面中出現:java
Uncaught TypeError: Cannot read property 'gc' of undefined
<script type="text/javascript"> var map = new BMap.Map("allmap");//建立Map實例,注意頁面中必定要有個id爲allmp的div var point = new BMap.Point(116.331398,39.897445);//建立定座標 map.centerAndZoom(point,12);//// 初始化地圖,設置中心點座標和地圖級別 var geolocation = new BMap.Geolocation(); var gc = new BMap.Geocoder();//建立地理編碼器 // 開啓SDK輔助定位 geolocation.enableSDKLocation(); geolocation.getCurrentPosition(function(r){ if(this.getStatus() == BMAP_STATUS_SUCCESS){ var mk = new BMap.Marker(r.point); map.addOverlay(mk); map.panTo(r.point); alert('您的位置:' + r.point.lng + ',' + r.point.lat); var pt = r.point; map.panTo(pt);//移動地圖中心點 //alert(r.point.lng);//X軸 //alert(r.point.lat);//Y軸 gc.getLocation(pt, function(rs){ var addComp = rs.addressComponents; //alert(addComp.city); alert(addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber); }); } else { alert('failed'+this.getStatus()); } }); </script>
<script type="text/javascript"> var map = new BMap.Map("allmap"); var point = new BMap.Point(116.331398,39.897445); map.centerAndZoom(point,12); var geolocation = new BMap.Geolocation(); geolocation.getCurrentPosition(function(r){ if(this.getStatus() == BMAP_STATUS_SUCCESS){ var mk = new BMap.Marker(r.point); map.addOverlay(mk); map.panTo(r.point); alert('您的位置:'+r.point.lng+','+r.point.lat); } else { alert('failed'+this.getStatus()); } }); </script>
<script type="text/javasript"> var map = new BMap.Map("allmap"); var point = new BMap.Point(116.331398,39.897445); map.centerAndZoom(point,12); function myFun(result){ var cityName = result.name; map.setCenter(cityName); alert("當前定位城市:"+cityName); } var myCity = new BMap.LocalCity(); myCity.get(myFun); </script>
http://api.map.baidu.com/geocoder/v2/?address=長沙市&output=json&ak=您的密鑰
我使用的是ajax請求數據,注意假如dataType爲json時會出現跨域問題,最終我使用的是jsonp請求就解決了:ajax
json和jsonp之間的區別:http://www.javashuo.com/article/p-xczwhswx-do.htmljson
$.ajax({ url:"http://api.map.baidu.com/geocoder/v2/?address="+city+"&output=json&ak=您的密鑰", dataType:'jsonp', processData: false, type:'get', success:function(data){ console.log(data); if (data.status==0) { console.log("緯度:"+data.result.location.lat+"經度:"+data.result.location.lng); } }, error:function(XMLHttpRequest, textStatus, errorThrown) { console.log(XMLHttpRequest.status); console.log(XMLHttpRequest.readyState); console.log(textStatus); }});
返回json格式的響應數據:api
{"status":0,"result":{"location":{"lng":112.94547319535288,"lat":28.23488939994364},"precise":0,"confidence":12,"comprehension":100,"level":"城市"}}