phpwordpresslocationweather

Show weather based on users location


I am using a code that changes my wordpress website's background according to the Yahoo API URL I inserted. Is there anyway to make it automatically show the Visitors weather without any databases? I have though of using Google's API but I am a novice in programming and dont know how to implement it into my website. Please help! The code can be viewed here: http://css-tricks.com/using-weather-data-to-change-your-websites-apperance-through-php-and-css/

Please be thorough because I am new to PHP Thanks!


Solution

  • This will get a user's zip code from their IP address using the open-source IP2Coordinates service from the Data Science Toolkit.

    There are more accurate Geo-location APIs out there, but this one is absolutely free and dead simple to use. If I were developing this on a production site, I'd use HTML5 Geolocation as my primary method with a fallback to a better IP geolocator, like Max Mind.

    Note that this will only work for US users of your site. You should probably pass more detailed data to one of the other Yahoo place APIs to get one of their WOEIDs to use (or pick a different weather API).

    Here is the code for you. Put this right after the <?php tag in your sample code. Once you're sure it's working, comment out all the lines that begin with print.

    //Get the user's IP address
    $user_ip = $_SERVER['REMOTE_ADDR'];
    //The Data Science Toolkit URL
    $url = 'http://www.datasciencetoolkit.org/ip2coordinates/';
    //Find the user's location from their IP. 
    //*** You need the get_data function from the sample code
    $raw_geocode = json_decode( get_data( $url . $user_ip) );
    //Check if the user is in the US
    if ('US' === $raw_geocode->$user_ip->country_code) {
      //If yes, store their zip code in a variable, and print it
      $zip_code = $raw_geocode->$user_ip->postal_code;
      printf('<p>Your zip code is: %s</p>', $raw_geocode->$user_ip->postal_code);
    } else {
      //If the user isn't in the US, set a sip code that will work.
      $zip_code = '97211';
      //and print an error
      printf('<p>Sorry, this app does not work in %s.</p>', $raw_geocode->$user_ip->country_name);
    }
    
    //Print the raw data for debugging.
    printf('<pre>%s</pre>', print_r($raw_geocode, true));
    

    Now change the line in the sample code that begins with $data = to this:

    $data = get_data("http://weather.yahooapis.com/forecastrss?p={$zip_code}&u=f");