Change site address based on location

My company has a few different domains, the most simple being a .com to .ca site. How can we create a system that changes the domain based on the users location. For example: if a visitor from the US finds our .ca site on google, how can I redirect them to .com instead?

Thanks!

Related posts

Leave a Reply

1 comment

  1. Maybe using html5 geolocation with google maps api and window.location.replace to redirect could be a solution.

     window.onload = function () {
       if (navigator.geolocation) {
           navigator.geolocation.getCurrentPosition(fnPosition);
       }
    }
    function fnPosition(position) {
       var lat = position.coords.latitude;
       var long = position.coords.longitude;
       checkCountry(lat,long);
    }
    
    function checkCountry(lat,long) {
       var country = {};
       var latlng = new google.maps.LatLng(lat, long);
       geocoder = new google.maps.Geocoder();
       geocoder.geocode({'latLng': latlng}, function(results) {
           if (results[1]) {
               for (var i=0; i<results[0].address_components.length; i++) {
                   for (var b=0;b<results[0].address_components[i].types.length;b++) {
                       if (results[0].address_components[i].types[b] == "country") {
                           country =results[0].address_components[i];
                           break;
                       }
                   }
               }
           }
           fnRedirect(country);
       });
    }
    
    function fnRedirect(country) {
       switch(country.short_name) {
           case 'CA':
     // some window window.location.replace(...)
     break;
     default:
     // whatever
    } 
    }
    

    I used this example to get the information from the location here

    In php, you can get the location based on the ip.

    $ip = $_SERVER['REMOTE_ADDR'];
    $details = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));
    switch ($details->country) {
        case 'CA':
            header('Location: http://www.example.com/');
        exit;
            break;
    
        default:
            #whatever
            break;
     }
    

    PHP Example here