在网页地图中获得当前位置

在因为要做一个地图显示的功能,所以在网上找了很多资料,结果还是不如官网来得快。

在网页地图中获得当前位置代码:
 1 <!DOCTYPE html>
 2 <html>
 3 <body>
 4 <p id="demo">运行效果:</p>
 5 <button onclick="getLocation()">试试看</button>
 6 <div id="mapholder"></div>
 7 <script src="http://maps.google.com/maps/api/js?sensor=false"></script>
 8 <script>
 9 var x=document.getElementById("demo");
10 function getLocation()
11   {
12   if (navigator.geolocation)
13     {
14     navigator.geolocation.getCurrentPosition(showPosition,showError);
15     }
16   else{x.innerHTML="Geolocation is not supported by this browser.";}
17   }
18 
19 function showPosition(position)
20   {
21   lat=position.coords.latitude;
22   lon=position.coords.longitude;
23   latlon=new google.maps.LatLng(lat, lon)
24   mapholder=document.getElementById('mapholder')
25   mapholder.style.height='250px';
26   mapholder.style.width='500px';
27 
28   var myOptions={
29   center:latlon,zoom:14,
30   mapTypeId:google.maps.MapTypeId.ROADMAP,
31   mapTypeControl:false,
32   navigationControlOptions:{style:google.maps.NavigationControlStyle.SMALL}
33   };
34   var map=new google.maps.Map(document.getElementById("mapholder"),myOptions);
35   var marker=new google.maps.Marker({position:latlon,map:map,title:"You are here!"});
36   }
37 
38 function showError(error)
39   {
40   switch(error.code) 
41     {
42     case error.PERMISSION_DENIED:
43       x.innerHTML="User denied the request for Geolocation."
44       break;
45     case error.POSITION_UNAVAILABLE:
46       x.innerHTML="Location information is unavailable."
47       break;
48     case error.TIMEOUT:
49       x.innerHTML="The request to get user location timed out."
50       break;
51     case error.UNKNOWN_ERROR:
52       x.innerHTML="An unknown error occurred."
53       break;
54     }
55   }
56 </script>
57 </body>
58 </html>

标签