JavaScript || How To Use Geolocation To Get Current Position With Promises Using Vanilla JavaScript
The following is a module with functions which demonstrates how to use geolocation to get the device current position with promises using vanilla JavaScript.
The following function is a wrapper for the navigator.geolocation.getCurrentPosition, updated to use promises to run as an asynchronous operation.
1. Get Current Position
The example below demonstrates the use of ‘Utils.getCurrentPosition‘ to get the current position of the device.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
// Get Current Position <script> (async () => { try { // Get device position let position = await Utils.getCurrentPosition(); console.log(position); alert(`Latitude: ${position.coords.latitude}, Longitude: ${position.coords.longitude}`); } catch (error) { console.log(error); alert(`Error Code: ${error.code}, Error Message: ${error.message}`); } })(); </script> // example output: /* { "coords": { "accuracy": 13.094 "altitude": null "altitudeAccuracy": null "heading": null "latitude": 36.4458083 "longitude": -114.6677835 "speed": null } "timestamp": 1639609018611 } */ |
3. Utils Namespace
The following is the Utils.js Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 15, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.js // Description: Javascript that handles general utility functions // ============================================================================ /** * NAMESPACE: Utils * USE: Handles general utility functions. */ var Utils = Utils || {}; (function(namespace) { 'use strict'; // Property to hold public variables and functions let exposed = namespace; /** * FUNCTION: getCurrentPosition * USE: Gets the current position of the device * @param options: The PositionOptions * @return: A promise that will contain the GeolocationPosition of the device on completion */ exposed.getCurrentPosition = (options = null) => { return new Promise((resolve, reject) => { if (navigator && navigator.geolocation) { navigator.geolocation.getCurrentPosition(resolve, reject, options); } else { reject(new Error('Geolocation is not supported by this environment')); } }); } (function (factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof exports === 'object') { module.exports = factory(); } }(function() { return namespace; })); }(Utils)); // http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Leave a Reply