-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
The Geolocation API allows web pages to get the geographic location of a user. With it, you can access latitude, longitude, altitude, and more. This API is widely used in maps, location-based services, weather apps, and delivery services.
The Geolocation API is a browser feature that lets JavaScript determine the user’s current position.
Key points:
Requires user permission to access location.
Works on most modern browsers.
Provides high-level accuracy if supported by GPS, Wi-Fi, or IP address.
Returns a position object with coordinates and additional data.
The Geolocation API is accessed through:
navigator.geolocation
It has two main methods:
Method | Description |
---|---|
getCurrentPosition(success, error, options) |
Gets the current location once. |
watchPosition(success, error, options) |
Continuously monitors the user’s location. |
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function(position) {
console.log("Latitude:", position.coords.latitude);
console.log("Longitude:", position.coords.longitude);
},
function(error) {
console.error("Error getting location:", error.message);
}
);
} else {
console.log("Geolocation is not supported by this browser.");
}
Explanation:
getCurrentPosition
gets the current coordinates.
position.coords.latitude
and position.coords.longitude
return the location.
error.message
shows why location could not be obtained.
The error
callback receives an object with a code and message.
Code | Meaning |
---|---|
1 | Permission denied |
2 | Position unavailable |
3 | Timeout |
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
alert("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable.");
break;
case error.TIMEOUT:
alert("The request to get user location timed out.");
break;
default:
alert("An unknown error occurred.");
}
}
You can pass an options
object to getCurrentPosition
or watchPosition
to control accuracy and timeout.
const options = {
enableHighAccuracy: true, // Use GPS if available
timeout: 5000, // Wait 5 seconds
maximumAge: 0 // Do not use cached location
};
navigator.geolocation.getCurrentPosition(
successCallback,
errorCallback,
options
);
Explanation:
enableHighAccuracy
improves accuracy but may consume more battery.
timeout
specifies maximum wait time.
maximumAge
prevents using old cached location.
watchPosition
continuously monitors location changes and calls the success callback whenever coordinates change.
if (navigator.geolocation) {
const watchId = navigator.geolocation.watchPosition(
function(position) {
console.log("Updated Latitude:", position.coords.latitude);
console.log("Updated Longitude:", position.coords.longitude);
},
function(error) {
console.error("Error:", error.message);
},
{ enableHighAccuracy: true }
);
// Stop watching after 30 seconds
setTimeout(() => {
navigator.geolocation.clearWatch(watchId);
console.log("Stopped watching position.");
}, 30000);
}
Explanation:
watchPosition
tracks changes automatically.
clearWatch
stops tracking using the returned watchId
.
You can integrate Geolocation with Google Maps or Leaflet.js to show the user’s location visually.
<div id="map" style="width: 500px; height: 300px;"></div>
<script>
function initMap(lat, lng) {
const location = { lat: lat, lng: lng };
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: location
});
new google.maps.Marker({ position: location, map: map });
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initMap(position.coords.latitude, position.coords.longitude);
});
}
</script>
<!-- Remember to include Google Maps API script -->
Explanation:
The user’s coordinates center the map.
A marker shows the exact location.
Requires a Google Maps API key.
Browsers require HTTPS for geolocation.
Users must grant permission.
Always inform users why you need their location.
Avoid storing precise coordinates unless necessary.
Maps and navigation apps – show user location and routes.
Weather apps – display weather for the current location.
Delivery services – track delivery or pickup locations.
Location-based content – customize content based on region.
Fitness apps – track running or cycling paths.
The Web Geolocation API allows you to access and use the user’s location safely and efficiently.
Key points:
Use navigator.geolocation.getCurrentPosition()
for a single fetch.
Use watchPosition()
to continuously track movement.
Always handle errors and ask for user permission.
Use options for accuracy, timeout, and cached positions.
Can integrate with maps or location-based services.
With this API, you can build dynamic, location-aware web applications that enhance user experience.
Write JavaScript code to get the user’s current latitude and longitude and display them in <p>
elements.
Create a function using getCurrentPosition
that alerts the user’s coordinates when a button is clicked.
Implement error handling to show a message if the user denies location access.
Use watchPosition
to log the user’s updated coordinates whenever they move, and stop watching after 20 seconds.
Create a map using Google Maps API and center it on the user’s current location.
Build a small app that fetches the user’s location and displays it in a formatted string: “Latitude: xx, Longitude: yy.”
Use getCurrentPosition
with enableHighAccuracy: true
and timeout: 5000
to get a precise location.
Write a script that shows an alert with a custom message if location information is unavailable.
Create a tracker that counts how many times the user’s location has changed in 30 seconds using watchPosition
.
Build a weather app example that gets the user’s coordinates and fetches weather data from an API (e.g., OpenWeatherMap).
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts