Web Geolocation Api in JavaScript
The Web Geolocation API in JavaScript allows you to get the geographical location (latitude and longitude) of a user's device.
? Basic Usage
if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( function(position) { const latitude = position.coords.latitude; const longitude = position.coords.longitude; console.log("Latitude:", latitude); console.log("Longitude:", longitude); }, function(error) { console.error("Error occurred:", error.message); } );} else { console.log("Geolocation is not supported by this browser.");}? Key Methods
getCurrentPosition(success, error, options)Gets the current position once.
watchPosition(success, error, options)Watches the user's position and calls back every time it changes.
clearWatch(watchId)Stops watching a position set by
watchPosition.
?? Optional Settings (third argument)
{ enableHighAccuracy: true, // try to use GPS timeout: 5000, // wait at most 5 seconds maximumAge: 0 // no cached position}?? Common Error Codes
1: Permission denied2: Position unavailable3: Timeout
? Important Notes
Requires HTTPS (except on
localhost).Prompts user for permission.
Might not work well on desktops (especially without GPS).
Let me know if you want an example with Google Maps or real-time tracking!