JSFiddle - React, Tailwind, and code Playground

by rohanghatpande

JavaScript

/*
Make sure you always check if geolocation is supported 
and then and only then pass the callback

Also take look at navigator.geolocation.watchPosition() and navigator.geolocation.clearWatch()



*/

var URL_GMAPS = 'http://maps.google.com/maps/api/staticmap?';
var options ={enableHighAccuracy:false//Approximate is okay
              ,maximumAge: 3000//A fix from last 5 mins is perfectly fine
              ,timeout:15000 //time in milliseconds before giving up goelocation
             };
if (window.navigator.geolocation) {
    window.navigator.geolocation.getCurrentPosition(success //necessary
    , error //needed to find out why location could not be obtained if the browser api supports it
    , options); // additional options for determining the position
}
else {
    throw 'Geolocation not supported'
}


//Determining location succeeded
function success(pos) {
    var image = document.createElement('img');
    var latitude = pos.coords.latitude;
    var longitude = pos.coords.longitude;
    var accuracy = pos.coords.accuracy; //this is meters
    var zoom = 20;
    if (accuracy > 80) //if accuracy is greater than 80 meters then you want to zoom out
    zoom = zoom - Math.round(Math.log(accuracy / 50) / Math.LN2);

    var url = URL_GMAPS + 'center=' + latitude + ',' + longitude + '&size=1280x800&sensor=true' + '&zoom=' + zoom;

    image.src = url;

    document.body.appendChild(image);
}
//Determining location failed
function error(error){
    /*
    e.code values
    =1 is user did not give permisiion to share the location
    =2 is browser was unable to determine the location
    =3 timeout elapsed
    e
    */
    document.write('Geolocation request failed error code: '+ e.code+ ', Message: ' +e.meesage);
}