Layar Developer Documentation

Back to layar.com

Create a simple Geo-location layer

This is the first of a series of tutorials on how to create a layer using the current Layar developer API . Each tutorial will explain how to implement a specific feature within a layer. Sample code is also provided at the end of each tutorial. The idea is to help developers get started with their layer development faster.

In this first tutorial, we explain how to create a simple geolocation layer step by step.  A geolocation layer returns POIs which are located in a specific geo-location. Please NOTE that only the minimum required code for creating a geolocation layer is explained here. A more generic and complete version is provided in the Sample code.

A layer can be written in various programming languages. In this tutorial however, we give the sample code in PHP. We make use of the following packages:

Please NOTE that the web server should be publicly reachable on the internet.

General Steps

Define and edit a layer on the publishing site

After logging in with your layar account, the developer can define a new layer by clicking the "Create a Layer" button under "layers" section on the publishing site. In this tutorial, we create a layer which shows the location of the Layar office in Amsterdam as an example (see sreenshot below). More details of defining a layer can be found here.

Fields Description Example value (Please customize this)
Layer name A unique name for your layer layaroffice
Title The title that will be visible once it is published The Layar Office
Publisher name The name of the publisher Layar
Layer type The type of the layer, can also be 3D and 2D objects in 3D space (will be introduced in later tutorials) Generic (2D)
API endpoint URL The URL for the web service that provides information about points of interest (POIs) in the database.  http://custom.layar.nl/FirstTutorial.php
Short Description A short description of the layer and where the POIs are located This layer shows the location of the Layar office in Amsterdam
Layar Vision Enabling this option will allow you to create a layer with Layar Vision. unchecked

After completing the form, click "Create layer" button and the layer appears in the layer list.

Click on "Edit" button to further customize this layer.

In layer editing section, there are quite a few tabs. In the table below, we highlight the needed customizations for this tutorial in the table below. The rest can be left on their default values. For more detailed description, please read here.

Tab Fields Customizations
Listing & Indexing  Icon We upload a layar icon image.
Category Local information
Detail description Fill in "This is a layer which shows the location of the layar office in Amsterdam. It is a tutorial on creating a simple layer.It is created by Layar Technical Support."
Look & feel Banner Icon Upload a banner icon(60x26).
Coverage Countries Only list countries that this layer covers. Here we choose "Netherlands"
Bounding Boxes If POIs are only available in a city or specific region. Bounding boxes can be used to define that region.  A layer with bounding boxes will be shown in the local tab when the user is in the defined region. In this layer, we set bounding boxes around Amsterdam.

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. In this tutorial, a table called POI is used. More tables will be created in the coming tutorials to enable more advanced features, such as actions, 3D objects, etc.

Based on the POI object description at GetPOIs-JSON Response , the POI table is defined as:

first tutorial - POI table

Please NOTE that since getPOIs API v6.0, it is possible to support both geo POIs and vision POIs. We added a field called "poiType" which has value either "geo" or "vision". We will use this field to distinguish these two types of POIs. More fields will be added to this POI table in future tutorials.

Gather POIs Information

When the "POI" Table is ready, we insert POIs into it. Google Maps is used to get the GPS coordinates for selected locations. You can also use other tools for this. 

In our tutorial, we locate the Layar office (see screenshot below):

Google map

first tutorial - POI entry

Build Up a Web Service

Now that we have a POI in the database, it is time to build up a web service to fetch the POI 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:

In the layer definition, we have provided the POI URL which will be called to retrieve the POI information. Let's have a look at the PHP script.

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');
?>

firstTutorial_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/FirstTutorial_POI.php?lang=en&countryCode=NL&lon=4.887339&userId=6f85d06929d160a7c8a3cc1ab4b54b87db99f74b&developerId=4441&developerHash=26ec094e19db2c4a82ebafa200ea2a5e87a7d671&version=4.0&radius=2500&timestamp=1286357071952&lat=52.377544&layerName=layaroffice&accuracy=100

We first put needed parameter names from the GetPOI request in an array. In our tutorial, we need the following parameters:

Then, we use $_GET, a php global variable, to retrieve these parameter values. The needed parameters are 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', 'lat', 'lon', 'radius' );

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

Function getRequestParams() is defined below:

// Put needed getPOI request parameters and their values in an associative array
//
// Arguments:
//  array ; An array of needed parameters passed in getPOI request
//
// 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 POI 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 POI information. We created a custom function called getHotspots() to do so.

There are two tasks in this function:

1. Create SQL statement to fetch the POI information

Now we are going to create a SQL statement to retrieve POIs information from POI table. 

In our tutorial, we use a combination of PDO::prepare() and PDO::execute() to prepare and execute the SQL query. These two PDO statements are used due to security reasons and will help prevent general SQL injection attacks. 

2. Parse the retrieved POIs information

Sort out retrieved POIs information and put them in $reponse["hotspots"] associative array.

function getHotspots( $db, $value ) {

/* Create the SQL query to retrieve POIs whose "poiType" value is "geo"  and

     the distance between POIs and the user is within the "radius" returned from GetPOI request.
     Returned POIs are sorted by distance and the first 50 POIs are selected.
     The distance is caculated based on the Haversine formula.
     Note: this way of calculation is not scalable for querying large database.
*/
    
  // Use PDO::prepare() to prepare SQL statement.
  // This statement is used due to security reasons and will help prevent general SQL injection attacks.
  // ":lat1", ":lat2", ":long" and ":radius" are named parameter markers for which real values
  // will be substituted when the statement is executed.
  // $sql is returned as a PDO statement object.
  $sql = $db->prepare( "
              SELECT id,
                     imageURL,
                     title,
                     description,
                     footnote,
                     lat,
                     lon,
                     (((acos(sin((:lat1 * pi() / 180)) * sin((lat * pi() / 180)) +
                        cos((:lat2 * pi() / 180)) * cos((lat * pi() / 180)) *
                        cos((:long  - lon) * pi() / 180))
                       ) * 180 / pi()
                      )* 60 * 1.1515 * 1.609344 * 1000
                     ) as distance
               FROM POI
              WHERE poiType = "geo"
             HAVING distance < :radius
           ORDER BY distance ASC
              LIMIT 0, 50 " );

  // PDOStatement::bindParam() binds the named parameter markers to the
  // specified parameter values.
  $sql->bindParam( ':lat1', $value['lat'], PDO::PARAM_STR );
  $sql->bindParam( ':lat2', $value['lat'], PDO::PARAM_STR );
  $sql->bindParam( ':long', $value['lon'], PDO::PARAM_STR );
  $sql->bindParam( ':radius', $value['radius'], PDO::PARAM_INT );
  // 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 $rawPois 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'];
      $poi['imageURL'] = $rawPoi['imageURL'];
      // get anchor object information, note that changetoFloat is a custom function used to covert a string variable to float.
      $poi['anchor']['geolocation']['lat'] = changetoFloat($rawPoi['lat']);
      $poi['anchor']['geolocation']['lon'] = changetoFloat($rawPoi['lon']);
      // get text object information
      $poi['text']['title'] = $rawPoi['title'];
      $poi['text']['description'] = $rawPoi['description'];
      $poi['text']['footnote'] = $rawPoi['footnote'];
     // 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 POI information and construct JSON response.

The mandatory keys in JSON response are:

To construct the JSON response:

/* 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.

/* All data is in $response, print it 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;

Until now, we have explained the minimum code needed for creating a simple geolocation layer web service. The code used above is provided in the sample code file to help quickly set up a layer web service. Besides this, a more generic and complete version is provided to allow:

For detailed information, please read the readmefirst.txt in the attached Sample Code folder first. 

Testing the layer

There are two ways to test a layer:

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

Publish the layer

Before request publication approval, please make sure that you test your layer against Layer testing instructions . Once your layer is approved, you can publish it to make it visible to the users. To publish the layer, you can press the "publish" button next to each layer under "layers" tab on the publishing sit. For more information, please read Publishing site.

This is the end of our first tutorial, get started with your first layer and impress us!!

For any technical questions, please visit Layar Developer Support Environment. The Layar developer community is there to help you out!