HOW TO GET A USERS LOCATION USING JAVASCRIPT
Tags: javascript, webdev, programming, tutorial
Published: 2023-02-14 13:12:39


<p class="graf graf--p">Detecting the location of a user’s device has become a significant way to make users get access to different contents from the same website or application.</p>
<p class="graf graf--p">The contents displayed in the application could vary according to the location it detects to provide personalized content for each specified user.</p>
<p class="graf graf--p">By getting a user’s location, you can determine his country’s currency, language, etc., and then use the information to provide contents that fit that area without breaching their privacy laws.</p>
<p class="graf graf--p">For example, an application might need to detect the user’s location to know which language to display to its user, or it may need to suggest nearby gas stations or restaurants for its user, and it can only do this by detecting the exact location of its user at that moment.</p>
<p class="graf graf--p"><strong class="markup--strong markup--p-strong">There are different ways to detect a user’s location using JavaScript</strong></p>

<ul class="postList">
 	<li class="graf graf--li">Geolocation API
Get current position function
watchPosition function
clearWatch function</li>
 	<li class="graf graf--li">Using Ip geolocation APIs</li>
 	<li class="graf graf--li">Using google maps API</li>
</ul>
<h3 class="graf graf--h3">Geolocation API</h3>
<p class="graf graf--p">The javaScript geolocation API is one of the various means of accessing a user’s geographical position.</p>
<p class="graf graf--p">This API provides access to a device’s location using its GPS, Wi-Fi, IP address, etc.</p>
<p class="graf graf--p">But for this to work, the API launches a request to access the user’s location. If the user grants permission, you’ll gain access to all data associated with its location, like its longitude, latitude, speed, etc.</p>
<p class="graf graf--p">You can access the geolocation API by calling window.navigator.geolocation. This grants the app or website access to the location of the device.</p>

<pre class="graf graf--pre graf--preV2" spellcheck="false" data-code-block-mode="1" data-code-block-lang="javascript"><span class="pre--content"><span class="hljs-keyword">var</span> x = <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">getElementById</span>(<span class="hljs-string">"demo"</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">getLocation</span>() {
<span class="hljs-keyword">if</span> (navigator.<span class="hljs-property">geolocation</span>) {
navigator.<span class="hljs-property">geolocation</span>.<span class="hljs-title function_">getCurrentPosition</span>(showPosition);
} <span class="hljs-keyword">else</span> {
x.<span class="hljs-property">innerHTML</span> = <span class="hljs-string">"Geolocation is not supported by this browser."</span>;
}
}
<span class="hljs-keyword">function</span> <span class="hljs-title function_">showPosition</span>(<span class="hljs-params">position</span>) {
x.<span class="hljs-property">innerHTML</span> = <span class="hljs-string">"Latitude: "</span> + position.<span class="hljs-property">coords</span>.<span class="hljs-property">latitude</span> +
<span class="hljs-string">"&lt;br&gt;Longitude: "</span> + position.<span class="hljs-property">coords</span>.<span class="hljs-property">longitude</span>;
}</span></pre>
<p class="graf graf--p">This code checks if the browser supports geolocation. If supported, it runs the get current position method else; it displays an error message to the user.</p>
<p class="graf graf--p">If the getCurrent position method is successful, it writes the coordinates of the object in the manner specified in the parameter and then outputs it in the HTML document.</p>
<p class="graf graf--p">Different methods in the geolocation API can be used to determine the user’s location.</p>

<ul class="postList">
 	<li class="graf graf--li"><strong class="markup--strong markup--li-strong">Get current position function</strong></li>
 	<li class="graf graf--li">The getCurrentPosition method mainly returns the longitude and latitude of a user’s position.</li>
</ul>
<pre class="graf graf--pre graf--preV2" spellcheck="false" data-code-block-mode="1" data-code-block-lang="javascript"><span class="pre--content"><span class="hljs-comment">// Write code here</span>
<span class="hljs-keyword">const</span> <span class="hljs-title function_">successMessage</span> = (<span class="hljs-params">position</span>) =&gt; {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(position);
};
<span class="hljs-keyword">const</span> <span class="hljs-title function_">errorMessage</span> = (<span class="hljs-params">error</span>) =&gt; {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(error);
};
navigator.<span class="hljs-property">geolocation</span>.<span class="hljs-title function_">getCurrentPosition</span>(successMessage, errorMessage);</span></pre>
<p class="graf graf--p">When you run this code, you’ll get a popup in your browser telling you to either allow or block the script from accessing your location.</p>
<p class="graf graf--p">When you click on allow, open up your developer console and see that the successMessage returns the device’s coordinates and timestamp.</p>
<p class="graf graf--p">It should be something like this:</p>

<pre class="graf graf--pre graf--preV2" spellcheck="false" data-code-block-mode="1" data-code-block-lang="yaml"><span class="pre--content"><span class="hljs-number">1</span><span class="hljs-string">.</span> <span class="hljs-string">GeolocationPosition</span> {<span class="hljs-attr">coords:</span> <span class="hljs-string">GeolocationCoordinates</span>, <span class="hljs-attr">timestamp:</span> <span class="hljs-number">1674050273983</span>}
  <span class="hljs-attr">1. coords:</span> <span class="hljs-string">GeolocationCoordinates</span>
    <span class="hljs-attr">1. accuracy:</span> <span class="hljs-number">8636.326773021921</span>
    <span class="hljs-attr">2. altitude:</span> <span class="hljs-literal">null</span>
    <span class="hljs-attr">3. altitudeAccuracy:</span> <span class="hljs-literal">null</span>
    <span class="hljs-attr">4. heading:</span> <span class="hljs-literal">null</span>
    <span class="hljs-attr">5. latitude:</span> <span class="hljs-number">6.5568768</span>
    <span class="hljs-attr">6. longitude:</span> <span class="hljs-number">3.3456128</span>
    <span class="hljs-attr">7. speed:</span> <span class="hljs-literal">null</span>
    <span class="hljs-number">8</span><span class="hljs-string">.</span> [[<span class="hljs-string">Prototype</span>]]<span class="hljs-string">:</span> <span class="hljs-string">GeolocationCoordinates</span>
<span class="hljs-attr">2. timestamp:</span> <span class="hljs-number">1674050273983</span>
<span class="hljs-number">3</span><span class="hljs-string">.</span> [[<span class="hljs-string">Prototype</span>]]<span class="hljs-string">:</span> <span class="hljs-string">GeolocationPosition</span></span></pre>
<ul class="postList">
 	<li class="graf graf--li"><strong class="markup--strong markup--li-strong">watchPosition function</strong></li>
 	<li class="graf graf--li">The watchPosition method is another exciting way as it returns the current position of its user and continues to update the position even as the user moves e.g. tracking device in a vehicle.</li>
 	<li class="graf graf--li">This method does this by installing a handler that is called whenever the position of the user’s device changes.</li>
 	<li class="graf graf--li">Below is the syntax of the code</li>
</ul>
<p class="graf graf--p"><code class="markup--code markup--p-code">const id = navigator.geolocation.watchPosition(successMessage, errorMessage);</code></p>

<ul class="postList">
 	<li class="graf graf--li"><strong class="markup--strong markup--li-strong">clearWatch function</strong></li>
 	<li class="graf graf--li">This method puts a stop to the watchPosition method.</li>
 	<li class="graf graf--li">By just calling its function and inputting the id of the watchPosition method you’ll be able to stop the watchPosition from functioning.</li>
 	<li class="graf graf--li">Below is its code syntax:</li>
</ul>
<p class="graf graf--p"><code class="markup--code markup--p-code">navigator.geolocation.clearWatch(id);</code></p>

<h4 class="graf graf--h4">Using google maps API</h4>
<p class="graf graf--p">Using the API provided by google maps, developers can now display user location in google Maps.</p>
<p class="graf graf--p">To use this method, you must first get an API key from google. After getting the key, you can now use the Google Maps API to plot the map using the user’s location.</p>

<pre class="graf graf--pre graf--preV2" spellcheck="false" data-code-block-mode="2" data-code-block-lang="javascript"><span class="pre--content">&lt;html lang=<span class="hljs-string">"en"</span>&gt;
<span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Document<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span></span>
<span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"locationInfo"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="language-javascript">
<span class="hljs-keyword">var</span> div = <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">getElementById</span>(<span class="hljs-string">"locationInfo"</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">getLocationInfo</span>() {
<span class="hljs-keyword">if</span> (navigator.<span class="hljs-property">geolocation</span>) {
navigator.<span class="hljs-property">geolocation</span>.<span class="hljs-title function_">getCurrentPosition</span>(showPosition, <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);
} <span class="hljs-keyword">else</span> {
div.<span class="hljs-property">innerHTML</span> = <span class="hljs-string">"The Browser Does not Support Geolocation"</span>;
}
}
<span class="hljs-keyword">function</span> <span class="hljs-title function_">showPosition</span>(<span class="hljs-params">position</span>) {
<span class="hljs-keyword">var</span> lat = position.<span class="hljs-property">coords</span>.<span class="hljs-property">latitude</span>;
<span class="hljs-keyword">var</span> lon = position.<span class="hljs-property">coords</span>.<span class="hljs-property">longitude</span>;
<span class="hljs-comment">// You need to enter your API Key here</span>
<span class="hljs-keyword">var</span> api_key = <span class="hljs-string">""</span>;
<span class="hljs-keyword">var</span> img_url = <span class="hljs-string">`https://maps.googleapis.com/maps/api/staticmap?center=<span class="hljs-subst">${lat}</span>,<span class="hljs-subst">${lon}</span>&amp;zoom=14&amp;size=400x300&amp;sensor=false&amp;key=<span class="hljs-subst">${api_key}</span>`</span>;
div.<span class="hljs-property">innerHTML</span> = <span class="hljs-string">`&lt;img src='<span class="hljs-subst">${img_url}</span>'&gt;`</span>;
}
<span class="hljs-title function_">getLocationInfo</span>();
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span></span></span></pre>
<p class="graf graf--p">In this code, you use the geolocation function to get the current position of your device and then pass a parameter inside the function if it returns TRUE.</p>
<p class="graf graf--p">The showPosition parameter passed into the getCurrent Position function collects the latitude and longitude coordinates of the device.</p>
<p class="graf graf--p">Immediately after that, you create a variable called API key and then pass your google maps API key inside as a string. Then you create a variable containing the URL of your IMG from the API itself.</p>
<p class="graf graf--p">In the end, you make your div element display the URL, which shows the position of the user’s device.</p>

<h3 class="graf graf--h3">Ip geolocation APIs</h3>
<p class="graf graf--p">Another way developers can identify a user’s location is by using API services available on the internet, Either free or paid.
<strong class="markup--strong markup--p-strong">Here is a list of websites you can get geolocation APIs</strong></p>

<ol class="postList">
 	<li class="graf graf--li"><a class="markup--anchor markup--li-anchor" href="https://www.softwaretestinghelp.com/best-ip-geolocation-api/#1_ipstack_Recommended" target="_blank" rel="noreferrer nofollow noopener noopener" data-href="https://www.softwaretestinghelp.com/best-ip-geolocation-api/#1_ipstack_Recommended">ipstack</a></li>
 	<li class="graf graf--li"><a class="markup--anchor markup--li-anchor" href="https://www.softwaretestinghelp.com/best-ip-geolocation-api/#2_Abstract_API" target="_blank" rel="noreferrer nofollow noopener noopener" data-href="https://www.softwaretestinghelp.com/best-ip-geolocation-api/#2_Abstract_API">Abstract API</a></li>
 	<li class="graf graf--li"><a class="markup--anchor markup--li-anchor" href="https://www.softwaretestinghelp.com/best-ip-geolocation-api/#3_Maxmind" target="_blank" rel="noreferrer nofollow noopener noopener" data-href="https://www.softwaretestinghelp.com/best-ip-geolocation-api/#3_Maxmind">Maxmind</a></li>
 	<li class="graf graf--li"><a class="markup--anchor markup--li-anchor" href="https://www.softwaretestinghelp.com/best-ip-geolocation-api/#4_ipdata" target="_blank" rel="noreferrer nofollow noopener noopener" data-href="https://www.softwaretestinghelp.com/best-ip-geolocation-api/#4_ipdata">ipdata</a></li>
 	<li class="graf graf--li"><a class="markup--anchor markup--li-anchor" href="https://www.softwaretestinghelp.com/best-ip-geolocation-api/#5_ipgeolocationio" target="_blank" rel="noreferrer nofollow noopener noopener" data-href="https://www.softwaretestinghelp.com/best-ip-geolocation-api/#5_ipgeolocationio">ipgeolocation.io</a></li>
 	<li class="graf graf--li"><a class="markup--anchor markup--li-anchor" href="https://www.softwaretestinghelp.com/best-ip-geolocation-api/#6_IP-API" target="_blank" rel="noreferrer nofollow noopener noopener" data-href="https://www.softwaretestinghelp.com/best-ip-geolocation-api/#6_IP-API">IP-API</a></li>
 	<li class="graf graf--li"><a class="markup--anchor markup--li-anchor" href="https://www.softwaretestinghelp.com/best-ip-geolocation-api/#7_DB-API" target="_blank" rel="noreferrer nofollow noopener noopener" data-href="https://www.softwaretestinghelp.com/best-ip-geolocation-api/#7_DB-API">DB-API</a></li>
 	<li class="graf graf--li"><a class="markup--anchor markup--li-anchor" href="https://www.softwaretestinghelp.com/best-ip-geolocation-api/#8_IP2Location" target="_blank" rel="noreferrer nofollow noopener noopener" data-href="https://www.softwaretestinghelp.com/best-ip-geolocation-api/#8_IP2Location">IP2Location</a></li>
 	<li class="graf graf--li"><a class="markup--anchor markup--li-anchor" href="https://www.softwaretestinghelp.com/best-ip-geolocation-api/#9_ipinfo" target="_blank" rel="noreferrer nofollow noopener noopener" data-href="https://www.softwaretestinghelp.com/best-ip-geolocation-api/#9_ipinfo">ipinfo</a></li>
 	<li class="graf graf--li"><a class="markup--anchor markup--li-anchor" href="https://www.softwaretestinghelp.com/best-ip-geolocation-api/#10_Positionstack" target="_blank" rel="noreferrer nofollow noopener noopener" data-href="https://www.softwaretestinghelp.com/best-ip-geolocation-api/#10_Positionstack">Positionstack</a></li>
</ol>
<p class="graf graf--p">Source: <a class="markup--anchor markup--p-anchor" href="https://www.softwaretestinghelp.com/best-ip-geolocation-api/" target="_blank" rel="noreferrer nofollow noopener noopener" data-href="https://www.softwaretestinghelp.com/best-ip-geolocation-api/">softwareTestingHelp</a></p>

<h3 class="graf graf--h3">Conclusion</h3>
<p class="graf graf--p">In this tutorial, you learned how to use various methods to get a users location like the javascript geolocation API, and Google maps API, which can detect the user’s location via google maps, and also outlined a few websites from which you can get geolocation APIs from.</p>
<p class="graf graf--p">You can use this API to build different apps, like a weather app or even a tracker.</p>

<h3 class="graf graf--h3">Resources:</h3>
<p class="graf graf--p"><a class="markup--anchor markup--p-anchor" href="https://www.codeunderscored.com/how-to-get-a-user-location-using-html-and-javascript/" target="_blank" rel="noreferrer nofollow noopener noopener" data-href="https://www.codeunderscored.com/how-to-get-a-user-location-using-html-and-javascript/">Codeunderscored</a></p>
<p class="graf graf--p"><a class="markup--anchor markup--p-anchor" href="https://www.geoapify.com/how-to-get-user-location-with-javascript" target="_blank" rel="noreferrer nofollow noopener noopener" data-href="https://www.geoapify.com/how-to-get-user-location-with-javascript">Geoapify</a></p>
<p class="graf graf--p"><a class="markup--anchor markup--p-anchor" href="https://www.w3schools.com/html/html5_geolocation.asp" target="_blank" rel="noreferrer nofollow noopener noopener" data-href="https://www.w3schools.com/html/html5_geolocation.asp">W3Schools</a></p>
<p class="graf graf--p"><a class="markup--anchor markup--p-anchor" href="https://www.freecodecamp.org/news/the-junior-developers-guide-to-writing-super-clean-and-readable-code-cd2568e08aae/" target="_blank" rel="noreferrer nofollow noopener noopener" data-href="https://www.freecodecamp.org/news/the-junior-developers-guide-to-writing-super-clean-and-readable-code-cd2568e08aae/">freecodecamp</a></p>
<a href="http://blog.learnhub.africa">LearnHub Blog</a>