1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
6 <title>获取地理位置</title>
7 <style>
8 html,body,#allmap{
9 width:100%;
10 height:100%;
11 }
12 </style>
13 </head>
14 <body>
15 <div id="box"></div>
16 <div id="allmap"></div>
17
18 <script>
19 var map;
20 //异步加载地图
21 function loadJScript() {
22 var script = document.createElement("script");
23 script.type = "text/javascript";
24 script.src = "http://api.map.baidu.com/api?v=2.0&ak=j9Qhl3n6K2RbPb2EnYr5LW0mEyaacdiC&callback=init";
25 document.body.appendChild(script);
26 }
27 function init() {
28 var map1 = new BMap.Map("allmap"); // 创建Map实例
29 var point = new BMap.Point(110, 38); // 创建点坐标
30 map1.centerAndZoom(point,15);
31 map1.enableScrollWheelZoom(); //启用滚轮放大缩小
32 map=map1;
33 }
34 window.onload = loadJScript;
35 //异步加载地图
36 //获取经纬度
37 var x = document.querySelector("#box");
38 function getLocation(){
39 if(navigator.geolocation){
40 console.log("123");
41 navigator.geolocation.getCurrentPosition(function(position){
42 console.log(456);
43 x.innerHTML ="纬度:"+position.coords.latitude +"<br>经度:"+
44 position.coords.longitude;
45 var longitude = position.coords.longitude,latitude = position.coords.latitude;
46 //调用百度地图api:
47 theLocation(map,longitude,latitude)
48 },
49 function (error){
50 switch(error.code)
51 {
52 case error.PERMISSION_DENIED:
53 x.innerHTML="User denied the request for Geolocation."
54 break;
55 case error.POSITION_UNAVAILABLE:
56 x.innerHTML="Location information is unavailable."
57 break;
58 case error.TIMEOUT:
59 x.innerHTML="The request to get user location timed out."
60 break;
61 case error.UNKNOWN_ERROR:
62 x.innerHTML="An unknown error occurred."
63 break;
64 }
65 },
66 {
67 // 指示浏览器获取高精度的位置,默认为false
68 enableHighAcuracy: true,
69 // 指定获取地理位置的超时时间,默认不限时,单位为毫秒
70 timeout: 5000,
71 // 最长有效期,在重复获取地理位置时,此参数指定多久再次获取位置。
72 maximumAge: 3000
73 }
74 );
75 }else{
76 x.innerHTML="该浏览器不支持获取地理位置!";
77 alert('123');
78 }
79 }
80 function theLocation(map,longitude,latitude) {
81 if (longitude != "" && latitude != "") {
82 map.clearOverlays();
83 var new_point = new BMap.Point(longitude, latitude);
84 //坐标转换
85 var convertor = new BMap.Convertor();
86 var pointArr = [];
87 pointArr.push(new_point);
88 convertor.translate(pointArr, 1, 5, function(data){
89 if(data.status === 0) {
90 //标注转换后的坐标
91 var marker = new BMap.Marker(data.points[0]);
92 map.addOverlay(marker);
93 var label = new BMap.Label("您现在的位置", {offset: new BMap.Size(20, -10)});
94 marker.setLabel(label); //添加百度label
95 map.setCenter(data.points[0]);
96 map.centerAndZoom(data.points[0],18);
97 }
98 })
99 }
100 }
101 //获取位置
102 getLocation();
103 </script>
104
105 </body>
106 </html>