Layar Developer Documentation

Back to layar.com

Create a simple vision layer

Since getPOIs API v6.0, developers can create vision layers which can augment objects in the physical world. For more information on what Layar Vision is, please check out Layar Vision section

In this fourth tutorial, we explain how to create a simple Vision layer step by step. In order to enable Layar Vision, please follow the steps described hereEnable Layar Vision in a layer  Please NOTE that only the minimum required code for creating a Vision layer is explained here. A more generic and complete version is provided in the Sample code.

If you haven't follow the previews tutorials , please make sure to check the following links before following this tutorial:

Prepare the Database

After defining a layer on the publishing site, we can prepare the database that stores the POI information. We shall use a MySQL database with phpMyAdmin, as in previous tutorials. The whole database looks like:

vision database

The VisionPoi table has been defined according to description on GetPOIs Request

Each row of this table represent a Page you have uploaded on the publishing site.

ViosionPoi table

Build Up a Web Service

Now that we have a ViosionPoi in the database, it is time to build up a web service to fetch the viosionPoi information and return it back to the Layar platform. The returned POI information should be formatted in JSON. If PHP version 5.2 or above is used, JSON is supported natively. Otherwise, the JSON string needs to be constructed programatically.

We will create the following php files to enable the web service: 

config.inc.php  

To get started, we pre-define variables for the MySQL database connection and save them in config.inc.php file.

<?php /* Pre-define connection to the MySQL database, please specify these fields based on your database configuration. */ define('DBHOST', 'localhost');
define('DBDATA', 'database_name');
define('DBUSER', 'database_username');
define('DBPASS', 'database_password'); ?>
fourthTutorial_simplified.php

In the main script, we need to:

Based on the layer definition we just did, an HTTP GET request with defined parameters has been sent to the POI URL.  A full list of request parameters can be found on the  GetPOIs-Request page . An example of GetPOIs request is:

http://custom.layar.nl/~olga/VisionTutorial_APIv7.0/tutorial_simple.php?lang=en&countryCode=%2A%2A&userId=6f85d06929d160a7c8a3cc1ab4b54b87db99f74b&lon=4.887339&version=7.0&radius=1500&lat=52.377544&layerName=visiontutorial&accuracy=100 

We first need to put the LayerName parameter from the GetPOI request in an array. 

Then, we use $_GET, a php global variable, to retrieve that parameter value. The needed parameter is stored in an associative array named $requestParams, which has parameter name as key and parameter value as value. This is done by calling a custom function  getRequestParams().

/* Put parameters from GetPOI request into an associative array named $requestParams */
// Put needed parameter names from GetPOI request in an array called $keys. 
$keys = array( 'layerName' );

// Initialize an empty associative array.
$requestParams = array(); 
// Call funtion getRequestParams()  
$requestParams = getRequestParams($keys);

Function getRequestParams() is defined below:

// Returns:
//  array ; An associative array which contains the request parameters and
//  their values.
function getRequestParams($keys) {

  $paramsArray = array();
  try {
    // Retrieve parameter values using $_GET and put them in $value array with
    // parameter name as key. 
    foreach( $keys as $key ) {
      if ( isset($_GET[$key]) )
        $paramsArray[$key] = $_GET[$key]; 
      else 
        throw new Exception($key .' parameter is not passed in GetPOI request.');
    }
    return $paramsArray;
  }
  catch(Exception $e) {
    echo 'Message: ' .$e->getMessage();
  }
}//getRequestParams 

Set up the connection to MySQL database and select the database which contains VisionPOI table. In our tutorial, we use PDO, a PHP extension, to formalise database connection. For more information regarding using PDO, please see http://php.net/manual/en/book.pdo.php.

// Connect to predefined MySQl database.  
$db = connectDb(); 

Function connnectDb() is defined below. If the database is connected successfully, a database connection handler is returned and assigned to $db. Otherwise, an exception is thrown.

// Connect to the database, configuration information is stored in
// config.inc.php file
function connectDb() {
  try {
    $dbconn = 'mysql:host=' . DBHOST . ';dbname=' . DBDATA ; 
    $db = new PDO($dbconn , DBUSER , DBPASS , array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
    // set the error mode to exceptions
    $db->setAttribute(PDO::ATTR_ERRMODE , PDO::ERRMODE_EXCEPTION);
     return $db; 
  }// try
  catch(PDOException $e) {
    error_log('message:' . $e->getMessage());
  }// catch
}// connectDb

Once the database is connected, we can retrieve needed  Vision Poi information as well as the respective object and actions of each Page. 

A function called getPoiActions() is created to fetch actions for each Vision POI.  We use an SQL statement to retrieve actions that has the same "actionID" defined for the POI in VisionPOI table. Return $actionArray array which contains retrieved action information. 

// Returns:
//   array ; An associative array of received actions for this VisionPOI.Otherwise,
//   return an empty array. 
// 
function getActions($db, $poi) {
    // Define an empty $actionArray array. 
    $actionArray = array();

    // A new table called 'POIAction' is created to store actions, each action
    // has a field called 'VisionpoiID' which shows the POI id that this action belongs
    // to. 
    // The SQL statement returns actions which have the same VisionpoiID as the id of
    // the VisionPOI($poiID).
    $sql_actions = $db->prepare(' 
      SELECT label, 
             uri, 
             contentType,
             activityType,
             autoTrigger,
             autoTriggerOnly,
             params
      FROM Actions
      WHERE VisionPoiID = :id ');

    // Binds the named parameter marker ':id' to the specified parameter value
    // '$poiID.                 
    $sql_actions->bindParam(':id', $poi['id'], PDO::PARAM_STR);
    // Use PDO::execute() to execute the prepared statement $sql_actions. 
    $sql_actions->execute();
    // Iterator for the $actionArray array.
    $count = 0;
    // Fetch all the poi actions. 
    $actions = $sql_actions->fetchAll(PDO::FETCH_ASSOC);

    /* Process the $actions result */
    // if $actions array is not empty. 
    if ($actions) {
        // Put each action information into $actionArray array.
        foreach ($actions as $action) {
            // Change 'activityType' to Integer.
            $action['activityType'] = changetoInt($action['activityType']);
            // For vision enabled POIs, we should use "autoTrigger"
            $action['autoTrigger'] = changetoBool($action['autoTrigger']);
            $action['autoTriggerOnly'] = changetoBool($action['autoTriggerOnly']);

            $action['params'] = changetoArray($action['params'], ',');
            // Assign each action to $actionArray array. 
            $actionArray[$count] = $action;
            $count++;
        }// foreach
    }//if
    return $actionArray;
}

//getPoiActions
// Put fetched object parameters for each Vision POI into an associative array.

The getObject() function works the same way to retrieve object information.

// Returns:
//   associative array or NULL ; An array of received object related parameters for this POI. otherwise, return NULL. 
// 
function getObject($db, $objectID) {
    // If no object object is found, return NULL. 
    $object = NULL;

    // A new table called 'Object' is created to store object related parameters,
    // namely 'url', 'contentType', 'reducedURL' and 'size'. The SQL statement
    // returns object which has the same id as $objectID stored in this POI. 
    $sql_object = $db->prepare(
            ' SELECT contentType,
             url, 
             size 
      FROM Object
      WHERE id = :objectID 
      LIMIT 0,1 ');

    // Binds the named parameter marker ':objectID' to the specified parameter
    // value $objectID.                 
    $sql_object->bindParam(':objectID', $objectID, PDO::PARAM_INT);
    // Use PDO::execute() to execute the prepared statement $sql_object. 
    $sql_object->execute();
    // Fetch the poi object. 
    $rawObject = $sql_object->fetch(PDO::FETCH_ASSOC);

    /* Process the $rawObject result */
    // if $rawObject array is not empty. 
    if ($rawObject) {
        // Change 'size' type to float. 
        $rawObject['size'] = changetoFloat($rawObject['size']);
        $object = $rawObject;
    }
    return $object;
}

//getObject

We then create  a custom function called getHotspots() . There are two tasks in this function:

  1. Create SQL statement to fetch the Vision POI information
  2. Parse the retrieved Vision POIs information, POI actions and POI object
// Returns:
//   array ; An array of received POIs.
//
function getHotspots($db, $value) {
    // Define an empty $hotspots array.
    $hotspots = array();
    /* Create the SQL query to retrieve vision POIs. 
      The first 50 returned POIs are selected.
     */

    // Use PDO::prepare() to prepare SQL statement. This statement is used due to
    // security reasons and will help prevent general SQL injection attacks.
    // $sql is returned as a PDO statement object. 
    $sql = $db->prepare('
  	       SELECT id,
               referenceImage,
               objectID,
               transformID
  	       FROM VisionPoi ');

    // Use PDO::execute() to execute the prepared statement $sql. 
    $sql->execute();
    // Iterator for the response array.
    $i = 0;
    // Use fetchAll to return an array containing all of the remaining rows in
    // the result set.
    // Use PDO::FETCH_ASSOC to fetch $sql query results and return each row as an
    // array indexed by column name.
    $rawPois = $sql->fetchAll(PDO::FETCH_ASSOC);

    /* Process the $pois result */
    // if $rawPois array is not  empty 
    if ($rawPois) {
        // Put each POI information into $hotspots array.
        foreach ($rawPois as $rawPoi) {
            $poi = array();
            $poi['id'] = $rawPoi['id'];
            // Get anchor object information
            $poi['anchor']['referenceImage'] = $rawPoi['referenceImage'];
            // get text object information
            $poi['actions'] = getActions($db, $rawPoi);
            // Get object object information if iconID is not null
            if (count($rawPoi['objectID']) != 0)
                $poi['object'] = getObject($db, $rawPoi['objectID']);
            // Get transform object information if transformID is not null
            if (count($rawPoi['transformID']) != 0)
                $poi['transform'] = getTransform($db, $rawPoi['transformID']);
            // Put the poi into the $hotspots array.
            $hotspots[$i] = $poi;
            $i++;
        }//foreach
    }//if
    return $hotspots;
}

//getHotspots

Now we have defined getHotspots function, we can use it to retrieve Vision POI information and construct JSON response.  

The mandatory keys in JSON response are: 

/* Construct the response into an associative array. */

// Create an empty array named response.
$response = array();

// Assign cooresponding values to mandatory JSON response keys.
$response['layer'] = $requestParams['layerName'];

// Use Gethotspots() function to retrieve POIs with in the search range.  
$response['hotspots'] = getHotspots($db, $requestParams);

// if there is no POI found, return a custom error message.
if (!$response['hotspots']) {
    $response['errorCode'] = 20;
    $response['errorString'] = 'No POI found. Please adjust the range.';
}//if
else {
    $response['errorCode'] = 0;
    $response['errorString'] = 'ok';
}//else

Finally, we are going to write $JsonResponse array into JSON format.

// Put the JSON representation of $response into $jsonresponse.
$jsonresponse = json_encode($response);

// Declare the correct content type in HTTP response header.
header('Content-type: application/json; charset=utf-8');

// Print out Json response.
echo $jsonresponse;

so now you have your first basic Vision layer.

Testing the layer

In order to test a Vision layer you need to scan the uploaded Page. Make sure to login with developer credentials on your device.

Please visit Test a layer  to get more information on how to test a layer on the API test page and on the phone.

Please find the attached sample code here and start creating your own vision layers!

Attachments