HTML5 Geolocation with Google Maps


/ Published in: JavaScript
Save to your folder(s)

HTML5 geolocation using the new HTML5 geolocation API, JavaScript and Google Maps. HTML5 geolocation detection is included. This will work in almost every modern browser except IE, but if your browser does not support it, it will tell you so. It will also provide a message to the user if they decline to share their location with the browser. This example uses jQuery.


Copy this code and paste it in your HTML
  1. <!DOCTYPE HTML>
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  5. <title>HTML5 Geolocation Demo</title>
  6. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
  7. <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
  8. </head>
  9.  
  10. <body>
  11.  
  12. <div id="doc">
  13.  
  14. <h1>HTML5 Geolocation Demo</h1>
  15.  
  16. <div id="geo-wrapper"></div>
  17. <p id="msg"></p>
  18. <p id="lat"></p>
  19. <p id="long"></p>
  20.  
  21. </div>
  22.  
  23. <script type="text/javascript">
  24. function supports_geolocation() {
  25. return !!navigator.geolocation;
  26. }
  27.  
  28. function get_location() {
  29. if ( supports_geolocation() ) {
  30. navigator.geolocation.getCurrentPosition(show_map, handle_error);
  31. } else {
  32. // no native support;
  33. $("#msg").text('Your browser doesn\'t support geolocation!');
  34. }
  35. }
  36.  
  37. function show_map(position) {
  38. var latitude = position.coords.latitude;
  39. var longitude = position.coords.longitude;
  40. // let's show a map or do something interesting!
  41.  
  42. $("#geo-wrapper").css({'width':'640px','height':'480px'});
  43.  
  44. var latlng = new google.maps.LatLng(latitude, longitude);
  45. var myOptions = {
  46. zoom: 10,
  47. center: latlng,
  48. mapTypeId: google.maps.MapTypeId.ROADMAP
  49. };
  50. var map = new google.maps.Map(document.getElementById("geo-wrapper"), myOptions);
  51.  
  52. var marker = new google.maps.Marker({
  53. position: latlng,
  54. title:"You are here (more or less)!"
  55. });
  56.  
  57. // To add the marker to the map, call setMap();
  58. marker.setMap(map);
  59.  
  60. $("#msg").text('Your browser thinks you are here:');
  61. $("#lat").text('Latitude: ' + latitude);
  62. $("#long").text('Longitude: ' + longitude);
  63. }
  64.  
  65. function handle_error(err) {
  66. if (err.code == 1) {
  67. // user said no!
  68. $("#msg").text('You chose not to share your location.');
  69. }
  70. }
  71.  
  72. get_location();
  73. </script>
  74.  
  75. </body>
  76. </html>

URL: http://diveintohtml5.org/geolocation.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.