<div id="wrap">
<header>
<h1>I reckon you're in: <em>…</em></h1>
<p class="how"><span>Based on…</span> <a id="geo" href="#detect">Use Geolocation API?</a></p>
<pre></pre>
</header>
<footer>This is a code example for the Stack Overflow question <br><a href="http://stackoverflow.com/q/6320674/154877">"Get a user's State with Geolocation"</a></footer>
</div>
// Next 2 vars are just the
var apiurl = 'http://api.ipinfodb.com/v3/ip-city/';
var apikey = 'ee637c133ffbbff0e4f895c81ef12e03cadfc2c0933c54a61a27bd25e515f36f';
$("pre").html("Requesting information...");
$.getJSON(apiurl+'?key=' + apikey + '&format=json&callback=?',
function(data){
$("header h1 em").html(capitalise(data.regionName + ", " + data.countryName + "."));
$("pre").html(JSON.stringify(data));
}
);
$.getJSON("http://jsonip.appspot.com?callback=?",
function(data){
$("p.how span").html("Based on looking up your IP (<code>" + data.ip + "</code>).");
}
);
// Use Geolocation API
$("#geo").click(function(e){
// Prevent the default link action and get rid of it
e.preventDefault(); $(this).remove();
$("pre").html("Requesting information...");
navigator.geolocation.getCurrentPosition(function(pos){
var latlng = pos.coords.latitude + "," + pos.coords.longitude;
var apiurl = 'http://maps.google.com/maps/geo?output=json&sensor=false&q=' + latlng;
var yqlqry = encodeURIComponent('select * from json where url="'+apiurl+'"');
var yqlurl = 'http://query.yahooapis.com/v1/public/yql?q='+yqlqry+'&format=json&callback=?';
$("p.how span").html("Based on reverse geocoding your coordinates (<code>" + latlng + "</code>).");
$.getJSON(yqlurl,
function(data){
var regionName = data.query.results.json.Placemark.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
var countryName = data.query.results.json.Placemark.AddressDetails.Country.CountryName;
$("header h1 em").html(capitalise(regionName + ", " + countryName + "."));
$("pre").html(JSON.stringify(data));
}
);
});
});
function capitalise(str){
return str.toLowerCase().replace(/\b[a-z]/g, function(str){ return str[0].toUpperCase(); });
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.