09-06-2022, 02:00 AM
Get User Location from Browser with JavaScript
<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/09/get-user-location-from-browser-with-javascript.jpg" width="550" height="233" title="" alt="" /></div><div><div class="modified-on" readability="7.1489361702128"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on September 5th, 2022.</div>
<p>This tutorial uses JavaScript’s GeoLocation API to get users’ location. This API call returns location coordinates and other geolocation details.</p>
<p>The following quick example has a function <em>getLatLong()</em> that uses the GeoLocation API. It calls the <em>navigator.geplocation.getCurrentPosition()</em>. This function needs to define the success and error callback function.</p>
<p>On success, it will return the geolocation coordinates array. The error callback includes the error code returned by the API. Both callbacks write the response in the browser console.</p>
<p>User’s location is a privacy sensitive information. We need to be aware of it before working on location access. Since it is sensitive, by default browser and the underlying operating system will not give access to the user’s location information.</p>
<p><strong>Important!</strong> The user has to,</p>
<ol>
<li>Explicitly enable location services at operating system level.</li>
<li>Give permission for the browser to get location information.</li>
</ol>
<p>In an earlier article we have seen about how to <a href="https://phppot.com/php/get-geolocation-with-country-by-ip-address-in-php/">get geolocation with country by IP address using PHP</a>.</p>
<div class="post-section-highlight" readability="36">
<h2>Quick example</h2>
<pre class="prettyprint"><code class="language-javascript">function getLatLong() { // using the JavaScript GeoLocation API // to get the current position of the user // if checks for support of geolocation API if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( function(currentPosition) { console.log(currentPosition)}, function(error) { console.log("Error: " + error.code)} ); } else { locationElement.innerHTML = "JavaScript Geolocation API is not supported by this browser."; }
}
</code></pre>
</div>
<h2>JavaScript GeoLocation API’s getCurrentPosition() function</h2>
<p>The below code is an extension of the quick example with <a href="https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API" target="_blank" rel="noopener">Geo Location API</a>. It has a UI that has control to call the JavaScript function to get the current position of the user.</p>
<p>The HTML code has the target to print the location coordinates returned by the API.</p>
<p>The JavaScript <em>fetch</em> callback parameter includes all the geolocation details. The callback function reads the latitude and longitude and shows them on the HTML target via JavaScript.</p>
<pre class="prettyprint"><code class="language-php-template"><!DOCTYPE html>
<html>
<head>
<title>Get User Location from Browser with JavaScript</title>
<link rel='stylesheet' href='style.css' type='text/css' />
<link rel='stylesheet' href='form.css' type='text/css' />
</head>
<body> <div class="phppot-container"> <h1>Get User Location from Browser with JavaScript</h1> <p>This example uses JavaScript's GeoLocation API.</p> <p>Click below button to get your latitude and longitude coordinates.</p> <div class="row"> <button onclick="getLatLong()">Get Lat Lng Location Coordinates</button> </div> <div class="row"> <p id="location"></p> </div> </div> <script> var locationElement = document.getElementById("location"); function getLatLong() { // using the JavaScript GeoLocation API // to get current position of the user // if checks for support of geolocation API if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( displayLatLong, displayError); } else { locationElement.innerHTML = "JavaScript Geolocation API is not supported by this browser."; } } /** * displays the latitude and longitude from the current position * coordinates returned by the geolocation api. */ function displayLatLong(currentPosition) { locationElement.innerHTML = "Latitude: " + currentPosition.coords.latitude + "<br>Longitude: " + currentPosition.coords.longitude; } /** * displays error based on the error code received from the * JavaScript geolocation API */ function displayError(error) { switch (error.code) { case error.PERMISSION_DENIED: locationElement.innerHTML = "Permission denied by user to get location." break; case error.POSITION_UNAVAILABLE: locationElement.innerHTML = "Location position unavailable." break; case error.TIMEOUT: locationElement.innerHTML = "User location request timed out." break; case error.UNKNOWN_ERROR: locationElement.innerHTML = "Unknown error in getting location." break; } } </script>
</body>
</html>
</code></pre>
<p><img loading="lazy" class="alignnone size-large wp-image-19347" src="https://phppot.com/wp-content/uploads/2022/09/get-user-location-browser-output-550x233.jpg" alt="get user location browser output" width="550" height="233" srcset="https://phppot.com/wp-content/uploads/2022/09/get-user-location-browser-output-550x233.jpg 550w, https://phppot.com/wp-content/uploads/20...00x127.jpg 300w, https://phppot.com/wp-content/uploads/20...68x326.jpg 768w, https://phppot.com/wp-content/uploads/20...output.jpg 1000w" sizes="(max-width: 550px) 100vw, 550px"></p>
<p>In the above example script, we have a function for handing errors. It is important to include the function when getting user location via browser. Because, by default, the user’s permission settings will be disabled.</p>
<p>So most of the times, when this script is invoked, we will get errors. So we should have this handler declared and passed as a callback to the getCurrentPosition function. On error, JavaScript will call this error handler.</p>
<h3>Geolocation API’s Output</h3>
<p>Following is the output format returned by the JavaScript geolocation API. We will be predominantly using latitude and longitude from the result. ‘speed’ may be used when getting dynamic location of the user. We will be seeing about that also at the end of this tutorial.</p>
<pre class="prettyprint"><code>{ coords = { latitude: 30.123456, longitude: 80.0253546, altitude: null, accuracy: 49, altitudeAccuracy: null, heading: null, speed: null, }, timestamp: 1231234897623
}
</code></pre>
<p><a class="demo" href="https://phppot.com/demo/get-user-location-browser-javascript/">View Demo</a></p>
<h2>User location by Geocoding</h2>
<p>We can <a href="https://phppot.com/php/how-to-get-current-location-using-google-map-javascript-api/">get the user’s location</a> by passing the latitude and longitude like below. There are many different service providers available and below is an example using Google APIs.</p>
<pre class="prettyprint"><code class="language-javascript">const lookup = position => { const { latitude, longitude } = position.coords; fetch(`http://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}`) .then(response => response.json()) .then(data => console.log(data)); //
}
</code></pre>
<h2></h2>
<h2>Get dynamic user location from browser using watchPosition()</h2>
<p>Here is an interesting part of the tutorial. How will get you a user’s dynamic location, that is when he is on the move.</p>
<p>We should use an another function of GeoLocation API to get dynamic location coordinates on the move. The function <em>watchPosition()</em> is used to do this via JavaScript.</p>
<p class="p1">To test this script, run it in a mobile browser while moving in a vehicle to get user’s dynamic location.</p>
<p>I have presented the code part that is of relevance below. You can get the complete script from the project zip, it’s free to download below.</p>
<pre class="prettyprint"><code class="language-javascript">var locationElement = document.getElementById("location"); function getLatLong() { // note the usage of watchPosition, this is the difference // this returns the dynamic user position from browser if (navigator.geolocation) { navigator.geolocation.watchPosition(displayLatLong, displayError); } else { locationElement.innerHTML = "JavaScript Geolocation API is not supported by this browser."; } }
</code></pre>
<p><a class="demo" href="https://phppot.com/demo/get-user-location-browser-javascript/">View Demo</a> <a class="download" href="https://phppot.com/downloads/javascript/get-user-location-browser-javascript.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/javascript/get-user-location-browser-javascript/#top" class="top">↑ Back to Top</a> </p>
</div>
https://www.sickgaming.net/blog/2022/09/...avascript/
<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/09/get-user-location-from-browser-with-javascript.jpg" width="550" height="233" title="" alt="" /></div><div><div class="modified-on" readability="7.1489361702128"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on September 5th, 2022.</div>
<p>This tutorial uses JavaScript’s GeoLocation API to get users’ location. This API call returns location coordinates and other geolocation details.</p>
<p>The following quick example has a function <em>getLatLong()</em> that uses the GeoLocation API. It calls the <em>navigator.geplocation.getCurrentPosition()</em>. This function needs to define the success and error callback function.</p>
<p>On success, it will return the geolocation coordinates array. The error callback includes the error code returned by the API. Both callbacks write the response in the browser console.</p>
<p>User’s location is a privacy sensitive information. We need to be aware of it before working on location access. Since it is sensitive, by default browser and the underlying operating system will not give access to the user’s location information.</p>
<p><strong>Important!</strong> The user has to,</p>
<ol>
<li>Explicitly enable location services at operating system level.</li>
<li>Give permission for the browser to get location information.</li>
</ol>
<p>In an earlier article we have seen about how to <a href="https://phppot.com/php/get-geolocation-with-country-by-ip-address-in-php/">get geolocation with country by IP address using PHP</a>.</p>
<div class="post-section-highlight" readability="36">
<h2>Quick example</h2>
<pre class="prettyprint"><code class="language-javascript">function getLatLong() { // using the JavaScript GeoLocation API // to get the current position of the user // if checks for support of geolocation API if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( function(currentPosition) { console.log(currentPosition)}, function(error) { console.log("Error: " + error.code)} ); } else { locationElement.innerHTML = "JavaScript Geolocation API is not supported by this browser."; }
}
</code></pre>
</div>
<h2>JavaScript GeoLocation API’s getCurrentPosition() function</h2>
<p>The below code is an extension of the quick example with <a href="https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API" target="_blank" rel="noopener">Geo Location API</a>. It has a UI that has control to call the JavaScript function to get the current position of the user.</p>
<p>The HTML code has the target to print the location coordinates returned by the API.</p>
<p>The JavaScript <em>fetch</em> callback parameter includes all the geolocation details. The callback function reads the latitude and longitude and shows them on the HTML target via JavaScript.</p>
<pre class="prettyprint"><code class="language-php-template"><!DOCTYPE html>
<html>
<head>
<title>Get User Location from Browser with JavaScript</title>
<link rel='stylesheet' href='style.css' type='text/css' />
<link rel='stylesheet' href='form.css' type='text/css' />
</head>
<body> <div class="phppot-container"> <h1>Get User Location from Browser with JavaScript</h1> <p>This example uses JavaScript's GeoLocation API.</p> <p>Click below button to get your latitude and longitude coordinates.</p> <div class="row"> <button onclick="getLatLong()">Get Lat Lng Location Coordinates</button> </div> <div class="row"> <p id="location"></p> </div> </div> <script> var locationElement = document.getElementById("location"); function getLatLong() { // using the JavaScript GeoLocation API // to get current position of the user // if checks for support of geolocation API if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( displayLatLong, displayError); } else { locationElement.innerHTML = "JavaScript Geolocation API is not supported by this browser."; } } /** * displays the latitude and longitude from the current position * coordinates returned by the geolocation api. */ function displayLatLong(currentPosition) { locationElement.innerHTML = "Latitude: " + currentPosition.coords.latitude + "<br>Longitude: " + currentPosition.coords.longitude; } /** * displays error based on the error code received from the * JavaScript geolocation API */ function displayError(error) { switch (error.code) { case error.PERMISSION_DENIED: locationElement.innerHTML = "Permission denied by user to get location." break; case error.POSITION_UNAVAILABLE: locationElement.innerHTML = "Location position unavailable." break; case error.TIMEOUT: locationElement.innerHTML = "User location request timed out." break; case error.UNKNOWN_ERROR: locationElement.innerHTML = "Unknown error in getting location." break; } } </script>
</body>
</html>
</code></pre>
<p><img loading="lazy" class="alignnone size-large wp-image-19347" src="https://phppot.com/wp-content/uploads/2022/09/get-user-location-browser-output-550x233.jpg" alt="get user location browser output" width="550" height="233" srcset="https://phppot.com/wp-content/uploads/2022/09/get-user-location-browser-output-550x233.jpg 550w, https://phppot.com/wp-content/uploads/20...00x127.jpg 300w, https://phppot.com/wp-content/uploads/20...68x326.jpg 768w, https://phppot.com/wp-content/uploads/20...output.jpg 1000w" sizes="(max-width: 550px) 100vw, 550px"></p>
<p>In the above example script, we have a function for handing errors. It is important to include the function when getting user location via browser. Because, by default, the user’s permission settings will be disabled.</p>
<p>So most of the times, when this script is invoked, we will get errors. So we should have this handler declared and passed as a callback to the getCurrentPosition function. On error, JavaScript will call this error handler.</p>
<h3>Geolocation API’s Output</h3>
<p>Following is the output format returned by the JavaScript geolocation API. We will be predominantly using latitude and longitude from the result. ‘speed’ may be used when getting dynamic location of the user. We will be seeing about that also at the end of this tutorial.</p>
<pre class="prettyprint"><code>{ coords = { latitude: 30.123456, longitude: 80.0253546, altitude: null, accuracy: 49, altitudeAccuracy: null, heading: null, speed: null, }, timestamp: 1231234897623
}
</code></pre>
<p><a class="demo" href="https://phppot.com/demo/get-user-location-browser-javascript/">View Demo</a></p>
<h2>User location by Geocoding</h2>
<p>We can <a href="https://phppot.com/php/how-to-get-current-location-using-google-map-javascript-api/">get the user’s location</a> by passing the latitude and longitude like below. There are many different service providers available and below is an example using Google APIs.</p>
<pre class="prettyprint"><code class="language-javascript">const lookup = position => { const { latitude, longitude } = position.coords; fetch(`http://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}`) .then(response => response.json()) .then(data => console.log(data)); //
}
</code></pre>
<h2></h2>
<h2>Get dynamic user location from browser using watchPosition()</h2>
<p>Here is an interesting part of the tutorial. How will get you a user’s dynamic location, that is when he is on the move.</p>
<p>We should use an another function of GeoLocation API to get dynamic location coordinates on the move. The function <em>watchPosition()</em> is used to do this via JavaScript.</p>
<p class="p1">To test this script, run it in a mobile browser while moving in a vehicle to get user’s dynamic location.</p>
<p>I have presented the code part that is of relevance below. You can get the complete script from the project zip, it’s free to download below.</p>
<pre class="prettyprint"><code class="language-javascript">var locationElement = document.getElementById("location"); function getLatLong() { // note the usage of watchPosition, this is the difference // this returns the dynamic user position from browser if (navigator.geolocation) { navigator.geolocation.watchPosition(displayLatLong, displayError); } else { locationElement.innerHTML = "JavaScript Geolocation API is not supported by this browser."; } }
</code></pre>
<p><a class="demo" href="https://phppot.com/demo/get-user-location-browser-javascript/">View Demo</a> <a class="download" href="https://phppot.com/downloads/javascript/get-user-location-browser-javascript.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/javascript/get-user-location-browser-javascript/#top" class="top">↑ Back to Top</a> </p>
</div>
https://www.sickgaming.net/blog/2022/09/...avascript/