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
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>
You can use a web service that supports JSONP, such as my service http://ipinfo.io. It'll provide you with the client's IP address, hostname, geolocation information and network owner. Here's an example of it in action with jQuery:
$.get("http://ipinfo.io", function(response) {
$("#ip").html(response.ip);
$("#address").html(response.city + ", " + response.region);
}, "jsonp");
Here's a more detailed JSFiddle example that also prints out the full response information, so you can see all of the available details: http://jsfiddle.net/zK5FN/2/
The HTML5 Geolocation API allows you to get a user's Latitude/Longitude with some JavaScript (if the browser is compatible, and if the user allows access to his/her location).
You can then reverse-geocode the location to get an address, there are several free reverse-geocoding services other than Google's API.
However, if you don't need accurate location, and if you want all your users to take advantage of the feature (no matter the browser), and if you don't want to ask them whether they allow your site to have their location, I would recommend to use your user's IP to get the location.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With