Done in 60 seconds: a location based service example using IP Geolocation: local weather

VA - Leesburg / Godfrey

Clear sky
  • Clear sky
  • Temperature: 17 °C
  • Wind: ENE, 13 km/h
Location of this weather station:
8.1 km WNW

Reported on:
Mon, 21/04/2014 - 6:55am
Earlier on these pages we showed how a couple of PHP code snippets used in combination with the IP Geolocation module are all it takes to add a simple location based feature to your web site. What follows is another example.
This time we team up IP Geolocation with the Weather module. This module finds the closest weather station based on the user's IP address. If you've read the IP Geolocation project page you know that we can do better than that by taking advantage of GPS, WiFi and the cell phone towers around us.
To realise this, first configure IP Geolocation according to its README (up to point A3). Then install and enable the Weather module. No need to configure it right now. Leave the Weather module's blocks. Instead, at Structure >> Blocks add a plain block. Copy and paste into the "Block body" text area the code below. Set the "Text format" to "PHP code" (note: requires core's PHP filter module be enabled). Save the block.
<?php
  if (isset($_SESSION['ip_geoloc']['location'])) {
    $location = $_SESSION['ip_geoloc']['location'];
    $station = weather_get_nearest_station($location['latitude'], $location['longitude']);
    $display = weather_get_display_settings('default', 1);
    variable_set('weather_fetch', 'HTTP');  // or 'FTP', but may not work in certain hosting environments
    $metar = weather_get_metar($station->icao);
    return theme('weather_theming', array('location' => $station, 'display' => $display, 'metar' => $metar));
  }
?>

There! Now you always have the weather report of where you are, not where your provider is or some other fixed location.

File under: 

Planet Drupal

Comments

Submitted by Dietmar Ludmann (not verified) on Fri, 27/01/2012 - 10:16pm

Stumbled upon this, while searching for something else, but had to try it out instantly on my test-site.
I included the first code snippet in a block, but I had to add an additional if clause to overcome an php error in line 3 of the code (the line starting with "$station =").
Seems that this error only occures when the user has not yet answered the browsers request to expose his position to the site. In that case $_SESSION['ip_geoloc']['location'] is set, but the array elements latitude and longitude are not there throwing an exception on the line mentioned above.
So I just added another if clause checking these elements and now it works just fine!
I've seen this error yesterday on your page too (with FF 9.01 on LinuxMint), but was not able to reproduce it today?!?
Anyway, thanks again for this great article!