Skip to main content

How to detect your website user's location using javascript

Getting Website vistor's location in Js

Hi there,in today's tutorial i am going to show you how you can get your Visitor's location using JavaScript
Detecting the location of your website’s users is useful for a variety of reasons.
You might, for instance, want to display different content, perhaps in different languages for people from different countries, or display targeted information to visitors from different locations,maybe to show them ads based on their location and much more. Whatever your reasons might be, you have two options:
  1. The Geolocation API and
  2. IP address lookup

The geolocation API

It is a new feature in HTML5 that allows a web page’s visitor to share their location with you if they so choose to(the choice is theirs to make).
When you try to retrieve the location using this API, a prompt is being displayed to the user, asking them if they’d like to share their location with your website.
Well, this obviously means that you won’t get the location of the user ,if the user decides not to share their location with you.
Also it only works on secure servers (https) and is not supported on Internet Explorer 10 and below, nor OperaMini.The output from the code only gives us the coordinates. What if you need the actual location, or get the address in words? We’ll talk about it but first lets look at IP address lookup.

IP address lookup

An IP address lookup is another way to get the location of your visitor,it is like a code assigned to computers ,every computer has a unique IP address which are different from other IP addresses of other computers.
We usually use public IP lookup services/APIs for this option. Some of these are paid services and some are free.Examples include IP Geolocation API, IPinfo,IPstack and GEOIP DB. They provide the data in various formats as well, such as JSON, XML and CSV. To get a good understanding of how to use this services, read their documentation.
But in my own case,i'd be using ipstack
ipstack.com offers a powerful, real-time IP to geolocation API capable of looking up accurate location data and assessing security threats originating from risky IP addresses. Results are delivered within milliseconds in JSON or XML format. Using the ipstack API you will be able to locate website visitors at first glance and adjust your user experience and application accordingly.
The ipstack API is being used by thousands of developers and corporates worldwide to know where the visitors are coming from and change the content based on their location.
The ipstack database and API is integrated with many large ISPs worldwide to get the latest information about new and existing IP ranges and so provides accurate information. Ipstack is integrated with multiple channels delivering real-time IP data, which is why the database used by the ipstack API is updated regularly, with up to 24 database updates per day.
But first you need to sign up for their free plan Once you sign up, you will get your free API access key, as shown below.

Let's test requester lookup.
Open your browser and enter http://api.ipstack.com/check?access_key=XXX. Replace XXX with your API access key. You will get the JSON response as shown below.

Using jQuery

The following example demonstrates the standard lookup request using jQuery.
// set endpoint and your access key
var ip = '134.201.250.155'
var access_key = 'YOUR_ACCESS_KEY';

// get the API result via jQuery.ajax
$.ajax({
url: 'http://api.ipstack.com/' + ip + '?access_key=' + access_key,
dataType: 'jsonp',
success: function(json) {

// output the "capital" object inside "location"
alert(json.location.capital);

} });
After executing the above request, you will get the following JSON response.
 {
        "ip": "134.201.250.155",
        "hostname": "134.201.250.155",
        "type": "ipv4",
        "continent_code": "NA",
        "continent_name": "North America",
        "country_code": "US",
        "country_name": "United States",
        "region_code": "CA",
        "region_name": "California",
        "city": "Los Angeles",
        "zip": "90013",
        "latitude": 34.0453,
        "longitude": -118.2413,
        "location": {
        "geoname_id": 5368361,
        "capital": "Washington D.C.",
        "languages": [
        {
            "code": "en",
            "name": "English",
           
            "native": "English"
        }
    ]
        "country_flag": "https://assets.ipstack.com/images/assets/flags_svg/us.svg"
        "country_flag_emoji": "πŸ‡ΊπŸ‡Έ",
        "country_flag_emoji_unicode": "U+1F1FA U+1F1F8",
       "calling_code": "1",
        "is_eu": false
    },
        "time_zone": {
        "id": "America/Los_Angeles",
        "current_time": "2018-03-29T07:35:08-07:00",
        "gmt_offset": -25200,
        "code": "PDT",
        "is_daylight_saving": true
    },
        "currency": {
        "code": "USD",
        "name": "US Dollar",
        "plural": "US dollars",
        "symbol": "$",
        "symbol_native": "$"
    },
        "connection": {
        "asn": 25876,
        "isp": "Los Angeles Department of Water & Power"
    },
        "security": {
        "is_proxy": false,
        "proxy_type": null,
        "is_crawler": false,
        "crawler_name": null,
        "crawler_type": null,
        "is_tor": false,
        "threat_level": "low",
        "threat_types": null
    }
}
  
Hope this gives you an idea of the kind of data websites can collect from you ,i know some of you are surprised to see what type of data we could get.

Thus, you can use ipstack API to know visitors IP addresses easily and quickly.
Visit ipstack documentation for detailed information.

Comments

Popular posts from this blog

how to create Session cookies in php

What are Session cookies Session cookies , also known as ' temporary cookies ', help websites recognise users and the information provided when they navigate through a website. Session cookies only retain information about a user's activities for as long as they are on the website. Once the web browser is closed, the cookies are deleted. These are commonly used on shopping websites or e-commerce websites.We have already talked about cookies, Learn all about cookies . Cookies are the reason Trednix.com remembers your username between visits and the reason you don’t necessarily need to log in to your Hotmail account every time you open your browser. Cookie data typically contains a short set of information regarding when you last accessed a site, an ID number, and, potentially, information about your visit. Let’s now look at the basic syntax used to create a cookie. <?php setcookie(cookie_name, cookie_value, [expiry_time], [cookie_path], [domain], [secure], [httponl...

How to create a search engine

How to create a search engine I am going to teach you how we can create a search engine using Google API . You can add more styles to it ,because I'd be creating a simple looking search engine. Google Custom Search API are wonderful tools to create some awesome search engine like tools. Also if you want to add a search option to your website and customize the look and feel of your search results, Google Custom Search API serve best to you. I have created a Real Time Search engine (I call it real time as it search as you type). I am really impressed by the speed/response of Google Search API. In order to use Google Search API, you have to first generate a Key for you. Go to following page and signup your self for the Key. Sign up for Google API Key https://code.google.com/apis/ajaxsearch/signup.html Next step is to include the Google Search API javascript. Don’t forget to mention your key in the below code. <script src="http://www.google.com/jsapi?key=YOURKEY...

All you need to know about web cookies

Hello guys ,we all know as a web developers we need cookies ,i am not talking about the normal cookies , I'm talking of web cookies , it's a really good cookie for us πŸ˜‹.All dynamic website uses cookies in one way or the other and we would be talking about all the types of cookies websites uses. What are cookies? Cookies are small text files placed on a user’s computer (or smartphone), which are commonly used to collect personal data. Most website operators place cookies on the browser or hard drive of their user's computer. Cookies can gather information about the use of a website or enable the website to recognise the user as an existing customer when they return to the website at a later date. This file is neither a virus nor spyware. The law protects website users and lets them opt-out from the use of cookies on their website browser. What are the benefits of cookies? Cookies are used to make the user's web experience faster, convenient and personalised. ...