Detecting the location of your users can be really useful if you want to personalize your user’s experience when they browse through your website. Want to show a uniquely tailored promotion? Want to change the language of your site or design based on where your users are coming from?
Lots of websites today show dynamic content based on the user’s location to provide relevant info, ads or local places. In this article, we’re going to show you how to detect user location using Geolocation API. A pure-JavaScript way without any third-party services to retrieve accurate user location.
Note: As of Chrome 50, the Geolocation API will only work on secure contexts such as HTTPS. If your site is hosted on a non-secure origin (such as HTTP) the requests to get the user’s location will no longer function.
Table of Contents
Features:
- Light Weight.
- Pure Vanilla JavaScript.
- Cross Browser.
- No External Files.
- Fully Customizable.
How To Get User Location (Lat/Long) Using Pure JavaScript?
There are a few easy and understandable steps to achieve your desired functionality using pure Vanilla JavaScript that we are gonna share below. Follow each step perfectly.
HTML:
<p>Click the button to get your coordinates.</p> <button onclick="getLocation()">Try It</button> <p id="demo"></p>
JavaScript:
<script> var x = document.getElementById("demo"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { x.innerHTML = "Geolocation is not supported by this browser."; } } function showPosition(position) { x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude; } </script>
Customization:
No need to customize it. Just copy-paste. Rest edit the code as per comments and need.
Troubleshooting the Errors:
Do it with concentration and patience. Check your alls steps and again and all codes or scripts. If you find any error you can contact us anytime via comment or better via email, We are always here to help you.
Final Words:
That’s all we have. We hope that you liked this article. If you have any problem with this code in your template then feel free to contact us with a full explanation of your problem. We will reply to you as time allows us or If you have any doubts and problems please comment below. We are happy to help you! If you liked this article, Don’t forget to share this with your friends so they can also take benefit from it and leave your precious feedback in our comment form below. Happy development, See you in the next article.
Be the first to write a comment.