Climate is what we expect, weather is what we get and when you are aware about the weather of your location then you don’t need to go anywhere else. Earlier, we learnt how can we add the weather to our website and now I will let you know how can we display the that based on your geo-location.

weather-geekword

First, we have to analyze how to get your geolocation. For this, you have to get your IP by writing this line of code.

$ip = $_SERVER['REMOTE_ADDR'];

There are multiple techniques, algorithms and approaches to get ones location based on IP address. We will be using an IPINFODB API which provides various methods to get your location for FREE (sign up required). So for this tutorial, I’d go with web based IP geolocation lookup feature of it.

Since you have already obtained your IP address in variable, therefore, let’s write a method which would return us the name of your location (city) by using the same SimpleXML extension of PHP that we used in our earlier post.

function CityAPI($ip)

{

  $document = simplexml_load_file("http://api.ipinfodb.com/v2/ip_query.php?key=6c16562376f47eb3e9ffabc01742f02ebd5ef1d3c46ec5e09962c3d9ebf4f66b&ip=$ip&timezone=false");

  foreach($document->children() as $children)

  {

    if($children->getName() == 'City')

    {

      return $children;

    }

  }

}

Now just store the city’s name in variable by calling out this function CityAPI and then pass it in ShortWeather to get the weather of your current city.

$cityName = CityAPI($ip);
$weather[] = ShortWeather($cityName);

Now you can easily display the weather of your current location anywhere on your websites and blogs.

<table>

<tr>

<td style="height: 27px"><?php echo $cityName ?></td>

<td style="text-align: center; height: 27px;"><?php echo $weather[0][0]; ?></td>

<td style="text-align: center; height: 27px;"><?php echo $weather[0][1]; ?></td>

<td style="text-align: center; height: 27px;"><?php echo $weather[0][2]; ?></td>

<td style="text-align: center; height: 27px;"><?php echo $weather[0][3]; ?></td>

</tr>

</table>

geo-geekword

I hope your readers will love it. Feel free to comment should you have any queries regarding fetching / displaying of data. Join us on our Facebook fan page and Twitter to get more development updates.