1+ // Geolocation API
2+ 3+ // Example One
4+ 5+ const textOne = document . getElementById ( "textOne" ) ;
6+ 7+ function getLocationOne ( ) {
8+ if ( navigator . geolocation ) {
9+ navigator . geolocation . getCurrentPosition ( showPositionOne ) ;
10+ } else {
11+ textOne . innerHTML = "Geolocation is not supported by this browser." ;
12+ }
13+ }
14+ 15+ function showPositionOne ( position ) {
16+ textOne . innerHTML = "Latitude: " + position . coords . latitude +
17+ "<br>Longitude: " + position . coords . longitude ;
18+ }
19+ 20+ 21+ // Example Two
22+ 23+ const textTwo = document . getElementById ( "textTwo" ) ;
24+ 25+ function getLocationTwo ( ) {
26+ if ( navigator . geolocation ) {
27+ navigator . geolocation . getCurrentPosition ( showPositionTwo , showError ) ;
28+ } else {
29+ textTwo . innerHTML = "Geolocation is not supported by this browser." ;
30+ }
31+ }
32+ 33+ function showPositionTwo ( position ) {
34+ textTwo . innerHTML = "Latitude: " + position . coords . latitude +
35+ "<br>Longitude: " + position . coords . longitude ;
36+ }
37+ 38+ function showError ( error ) {
39+ switch ( error . code ) {
40+ case error . PERMISSION_DENIED :
41+ textTwo . innerHTML = "User denied the request for Geolocation."
42+ break ;
43+ case error . POSITION_UNAVAILABLE :
44+ textTwo . innerHTML = "Location information is unavailable."
45+ break ;
46+ case error . TIMEOUT :
47+ textTwo . innerHTML = "The request to get user location timed out."
48+ break ;
49+ case error . UNKNOWN_ERROR :
50+ textTwo . innerHTML = "An unknown error occurred."
51+ break ;
52+ }
53+ }
54+ 55+ // Example Three
56+ const textThree = document . getElementById ( "textThree" ) ;
57+ 58+ function getLocationThree ( ) {
59+ if ( navigator . geolocation ) {
60+ navigator . geolocation . watchPosition ( showPositionThree ) ;
61+ } else {
62+ textThree . innerHTML = "Geolocation is not supported by this browser." ;
63+ }
64+ }
65+ 66+ function showPositionThree ( position ) {
67+ textThree . innerHTML = "Latitude: " + position . coords . latitude +
68+ 69+ "<br>Longitude: " + position . coords . longitude ;
70+ }
71+ 72+ // Show Position Example Four
73+ let mapholder = document . getElementById ( "mapholder" )
74+ 75+ function showPositionFour ( position ) {
76+ let latlon = position . coords . latitude + "," + position . coords . longitude ;
77+ 78+ let img_url = "https://maps.googleapis.com/maps/api/staticmap?center=" + latlon + "&zoom=14&size=400x300&sensor=false&key=YOUR_KEY" ;
79+ 80+ mapholder . innerHTML = "<img src='" + img_url + "'>" ;
81+ }
0 commit comments