Show weather based on users location

user1373771 picture user1373771 · Aug 26, 2012 · Viewed 12.1k times · Source

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!

Answer

user6299091 picture user6299091 · May 6, 2016

You'll need an API for mapping visitors IP address to location ( ipapi.co ) and another one to get weather forecast for the location ( openweathermap.org ). The code below is for php (server side) :

# Part 1 (get latitude & longitude)
$ip = '1.2.3.4';
$api_1 = 'https://ipapi.co/' . $ip . '/latlong/';
$location = file_get_contents($api_1);
$point = explode(",", $location);

# Part 2 (get weather forecast)
$api_2 = 'http://api.openweathermap.org/data/2.5/weather?lat=' . $point[0] . '&lon=' . $point[1] . '&appid=API_KEY';
$weather = file_get_contents($api_2);