转自CSDN博客
xmt1139057136的专栏 网址:http://blog.csdn.net/xmtblog/article/details/45093661
1 <head runat="server"> 2 <title>调用百度地图API进行地理定位</title> 3 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 4 <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=nsfmboEtl3uEvghM4L1pGG5w"></script> 5 </head> 6 <body style="margin:50px 10px;"> 7 <form id="form1" runat="server"> 8 <div id="status" style="text-align: center"></div> 9 <div style="600px;height:480px;border:1px solid gray;margin:30px auto" id="container"></div> 10 </form> 11 </body> 12 </html> 13 <script type="text/javascript"> 14 //默认地理位置设置为上海市浦东新区 15 var x = 121.48789949, y = 31.24916171; 16 window.onload = function () { 17 if (navigator.geolocation) { 18 navigator.geolocation.getCurrentPosition(showPosition); 19 document.getElementById("status").innerHTML = "HTML5 Geolocation is supported in your browser."; 20 // 百度地图API功能 21 var map = new BMap.Map("container"); 22 var point = new BMap.Point(x, y); 23 map.centerAndZoom(point, 12); 24 25 var geolocation = new BMap.Geolocation(); 26 geolocation.getCurrentPosition(function (r) { 27 if (this.getStatus() == BMAP_STATUS_SUCCESS) { 28 var mk = new BMap.Marker(r.point); 29 map.addOverlay(mk); 30 map.panTo(r.point); 31 } 32 else { 33 alert('failed' + this.getStatus()); 34 } 35 }, { enableHighAccuracy: true }) 36 return; 37 } 38 alert("你的浏览器不支持获取地理位置!"); 39 }; 40 function showPosition(position) { 41 x = position.coords.latitude; 42 y = position.coords.longitude; 43 } 44 </script> 45
查看运行效果: