Easy user location with Midgard

Location is an important context that web services can utilize for fun or smarter user interaction. In past getting location used to be difficult, but now thanks to good IP locationing databases and browser geolocation capabilities it is becoming a lot easier.

But to be really easy, the framework you're using should provide user's location built-in, without you as an application developer having to think about it. This is the reason for Midgard's geolocation features to exist, after all. With Midgard, getting user's location is quite easy:

Midgard MVC (Midgard 9.09)

// Read location from session or user's location log
$user_location = midgardmvc_helper_location_user::get_location();
if (is_null($user_location))
{
    // No location found, try to geocode based on user IP via the GeoPlugin service
    $geocoder = new new midgardmvc_helper_location_geocoder_geoplugin()
    $location_parameters = array('ip' => $_SERVER['REMOTE_ADDR']);
    try
    {
        $user_location = $geocoder->geocode($location_parameters);
        midgardmvc_helper_location_user::set_location($user_location);
    }
    catch (Exception $e)
    {
        // Couldn't get location from IP
    }
}

if (!is_null($user_location))
{
    echo sprintf('You\'re in %s, %s', $user_location->latitude, $user_location->longitude);
    // Will print "You're in 60.1633, 24.9279"
}

MidCOM (Midgard 8.09)

<?php
// Read location from session or user's location log
$user_location = org_routamc_positioning_user::get_location();
if (is_null($user_location))
{
    // No location found, try to geocode based on user IP
    $geocoder = org_routamc_positioning_geocoder::create('geoplugin');
    $location_parameters = array('ip' => $_SERVER['REMOTE_ADDR']);
    $user_location = $geocoder->geocode($location_parameters);
    if (!is_null($user_location))
    {
        // Store geocoded location to session or user's location log
        org_routamc_positioning_user::set_location($user_location);
    }
}

if (!is_null($user_location))
{
    echo sprintf('You\'re in %s, %s', $user_location['latitude'], $user_location['longitude']);
    // Will print "You're in 60.1633, 24.9279"
}
?>

The examples above will work with both anonymous site visitors (using sessions) and registered users (using Midgard's position log). In this example we check if location is already available via browser geolocation or some importer like Qaiku or Fire Eagle, and if not we fall back to IP-based positioning using the GeoPlugin service. The resulting user location array or object (depending on Midgard used) contains a textual description of the place and accuracy information in addition to WGS-84 coordinates.


Read more Midgard posts.