首页 > 语言 > JavaScript > 正文

js+html5获取用户地理位置信息并在Google地图上显示的方法

2024-05-06 16:21:29
字体:大 中 小
来源:转载
供稿:网友

这篇文章主要介绍了js+html5获取用户地理位置信息并在Google地图上显示的方法,涉及html5元素的操作技巧,需要的朋友可以参考下

本文实例讲述了js+html5获取用户地理位置信息并在Google地图上显示的方法。分享给大家供大家参考。具体实现方法如下:

  1. <!DOCTYPE html> 
  2. <html> 
  3. <body> 
  4. <p id="demo">Click the button to get your position:</p> 
  5. <button onclick="getLocation()">Try It</button> 
  6. <div id="mapholder"></div> 
  7. <script> 
  8. var x=document.getElementById("demo"); 
  9. function getLocation() 
  10. { 
  11. if (navigator.geolocation) 
  12. { 
  13. navigator.geolocation.getCurrentPosition(showPosition,showError); 
  14. } 
  15. else{x.innerHTML="Geolocation is not supported by this browser.";} 
  16. } 
  17. function showPosition(position) 
  18. { 
  19. var latlon=position.coords.latitude+","+position.coords.longitude; 
  20. var img_url="http://maps.googleapis.com/maps/api/staticmap?center=" 
  21. +latlon+"&zoom=14&size=400x300&sensor=false"; 
  22. document.getElementById("mapholder").innerHTML="<img src='"+img_url+"' />"; 
  23. } 
  24. function showError(error) 
  25. { 
  26. switch(error.code)  
  27. { 
  28. case error.PERMISSION_DENIED: 
  29. x.innerHTML="User denied the request for Geolocation." 
  30. break; 
  31. case error.POSITION_UNAVAILABLE: 
  32. x.innerHTML="Location information is unavailable." 
  33. break; 
  34. case error.TIMEOUT: 
  35. x.innerHTML="The request to get user location timed out." 
  36. break; 
  37. case error.UNKNOWN_ERROR: 
  38. x.innerHTML="An unknown error occurred." 
  39. break; 
  40. } 
  41. } 
  42. </script> 
  43. </body> 
  44. </html> 



希望本文所述对大家的web程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选