Get a user's State with Geolocation

http://stackoverflow.com/q/6320674/154877

by Alex Azuero

HTML

<div id="wrap">
    <header>
        <h1>I reckon you're in: <em>&hellip;</em></h1>
        <p class="how"><span>Based on&hellip;</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>

CSS

body { color:#222; background:#eee; text-align:center; font:12px/1.4 'segoe ui', sans-serif; }
h1 { text-align:left; margin:.25em 0; font:400 2em/1.6 'myriad pro', sans-serif; }
h1 em { display:block; font-weight:700; text-align:center; }
p.how { margin:0; padding:2em 0 1em; }
pre { color:#393; word-wrap:break-word; }
footer { color:#999; font-style:italic; padding:2em 0 0; } footer a { color:#666; } footer a:hover { color:#333; }
#wrap { width:500px; margin:1em auto; padding:2em; background:#fff; box-shadow:0 .25em 1em rgba(0,0,0,.25); }

JavaScript

// 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(); });
}