Displaying a local weather forecast on your website is an excellent way to personalize user experience. By using IPLocate, you can quickly detect a user's location based on their IP address and retrieve accurate weather data through the OpenWeatherMap API. Here's how you can easily set this up.
First, sign up for both of these free services to get your API keys:
Using Javascript
async function getLocalWeather(iplocate_api_key, openweathermap_api_key) {
// Get location from IP address
const locResponse = await fetch(`https://iplocate.io/api/lookup/?apikey=${iplocate_api_key}`);
const locData = await locResponse.json();
const { latitude, longitude, city } = locData;
// Get weather for the location
const weatherResponse = await fetch(
`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&units=metric&appid=${openweathermap_api_key}`
);
const weatherData = await weatherResponse.json();
console.log(`The current temperature in ${city} is ${weatherData.main.temp}°C.`);
// Use the weather data here.
return weatherData;
}
// --- How to use it: ---
// const iplocateKey = 'YOUR_IPLOCATE_API_KEY';
// const openWeatherKey = 'YOUR_OPENWEATHERMAP_API_KEY';
// getLocalWeather(iplocateKey, openWeatherKey).then(weather => {
// if (weather) {
// console.log("Weather data:", weather);
// // Update your UI here
// }
// });
Using PHP
<?php
function getLocalWeather(string $iplocate_api_key, string $openweathermap_api_key): ?array {
// Get location from IP address
$locJson = file_get_contents("https://iplocate.io/api/lookup/?apikey={$iplocate_api_key}");
$locData = json_decode($locJson, true);
$latitude = $locData['latitude'];
$longitude = $locData['longitude'];
$city = $locData['city'] ?? 'your location';
// Get weather for the location
$weatherUrl = "https://api.openweathermap.org/data/2.5/weather?lat={$latitude}&lon={$longitude}&units=metric&appid={$openweathermap_api_key}";
$weatherJson = file_get_contents($weatherUrl);
$weatherData = json_decode($weatherJson, true);
echo "The current temperature in {$city} is " . $weatherData['main']['temp'] . "°C.\\n";
// Use the weather data here.
return $weatherData;
}
// --- How to use it: ---
// $iplocateKey = 'YOUR_IPLOCATE_API_KEY';
// $openWeatherKey = 'YOUR_OPENWEATHERMAP_API_KEY';
// $weather = getLocalWeather($iplocateKey, $openWeatherKey);
// if ($weather) {
// // Use $weather array here
// }
?>
Using Python
import requests
def get_local_weather(iplocate_api_key: str, openweathermap_api_key: str) -> dict | None:
"""Fetches local weather based on IP address."""
# Get location from IP address
loc_response = requests.get(f"https://iplocate.io/api/lookup/?apikey={iplocate_api_key}")
loc_data = loc_response.json()
latitude = loc_data.get('latitude')
longitude = loc_data.get('longitude')
city = loc_data.get('city', 'your location')
# Get weather for the location
weather_response = requests.get(
f"https://api.openweathermap.org/data/2.5/weather",
params={
"lat": latitude,
"lon": longitude,
"units": "metric",
"appid": openweathermap_api_key
}
)
weather_data = weather_response.json()
temp = weather_data.get('main', {}).get('temp')
if temp is not None:
print(f"The current temperature in {city} is {temp}°C.")
# Use the weather data here
return weather_data
# --- How to use it: ---
# IPLOCATE_KEY = 'YOUR_IPLOCATE_API_KEY'
# OPENWEATHERMAP_KEY = 'YOUR_OPENWEATHERMAP_API_KEY'
# weather = get_local_weather(IPLOCATE_KEY, OPENWEATHERMAP_KEY)
# if weather:
# # Use weather dict here
# pass
Using Ruby
require 'net/http'
require 'json'
require 'uri'
def get_local_weather(iplocate_api_key, openweathermap_api_key)
# Get location from IP address
iplocate_uri = URI("https://iplocate.io/api/lookup/?apikey=#{iplocate_api_key}")
loc_response = Net::HTTP.get(iplocate_uri)
loc_data = JSON.parse(loc_response)
latitude = loc_data['latitude']
longitude = loc_data['longitude']
city = loc_data['city'] || 'your location'
# Get weather for the location
weather_uri = URI('https://api.openweathermap.org/data/2.5/weather')
params = { lat: latitude, lon: longitude, units: 'metric', appid: openweathermap_api_key }
weather_uri.query = URI.encode_www_form(params)
weather_response = Net::HTTP.get(weather_uri)
weather_data = JSON.parse(weather_response)
temp = weather_data.dig('main', 'temp')
if temp
puts "The current temperature in #{city} is #{temp}°C."
end
# Use the weather data here
return weather_data
end
# --- How to use it: ---
# iplocate_key = 'YOUR_IPLOCATE_API_KEY'
# openweathermap_key = 'YOUR_OPENWEATHERMAP_API_KEY'
# weather = get_local_weather(iplocate_key, openweathermap_key)
# if weather
# # Use weather hash here
# end
By combining IPLocate with OpenWeatherMap, you can offer visitors personalized weather updates quickly and reliably.
Browse the complete IPLocate API documentation for more information on the accurate geolocation and IP intelligence data we provide.