GeoLocation API With Javascript

GeoLocation API With Javascript

Getting an accurate location for many applications is essential for the way they run their business. From letting customers track where their food delivery is to simply viewing properties within your area without putting in lots of details, it's not as complicated as you may think for such an advanced feature.

Let's get into our Javascript code. Before retreiving our location, we need to construct a success function, failure function, and an options object. The only mandatory argument you need to pass in is a success function, but it's reccomended to provide a failure function and options for more granular control and to enable high accuracy if we need it.

So, here is our mandatory success function. It requires one parameter in which a GeolocationPosition object is passed:



const geoSuccess = pos => {
    // Latitude and longitude coordinates
    const latitude = pos.coords.latitude;
    const longitude = pos.coords.longitude;
    // Accuracy radius in meters
    const accuracy = pos.coords.accuracy;
    // UNIX timestamp
    const timestamp = pos.timestamp;
    console.log(latitude, longitude, accuracy, timestamp);
};

Now let's just define a simple failure method which, if an error were to arise, gives us a warning in the console.



const geoFailure = err => {
    console.warn(`Error ${err.code}: ${err.message}`);
}

Okay! time to pass in our options object. There are three arguments to pass into this:



const geoOptions = {
    maximumAge: 0, // Amount of time in milliseconds a location is cached before returning a new location
    timeout: 10000, // Amount of time in milliseconds that the device can take until an error is raised. Default is Infinity
    enableHighAccuracy: true, // A boolean indicating whether you want the most accurate results
}

Okay, time to get our location! This command should ask the end user for permission to get their location if not already accepted on your domain:



// Verify if the geolocation object is in navigator to avoid unneccasary errors disrupting your script
if('geolocation' in navigator) {
    navigator.geolocation.getCurrentPosition(geoSuccess, geoFailure, geoOptions);
}
else {
    console.log('Geolocation is not enabled on this device');
}

And there we have it! You should have the latitude, longitude, accuracy and UNIX timestamp of your position in your console, and you can configure a fetch request to your server if you need to gather that information accordingly. You can also format a Google Maps URL to show the location on a map like so in your geoSuccess function:



const geoSuccess = pos => {
    const latitude = pos.coords.latitude;
    const longitude = pos.coords.longitude;
    const accuracy = pos.coords.accuracy;
    const timestamp = pos.timestamp;
    console.log(latitude, longitude, accuracy, timestamp);
    // Construct and return Google Maps URL
    const mapURL = `https://www.google.com/maps/search/?api=1&query=${latitude}%2C${longitude}`;
    return mapURL;
};

You can also use another method that takes the same arguments, but it registers a worker that executes the geoSuccess function every time the device location changes, perfect if you need real-time tracking:



// Execute the method that registers the worker and returns the ID of that worker
const geoWatchID = navigator.geolocation.watchPosition(geoSuccess, geoFailure, geoOptions);
// Clear the worker and stop tracking
navigator.geolocation.clearWatch(geoWatchID);

Go ahead and give it a try below, and feel free to inspect the code that makes it function in your browser tools!:



Latitude: 0
Longitude: 0
Accuracy: Within 0 meters

Show On Map
Broadband Providers