Module 42 : Javascript Geolocation
API.
📚 Theory & Concepts
✅ What is Geolocation?
Geolocation refers to the identification of the geographic location of an object, such as a smartphone or computer. In JavaScript, this is done through the navigator.geolocation object.
✅ Core Methods
Method
Description
getCurrentPosition()
Gets the user's current location once.
watchPosition()
Continuously monitors position changes.
clearWatch()
Stops watching for location changes.
Example with Explanation
function getUserLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition, showError); } else { console.log("Geolocation is not supported by this browser."); } } function showPosition(position) { const latitude = position.coords.latitude; const longitude = position.coords.longitude; console.log("Latitude: " + latitude + " | Longitude: " + longitude); } function showError(error) { switch(error.code) { case error.PERMISSION_DENIED: console.log("User denied the request for Geolocation."); break; case error.POSITION_UNAVAILABLE: console.log("Location information is unavailable."); break; case error.TIMEOUT: console.log("The request to get user location timed out."); break; case error.UNKNOWN_ERROR: console.log("An unknown error occurred."); break; } } // Call the function getUserLocation();
Explanation:
navigator.geolocation: Built-in object that provides access to location services.
getCurrentPosition(success, error):
success is the callback function that receives the location.
error is the callback function that handles failures.
position.coords.latitude / longitude: The actual coordinates.
Error handling is crucial for fallback behaviors.
Exercise: Display Location on Google Maps
🎯 Goal:
Display the user's current location using Google Maps with a marker.
✅ Example:
<!DOCTYPE html> <html> <head> <title>Geolocation Map</title> <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script> </head> <body> <h2>My Location</h2> <div id="map" style="width:100%;height:400px;"></div> <script> function initMap(latitude, longitude) { const userLocation = { lat: latitude, lng: longitude }; const map = new google.maps.Map(document.getElementById("map"), { zoom: 15, center: userLocation }); new google.maps.Marker({ position: userLocation, map: map }); } function getLocationAndMap() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { const lat = position.coords.latitude; const lng = position.coords.longitude; initMap(lat, lng); }, function(error) { console.log("Error: ", error.message); }); } else { alert("Geolocation not supported."); } } getLocationAndMap(); </script> </body> </html>
Replace YOUR_API_KEY with your actual Google Maps API key.
🧠 Research Insight
How does geolocation work?
GPS: Most accurate; uses satellite data.
Wi-Fi Positioning: Uses Wi-Fi hotspots for estimating location.
IP Address: Approximate location based on your IP.
Cell Tower Triangulation: Mobile networks use tower distance.
Privacy Consideration
Browsers ask user permission before sharing location. Always respect the user's decision and explain why the location is needed.
Instructor. Notes
Suggested
Introduce use cases: Food delivery, Uber, weather.
Live demo using getCurrentPosition().
Discuss browser permission prompts.
Error simulation: Disable location to see error cases.
Integrate with Google Maps for a complete app experience.
Discussion Topics:
Why does geolocation sometimes fail indoors?
Compare getCurrentPosition() vs watchPosition().
How can apps use location for better UX?
Exercise
Create a webpage that:
Shows user’s coordinates.
Monitors changes using watchPosition().
Displays updates on the page.
✅ Starter Code:
<p id="output">Waiting for location...</p> <script> const output = document.getElementById("output"); if (navigator.geolocation) { const watchId = navigator.geolocation.watchPosition( (pos) => { output.innerText = `Latitude: ${pos.coords.latitude}, Longitude: ${pos.coords.longitude}`; }, (err) => { output.innerText = `Error: ${err.message}`; } ); // To stop watching: // navigator.geolocation.clearWatch(watchId); } else { output.innerText = "Geolocation not supported."; } </script>
🧠 Review
Questions
What is the difference between getCurrentPosition() and watchPosition()?
What are the common sources of location in Geolocation API?
How does the Geolocation API handle privacy and user permission?
What are some use cases for this API?
How do you integrate location data with a map?
Summary
Concept
Explanation
Geolocation API
Allows access to user's geographic location
getCurrentPosition()
Retrieves location once
watchPosition()
Tracks location over time
Permissions
Browsers prompt user before allowing access
Use Cases
Maps, tracking, weather, local services
✅ Assignment
Build a mini weather app:
Get the user's location.
Use the coordinates to call a weather API like OpenWeatherMap.
Display current weather info (temperature, humidity, etc.).
📚 Additional References
Web Docs - Geolocation API
Google Maps JavaScript API
OpenWeatherMap API
No comments:
Post a Comment