Skip to content

Instantly share code, notes, and snippets.

@mikehadlow
Created November 17, 2010 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikehadlow/703237 to your computer and use it in GitHub Desktop.
Save mikehadlow/703237 to your computer and use it in GitHub Desktop.
HTML5 / Google maps api, Get the long name of the current user's coujntry
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Geolocation Demo</title>
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="Geolocation.js" type="text/javascript"></script>
<style type="text/css">
body
{
font-family: arial;
}
li.button
{
display: inline;
background-color: Black;
color: White;
margin: 5px;
padding: 5px;
border-radius: 5px;
}
li.button a
{
color: White;
text-decoration: none;
}
li.selected
{
background-color: Red;
}
</style>
</head>
<body>
<h1>Geolocation Demo</h1>
<ul>
<li class="button"><a id="locateMe" href="#">Locate Me!</a></li>
</ul>
<p id="location"></p>
<script type="text/javascript">
var geoDemo = {
init: function() {
$("#locateMe").click(geoDemo.onLocateMeClick);
},
onLocateMeClick: function() {
geo.getUserCountry(geoDemo.onGetUserCountry);
},
onGetUserCountry: function(country) {
$("#location").html(country);
}
};
$(geoDemo.init);
</script>
</body>
</html>
// requires <script src="http://maps.google.com/maps/api/js?sensor=false"></script>
var geo = {
// returns the user's country, or '' if not available
// callback: function(country) {}
getUserCountry: function(callback) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geo.createCurrentPositionCallback(callback));
}
},
createCurrentPositionCallback: function(callback) {
return function(position) {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
geocoder.geocode({ 'latLng': latlng }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// dig into the results to find the country
for (resultIndex in results) {
var result = results[resultIndex];
for (address_componentIndex in result.address_components) {
var address_component = result.address_components[address_componentIndex];
for (typeIndex in address_component.types) {
var type = address_component.types[typeIndex];
if (type == "country") {
callback(address_component.long_name);
return;
}
}
}
}
}
callback('');
});
}
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment