How to get visitors location like country and city
One popular option is the IP Geolocation API, which allows you to obtain geolocation information based on the user's IP address.It can be used for getting user details. Here's an example of how you can use the this API:
<main> <div class="row"> <section class="col-md-4" aria-labelledby="gettingStartedTitle"> <h2 id="gettingStartedTitle">User Location and IP</h2> <p id="IP"></p> <p id="City"></p> <p id="Country"></p> <p id="currency"></p> <p id="timezone"></p> </section> </div> </main> <script> fetch('https://ipapi.co/json/') .then(response => response.json()) .then(data => { const city = data.city; console.log(data); $('#IP').html("IP Address: " + data.ip); $('#City').html("city: " + data.city); $('#Country').html("Country: " + data.country_name); $('#currency').html("currency: " + data.currency); $('#timezone').html("timezone: " + data.timezone); }) </script>
Now run the application and check the console tab after inspect element. You will be able to see following details
So, this is how to get visitors location like country and city. And also we can get the user's ip address if we need.
In the code above, we use the IP Geolocation API provided by ipapi.co. The API endpoint 'https://ipapi.co/json/' returns JSON data containing geolocation information based on the user's IP address. We can extract the city information from the response and log it to the console or user it wherever we want .
One thing to be noted here is IP Geolocation api can have usage restriction for free quota . So don't forget to check the terms of usage and limits. And also results can vary in case of use of vpn's.