Weather forecast from IP address
1 min readDec 30, 2016
Recipe to get weather forecast from an IP address
Ingredients
- IP address to location API : ipapi.co (free, no key required)
- Weather API : openweathermap.org (free, but requires key)
Ruby
require 'net/http'
require 'json'$ip = '208.67.222.222'$latlong = Net::HTTP.get(URI('https://ipapi.co/' + $ip + '/latlong/')).split(",")$weather = JSON.parse(Net::HTTP.get(URI('http://api.openweathermap.org/data/2.5/weather?lat='+$latlong[0]+'&lon='+$latlong[1]+'&appid='+$API_KEY)))
Python
from requests import getip = '208.67.222.222'latlong = get('https://ipapi.co/{}/latlong/'.format(ip)).text.split(',')weather = get('http://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&appid=API_KEY'.format(latlong[0], latlong[1])).json()
PHP
$ip = '208.67.222.222';$latlong = explode(",", file_get_contents('https://ipapi.co/' . $ip . '/latlong/'));$weather = file_get_contents('http://api.openweathermap.org/data/2.5/weather?lat=' . $latlong[0] . '&lon=' . $latlong[1] . '&appid=API_KEY');echo $weather;$json = json_decode($weather);
Javascript
// jQuery required for this examplevar ip = '208.67.222.222'$.get('https://ipapi.co/'+ip+'/latlong/', function(response){
var latlong = response.split(',');
console.log(latlong); $.get('http://api.openweathermap.org/data/2.5/weather?lat=' + latlong[0] + '&lon=' + latlong[1] + '&appid=API_KEY', function(wResponse){
console.log(weather);
})
})