Find user location using jQuery/JS (without google geolocation api)?

user1530249 picture user1530249 · Jan 6, 2013 · Viewed 85.3k times · Source

Is there a way to find a clients location on a website using just jQuery. For example, if a user comes to my site, how could I find out what their approximate location is just using jQuery. For example, if a user came from San Francisco CA it would have some type identifier to let me know the user came from San Francisco CA. I wouldn't really need their exact location just the county or general area of origin.

edit: How is the information on http://flourishworks-webutils.appspot.com/req generated?

Thanks

Answer

Durgesh Pandey picture Durgesh Pandey · Sep 24, 2015

To get the client IP address & country name in jQuery:

$.getJSON("http://freegeoip.net/json/", function(data) {
    var country_code = data.country_code;
    var country = data.country_name;
    var ip = data.ip;
    var time_zone = data.time_zone;
    var latitude = data.latitude;
    var longitude = data.longitude;

    alert("Country Code: " + country_code);
    alert("Country Name: " + country);
    alert("IP: " + ip); 
    alert("Time Zone: " + time_zone);
    alert("Latitude: " + latitude);
    alert("Longitude: " + longitude);   
});

$.get("http://freegeoip.net/json/", function (response) {
    $("#ip").html("IP: " + response.ip);
    $("#address").html("Location: " + response.city + ", " + response.region_name);
    $("#details").html(JSON.stringify(response, null, 4));
}, "jsonp");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h3>Client side IP geolocation using <a href="http://freegeoip.net">freegeoip.net</a></h3>

<hr/>
<div id="ip"></div>
<div id="address"></div>
<hr/>Full response: <pre id="details"></pre>