google-mapsgeolocationgoogle-gears

Is there a way to get the users location without having the user install Google Gears?


I don't want to have the user install Google Gears so I can show him his guessed location. Is there a way to get the location without having to use Google Gears?

I have found http://www.wipmania.com/de/blog/google-geolocation-api/ but it does not offer an example.


Solution

  • This is typically called IP Geolocation.

    An example is here.

    The thing is, most sites (if you plan on calling this as a web service) will charge you for it. Otherwise, throw together a web service that grabs a geolocation page, parses it for the address, and returns that piece of information.

    In PHP, this seems to work pretty well:

    <?php
     if(isset($_GET["ip"])){
       echo geolocate($_GET["ip"]);
     }
    
     function geolocate($ip){
       $raw_html = file_get_contents("http://www.geody.com/geoip.php?ip=$ip");
       if(preg_match('/Location:(.*)/',$raw_html,$matches)){
         $location_raw = $matches[1];
    
         //Get rid of pesky HTML tags
         $location = preg_replace("/<[^>]*>/","",$location_raw);
         return $location;
       }else{
         return "ERROR";
       }
     }