| 
  • If you are citizen of an European Union member nation, you may not use this service unless you are at least 16 years old.

  • You already know Dokkio is an AI-powered assistant to organize & manage your digital files & messages. Very soon, Dokkio will support Outlook as well as One Drive. Check it out today!

View
 

First Layar Tutorial - Create a simple Geolocation layer

Page history last edited by xuan wang 12 years, 2 months ago
Please NOTE that this documentation will not be updated anymore. Please see our new Developer Documentation Site for the latest updates! The content of this page can be found here.

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.

 

General Steps

 

Generally, the steps to create a layer can be outlined as follows:

  1. Sign up to be a developer (only once)
  2. Define and edit a layer on the publishing site 
  3. Prepare the database 
  4. Gather POIs information  
  5. Build a web service 
  6. Test the layer 
  7. Publish the layer

 

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:

 

  • A web server with PHP (5.3 or above) which supports JSON
  • A MySQL database (preferably with phpMyAdmin)

 

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

 

When the needed applications are installed, we follow the steps mentioned above to create a simple layer.

 

1. Sign up to be a developer

 

Before creating a layer, a developer needs to sign up to be a developer on layar website. For more information on how to become a layer developer, please read Sign up to be a developer. After activating the account, the developer can sign in on the publishing site

 

 

2. Define and edit a layer on the publishing site

 

After logging in, 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 at the Create a layer page.

 

screenshot 1 - "create a layer" button

 

 

screenshot 2 - create a layer form

 

Each field in the above screenshot is explained below. More information can be obtained from Create a layer .

 

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.

 

screenshot 3 - created layer in the list

 

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

 

screenshot 4 - layer editing

 

In layer editing section, there are 9 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 Edit a layer page.

 

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."
Minimum API version

Since we are creating a simple layer without any fancy feature implemented. Therefore, we set the Minimum API version to 2.1.

NOTE that based on different features implemented in a layer, Minimum API version should be adjusted accordingly.

Look & feel   Banner Icon Upload a banner icon(60x26).
Custom POI indicator Widgets (CIW) Instead of using default POI icons, custom POI indicator widgets(CIW) can be defined here.  We show the same layar icon image when POI is in Focus status and leave the others as default.
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.

Filters
Range slider We add a "Range slider" to set search range. 

 

 

3. 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:

 

screenshot 5 - 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.

 

4. 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):

     1) Search for "layar, amsterdam" at Google Maps.

     2) Right click on the icon on the map and press "What's here".  The Geo coordinates (latitude, longitude) will be displayed in the search field. In our case the coordinates are (52.374518, 4.9353).

screenshot 6 - POI Geo-coordinates

 

     3) Add the POI information to the POI below. The remaining fields are left as default for now.

 

screenshot 7 - POI entry

 

 

5. 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:

  • config.inc.php - contains the database configuration information.  
  • firstTutorial_simplified.php - the main php script file which is called by Layar server. It is the same file as defined under "API endpoint URL" field mentioned above. 

 

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 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:

  • layerName - The name of the layer defined on the publishing site. 
  • lat - The latitude of the position where the user/phone is located.
  • lon - The longitude of the position where the user/phone is located.
  • radius - The search range within which POIs should be returned.

 

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


 

  • Connect to MySQL database

 

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


  • Query database to get POI information

 

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.  

 

  • Only POIs within the defined search range (in our case, "radius" returned from the GetPOI request) are fetched. Returned POIs are sorted by distance and the first 50 POIs are selected. The calculation of the distance (in meters) between two locations is based on the Haversine formula. Please NOTE that this way of calculation is not scalable for querying large databases.
  • For each POI, we only return mandatory parameters and optional parameters with non-default values defined for POI object. Please NOTE that only return mandatory parameters and optional parameters which have different values than their default values.

 

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


  • Construct the JSON response

 

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:

  • layer: String; The name of the layer.
  • hotspots: Array of POIs; A list of returned POIs information from the database, returned by function getHotspots.
  • errorCode: Integer; 0 is ok. Use any error code between 20 and 29 to return a custom error message that will be displayed to the end-user.
  • errorString: String; The corresponding error message returned back to the user, visible in the AR view. 

 

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

 


 

  • Write to JSON  

 

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: 

  • Creation and storage of multiple layers in the database (A new table "Layer" is created)
  • For each POI, only mandatory and non-default optional parameters are returned 

 

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

 

6. Testing the layer

 

There are two ways to test a layer:

  • API test page: It is available on the publishing site next to each layer. The test man can be placed anywhere your POIs are located. In our case, we just leave it as default. After adjusting the search slider to the right position, press "Load POIs" button to retrieve POIs. 

 

 

screenshot 6 - API test page

 

  • On the phone: Layar application is currently available on Android(version 1.5 and above) and IPhone( 3GS and 4).

 

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

 

7. 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 site (see screenshot below). For more information, please read Publish a layer on the wiki.

 

 

In this tutorial, we provide the fixed location of the phone as (lat: 52.373801, lon: 4.890935), country is Netherlands. Now, let's try to find the layer office on the screen!!

 

 

Oops, we see the custom error message on the top right, no poi is within the range. Let's increase the search range to 3.5km to try it again. Now we find the layar office!

 

 

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!

 

Comments (0)

You don't have permission to comment on this page.