0

I have searched for an answer for this, but has proven to be a bit tricky...

On my html page I have a dropdown menu with a list of all the countries.

<option value="AF">Afghanistan</option>
<option value="AX">Åland Islands</option>
<option value="AL">Albania</option>
<option value="DZ">Algeria</option>

My question is that is there a way to default the selected option according to where the site is visited from? (i.e. If I am visiting the site from South Africa, it would automatically change to South Africa

imieliei
  • 19
  • 5
  • 1
    Yes, but you'll likely need a server side scripting language for that. – Pekka Nov 20 '12 at 13:46
  • Like PHP? Would you know how to do that? – imieliei Nov 20 '12 at 13:58
  • See e.g. [best way to detect country / location of visitor?](http://stackoverflow.com/q/4179000) and many duplicates when searching `php detect country`... once you have the (approximate) country code, setting the default is a breeze. – Pekka Nov 20 '12 at 14:03

1 Answers1

1

There are some free services out there that let you make country and ip-based geolocalization from the client-side.

I've used the wipmania free JSONP service, it's really simple to use:

<script type="text/javascript">
  // plain JavaScript example
  function jsonpCallback(data) { 
    alert('Latitude: ' + data.latitude + 
          '\nLongitude: ' + data.longitude + 
          '\nCountry: ' + data.address.country); 
  }
</script>
<script src="http://api.wipmania.com/jsonp?callback=jsonpCallback"
        type="text/javascript"></script>

Or if you use a framework that supports JSONP, like jQuery you can:

// jQuery example
$.getJSON('http://api.wipmania.com/jsonp?callback=?', function (data) { 
  alert('Latitude: ' + data.latitude + 
        '\nLongitude: ' + data.longitude + 
        '\nCountry: ' + data.address.country); 
});

Check the above snippet running here.

Raul Valverde
  • 587
  • 4
  • 11