Get geolocation with Google map script


SUBMITTED BY: lakben

DATE: July 13, 2017, 7:56 p.m.

FORMAT: HTML

SIZE: 2.0 kB

HITS: 3726

  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 src="https://maps.google.com/maps/api/js?sensor=false&key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU"></script>
  8. <!--
  9. To use this code on your website, get a free API key from Google.
  10. Read more at: https://www.w3schools.com/graphics/google_maps_basic.asp
  11. -->
  12. <script>
  13. var x = document.getElementById("demo");
  14. function getLocation() {
  15. if (navigator.geolocation) {
  16. navigator.geolocation.getCurrentPosition(showPosition, showError);
  17. } else {
  18. x.innerHTML = "Geolocation is not supported by this browser.";
  19. }
  20. }
  21. function showPosition(position) {
  22. lat = position.coords.latitude;
  23. lon = position.coords.longitude;
  24. latlon = new google.maps.LatLng(lat, lon)
  25. mapholder = document.getElementById('mapholder')
  26. mapholder.style.height = '250px';
  27. mapholder.style.width = '500px';
  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. function showError(error) {
  38. switch(error.code) {
  39. case error.PERMISSION_DENIED:
  40. x.innerHTML = "User denied the request for Geolocation."
  41. break;
  42. case error.POSITION_UNAVAILABLE:
  43. x.innerHTML = "Location information is unavailable."
  44. break;
  45. case error.TIMEOUT:
  46. x.innerHTML = "The request to get user location timed out."
  47. break;
  48. case error.UNKNOWN_ERROR:
  49. x.innerHTML = "An unknown error occurred."
  50. break;
  51. }
  52. }
  53. </script>
  54. </body>
  55. </html>

comments powered by Disqus