Friday, January 23, 2009

Local Search Control Programming Guide in Google API - Local Search Control for Google Maps

Instructions for adding this to your site
Assuming you already have a working maps application, adding the control is a simple two step process (alternatively,you can always start with "hello world" starter andthen customize the esulting code.)
Step 1 - Load AJAX Search API and Local Search Control for Google Maps

// Load the Code
<script src="http://www.google.com/uds/api?file=uds.js&v=1.0&key=ABQIAAAAipgi6ppj9z1Np5lR2SFXbBSMWlLVwX1ylsLSaLe34pMM37gB9hQjNUQFvLuLRgiSMzRlZIgxSIE1vw"
type="text/javascript"></script>
<script src="http://www.google.com/uds/solutions/localsearch/gmlocalsearch.js"
type="text/javascript"></script>

// Load the Style Sheets
<style type="text/css">
@import url("http://www.google.com/uds/css/gsearch.css");
@import url("http://www.google.com/uds/solutions/localsearch/gmlocalsearch.css");
</style>

The first step is to load the Google AJAX Search API and the Local Search Control code and style sheet into your application. The AJAX Search API uses the same key system that Google Maps API uses, so just use your maps key where required.

// Load the Code
<script src="http://www.google.com/uds/api?file=uds.js&v=1.0&key=ABQIAAAAipgi6ppj9z1Np5lR2SFXbBSMWlLVwX1ylsLSaLe34pMM37gB9hQjNUQFvLuLRgiSMzRlZIgxSIE1vw"
type="text/javascript"></script>
<script src="http://www.google.com/uds/solutions/localsearch/gmlocalsearch.js"
type="text/javascript"></script>

// Load the Style Sheets
<style type="text/css">
@import url("http://www.google.com/uds/css/gsearch.css");
@import url("http://www.google.com/uds/solutions/localsearch/gmlocalsearch.css");
</style>

Step 2 - Create a Local Search Control
The next step is to create a Local Search control and add it to your map.

// create your map
var map = new GMap2(document.getElementById("map"));
// create a local search control and add it to your map
map.addControl(new google.maps.LocalSearch());

Customizing the Local Search Control and Other Advanced Features
The Local Search Control for Google Maps contains a number of options that you control.

* Result List Format and Placement Control
* Setting the Link Target
* Custom Search Form Hint Text
* Idle and Search Completion Callbacks
* Marker Html Generation and Markers Set CallbacksNew!
* Setting Focus on the Search Control
* First Result Info Window Suppression
* Suppress Default Zoom on Search Complete

Result List Format and Placement Control

By default, when a search completes, the search results are placed on your map and they are also listed in tabular form above the search form input. By using the opt_options argument to the control, you can specify this default behavior, you can suppress the tabular display of
the search results, or you can provide us with a container element and we will place the tabular results within your container. The following snippets and samples demonstrate these options.
Suppressed Tabular Result List
The following snippet and sample demonstrates how to suppress the tabular result list.

<script type="text/javascript">
// request that tabular search results should be suppressed
var options = {
resultList : google.maps.LocalSearch.RESULT_LIST_SUPPRESS
};
map.addControl(new google.maps.LocalSearch(options));
</script>

Default Tabular Result List
The following snippet and sample demonstrates how to request the default tabular result list.

<script type="text/javascript">
// no option needed, this is the default
map.addControl(new google.maps.LocalSearch());

// BUT, If you want to, you can explicityly request the default
var options = {
resultList : google.maps.LocalSearch.RESULT_LIST_INLINE
};
map.addControl(new google.maps.LocalSearch(options));
</script>

External Tabular Result List
The following snippet and sample demonstrates how to request that the tabular result list be displayed in a container of your choice.
<script type="text/javascript">

// request that tabular search results be displayed in an external container
var options = {
resultList : document.getElementById("results")
};
map.addControl(new google.maps.LocalSearch(options));
...
<div id="results">Loading...</div>
</script>

Setting the Link Target

This option allows you to set the link target used for links embedded in the Local Search Control. The default value is GSearch.LINK_TARGET_BLANK which specifies that will open in a new window. To change this behavior, simply use the linkTarget property of options and supply a value of GSearch.LINK_TARGET_SELF to open links in the current new window, Search.LINK_TARGET_BLANK to open links in a new window, GSearch.LINK_TARGET_TOP to open links in the topmost frame,
GSearch.LINK_TARGET_PARENT to open links in the parent frame or to replace the current frame.
You can also specify any other value which will be used as the value of the target property on all links.

/*** open links in the current window*/

var options = {
linkTarget : GSearch.LINK_TARGET_SELF
};
map.addControl(new google.maps.LocalSearch(options));

Custom Search Form Hint Text

When the search control is in its idle state, the search form normally contains localized
search hint text, e.g.: "search the map". Using this option, you can supply your own custom hint
text.

var options = {
searchFormHint : "Example Searches: Hotels in New York City"
};
map.addControl(new google.maps.LocalSearch(options));

Idle and Search Completion Callbacks

In some cases, its useful for an application to know when a search has completed and when the earch control goes idle. For instance, when the search control goes idle, the application may want to recenter the map. When a search completes, an application may want to alter the zoom level of the map. These are easily accomplished by using the search control callbacks.
Search Control Idle Callback
The search control idle callback is called when the search control finishes its initial load and whenever search results are dismissed. The following snippet demonstrates how to use this.

// request an "on idle" callback. This is called when a search is dismissed and
// when the search control initially loads
var options = {
onIdleCallback : function() { alert("search control is idle");}
};
map.addControl(new google.maps.LocalSearch(options));

Search Complete Callback
The search complete callback is called whenever a search completes. It is passed the localSearch object associated with the search control. It is called before results are placed on the map or into the tabular results list. The following snippet demonstrates how to use this.

// request an "on search complete" callback. This is called when a search completes
// and before results are placed on the map or tabular tabular result list
var options = {
onSearchCompleteCallback : function(searcher){
alert(searcher.results.length + " results");
}
};
map.addControl(new google.maps.LocalSearch(options));

Marker Html Generation and Markers Set CallbacksNew!

The callbacks listed above give your application basic notifications that a search has completed
and that the user is done using the control. The marker oriented callbacks described in this section are designed to allow you to participate in the html generation phase of a search result's
info window as well as providing you with direct access to the markers once they have been placed on the map.
Generate Marker HTML Callback
When the info window for a marker representing a search result is opened, this callback is executed in order to allow you to participate in the html generation. For instance, suppose you want to add a link to the info window, or add a photo, or whatever makes sense for your application. The following snippet shows how to do this.

// request an "on generate marker html" callback. This is called during the open of an info window.
var options = {
onGenerateMarkerHtmlCallback : extendMarker
};
map.addControl(new google.maps.LocalSearch(options));
...
function extendMarker(marker, html, result) {
// extend the passed in html for this result
myStuff = document.createElement("div");
div.innerHTML = "Bookmark This Result...";
html.appendChild(div);
return html;
}

Markers Set Callback
The Search Complete callback calls your application before the search results are converted into markers and placed on the map. This allows your application to inspect and process the raw results. The onMarkersSetCallback calls your application after the search complete callback, and after the results are processed and placed on the map. This callback allows you to inspect and
process the markers, etc. The sample below demonstrates this callback. Normally, after a search completes, the first marker's info window is opened. Using this callback, you can open an alternate info window (maybe the info window of one of your partners, etc.)
// request an "on markers set" callback.

var options = {
onMarkersSetCallback : markersSet
};
myLocalSearchControl = new google.maps.LocalSearch(options);
map.addControl(myLocalSearchControl);
...
function markersSet(markers) {
// note: markers is an array of LocalResult
if (markers.length > 1) {
// grab the title of the 2nd result object
// if it matches starbucks, then alert
var title = markers[1].result.titleNoFormatting;
if (title.search(/starbucks/i) >= 0) {
alert(markers[1].result.titleNoFormatting);
}
}
}

Setting Focus on the Search Control
Applications may use the focus() method on the search control to force focus to the search form's input box.

var searchControl = new google.maps.LocalSearch();
map.addControl(searchControl);
...
searchControl.focus();

First Result Info Window Suppression
Normally, when a search completes, the first search result is selected, the map is panned to this
result, and the info window associated with the result is opened. This option allows an application to suppress this initial info window open.

// request the the initial search result info window should not be
// auto-opened
var options = {
suppressInitialResultSelection : true
};
map.addControl(new google.maps.LocalSearch(options));

Suppress Default Zoom on Search CompleteNew!
Normally, when a search completes, the map is re-positioned and zoomed in so that it shows all of the results. Applications can disable this move/zoom operation by setting the suppressZoomToBounds option to false. The HotLinks sample demonstrates this. The other interesting thing this sample does is demonstrate how to use the search control's .execute() method to do initiate a search from your own code. Note the Featured Locations links beneath the map.

// instruct the system to NOT zoom on search complete
var options = {
suppressZoomToBounds : true
};
map.addControl(new google.maps.LocalSearch(options));

The "Hello World" of the Local Search Control for Google Maps

The following page demonstrates a complete page which uses the Local Search Control
for Google Maps. You can start with this simple page, change YOUR-KEY to the value of
your key and be up and running in seconds.

Warning: Make sure you signup for your own key. Do not use the key value of "YOUR-KEY" on your pages.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type"
content="text/html; charset=utf-8"/>
<title>Local Search Control for Google Maps -
default.html</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=
ABQIAAAAipgi6ppj9z1Np5lR2SFXbBSMWlLVwX1ylsLSaLe34pMM37gB9hQjNUQFvLuLRgiSMzRlZIgxSIE1vw" type="text/javascript"></script>
<script src="http://www.google.com/uds/api?file=uds.js&
v=1.0&key=YOUR-KEY" type="text/javascript"></script>
<script src="http://www.google.com/uds/solutions/localsearch/gmlocalsearch.js"
type="text/javascript"></script>
<style type="text/css">
@import url("http://www.google.com/uds/css/gsearch.css");
@import url("http://www.google.com/uds/solutions/localsearch
/gmlocalsearch.css");
#map {
border : 1px solid #979797;
width : 100%;
height : 600px;
}
</style>
<script type="text/javascript">
//<![CDATA[
function load() {
if (GBrowserIsCompatible()) {
// Create and Center a Map
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(12.4419, 79.1419), 13);
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
// bind a search control to the map, suppress result list
map.addControl(new google.maps.LocalSearch());
}
}
GSearch.setOnLoadCallback(load);
//]]>
</script>
</head>
<body onunload="GUnload()">
<div id="map"></div>
</body>
</html>



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type"
content="text/html; charset=utf-8"/>
<title>Local Search Control for Google Maps -
default.html</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=
ABQIAAAAipgi6ppj9z1Np5lR2SFXbBSMWlLVwX1ylsLSaLe34pMM37gB9hQjNUQFvLuLRgiSMzRlZIgxSIE1vw"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
google.load("search", "1");
function OnLoad() {
// Create a search control
var searchControl = new google.search.SearchControl();
// Add in a full set of searchers
var localSearch = new google.search.LocalSearch();
searchControl.addSearcher(localSearch);
searchControl.addSearcher(new google.search.WebSearch());
searchControl.addSearcher(new google.search.VideoSearch());
searchControl.addSearcher(new google.search.BlogSearch());
// Set the Local Search center point
localSearch.setCenterPoint("India, India");
// Tell the searcher to draw itself and tell it where to attach
searchControl.draw(document.getElementById("searchcontrol"));
// Execute an inital search
searchControl.execute("Google");
}
google.setOnLoadCallback(OnLoad);>
</script>
</head>
<body onunload="GUnload()">
<div id="searchcontrol">Loading...</div>
</body>
</html>

Monday, January 19, 2009

Function arguments in PHP

Function arguments
Information may be passed to functions via the argument list, which is a comma-delimited list of expressions.

PHP supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists are also supported, see also the function references for func_num_args(), func_get_arg(), and func_get_args() for more information.

Example Passing arrays to functions

Making arguments be passed by reference
By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.

To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition:

Example Passing function parameters by reference

Default argument values
A function may define C++-style default values for scalar arguments as follows:

Example Use of default parameters in functions

The output from the above snippet is:

Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.

PHP also allows the use of arrays and the special type NULL as default values, for example:


Example Using non-scalar types as default values

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected. Consider the following code snippet:

Example Incorrect usage of default function arguments

The output of the above example is:

Warning: Missing argument 2 in call to makeyogurt() in
/usr/local/etc/httpd/htdocs/phptest/functest.html on line 41
Making a bowl of raspberry .

Now, compare the above with this:

Example Correct usage of default function arguments

The output of this example is:

Making a bowl of acidophilus raspberry.

Note: As of PHP 5, default values may be passed by reference.

Variable-length argument lists
PHP 4 and above has support for variable-length argument lists in user-defined functions. This is really quite easy, using the func_num_args(), func_get_arg(), and func_get_args() functions.

Variable functions in PHP

Variable functions
PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.

Variable functions won't work with language constructs such as echo(), print(), unset(), isset(), empty(), include(), require() and the like. Utilize wrapper functions to make use of any of these constructs as variable functions.


Example Variable function example

\n";
}

function bar($arg = '')
{
echo "In bar(); argument was '$arg'.
\n";
}

// This is a wrapper function around echo
function echoit($string)
{
echo $string;
}

$func = 'foo';
$func(); // This calls foo()

$func = 'bar';
$func('test'); // This calls bar()

$func = 'echoit';
$func('test'); // This calls echoit()
?>

An object method can also be called with the variable functions syntax.

Example Variable method example

$name(); // This calls the Bar() method
}

function Bar()
{
echo "This is Bar";
}
}

$foo = new Foo();
$funcname = "Variable";
$foo->$funcname(); // This calls $foo->Variable()

?>

Declare Control Structure in PHP

declare

The declare construct is used to set execution directives for a block of code. The syntax of declare is similar to the syntax of other flow control constructs:

declare (directive)
statement

The directive section allows the behavior of the declare block to be set. Currently only two directives are recognized: the ticks directive (See below for more information on the ticks directive) and the encoding directive (See below for more information on the encoding directive).

The statement part of the declare block will be executed - how it is executed and what side effects occur during execution may depend on the directive set in the directive block.

The declare construct can also be used in the global scope, affecting all code following it (however if the file with declare was included then it does not affect the parent file).
// these are the same:

// you can use this:
declare(ticks=1) {
// entire script here
}

// or you can use this:
declare(ticks=1);
// entire script here
?>

As of PHP 5.3.0 ticks are deprecated and will be removed in PHP 6.0.0.

A tick is an event that occurs for every N low-level statements executed by the parser within the declare block. The value for N is specified using ticks=N within the declare blocks's directive section.

The event(s) that occur on each tick are specified using the register_tick_function(). See the example below for more details. Note that more than one event can occur for each tick.

Example #1 Profile a section of PHP code
// A function that records the time when it is called
function profile($dump = FALSE)
{
static $profile;

// Return the times stored in profile, then erase it
if ($dump) {
$temp = $profile;
unset($profile);
return $temp;
}

$profile[] = microtime();
}

// Set up a tick handler
register_tick_function("profile");

// Initialize the function before the declare block
profile();

// Run a block of code, throw a tick every 2nd statement
declare(ticks=2) {
for ($x = 1; $x < 50; ++$x) {
echo similar_text(md5($x), md5($x*$x)), "
;";
}
}

// Display the data stored in the profiler
print_r(profile(TRUE));
?>

The example profiles the PHP code within the 'declare' block, recording the time at which every second low-level statement in the block was executed. This information can then be used to find the slow areas within particular segments of code. This process can be performed using other methods: using ticks is more convenient and easier to implement.

Ticks are well suited for debugging, implementing simple multitasking, background I/O and many other tasks.

See also register_tick_function() and unregister_tick_function().
Encoding

A script's encoding can be specified per-script using the encoding directive.

Example #2 Declaring an encoding for the script.
declare(encoding='ISO-8859-1');
// code here
?>
Caution

When combined with namespaces, the only legal syntax for declare is declare(encoding='...'); where ... is the encoding value. declare(encoding='...') {} will result in a parse error when combined with namespaces.

The encoding declare value is ignored in PHP 5.3 unless php is compiled with --enable-zend-multibyte. In PHP 6.0, the encoding directive will be used to inform the scanner what encoding the file is created in. Legal values are encoding names such as UTF-8.

Internal (built-in) functions in PHP

Internal (built-in) functions
PHP comes standard with many functions and constructs. There are also functions that require specific PHP extensions compiled in, otherwise fatal "undefined function" errors will appear. For example, to use image functions such as imagecreatetruecolor(), PHP must be compiled with GD support. Or, to use mysql_connect(), PHP must be compiled with MySQL support. There are many core functions that are included in every version of PHP, such as the string and variable functions. A call to phpinfo() or get_loaded_extensions() will show which extensions are loaded into PHP. Also note that many extensions are enabled by default and that the PHP manual is split up by extension. See the configuration, installation, and individual extension chapters, for information on how to set up PHP.

Reading and understanding a function's prototype is explained within the manual section titled how to read a function definition. It's important to realize what a function returns or if a function works directly on a passed in value. For example, str_replace() will return the modified string while usort() works on the actual passed in variable itself. Each manual page also has specific information for each function like information on function parameters, behavior changes, return values for both success and failure, and availability information. Knowing these important (yet often subtle) differences is crucial for writing correct PHP code.

Predefined variables in PHP

Predefined variables

PHP provides a large number of predefined variables to all scripts. The variables represent everything from external variables to built-in environment variables, last error messages to last retrieved headers.

See also the FAQ titled "How does register_globals affect me?"

Contents

  • Superglobals — Superglobals are built-in variables that are always available in all scopes
  • $GLOBALS — References all variables available in global scope
  • $_SERVER — Server and execution environment information
  • $_GET — HTTP GET variables
  • $_POST — HTTP POST variables
  • $_FILES — HTTP File Upload variables
  • $_REQUEST — HTTP Request variables
  • $_SESSION — Session variables
  • $_ENV — Environment variables
  • $_COOKIE — HTTP Cookies
  • $php_errormsg — The previous error message
  • $HTTP_RAW_POST_DATA — Raw POST data
  • $http_response_header — HTTP response headers
  • $argc — The number of arguments passed to script
  • $argv — Array of arguments passed to script

Extending Exceptions in PHP

Exceptions

Extending Exceptions
PHP 5 has an exception model similar to that of other programming languages. An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try block, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exeptions. Normal execution (when no exception is thrown within the try block, or when a catch matching the thrown exception's class is not present) will continue after that last catch block defined in sequence. Exceptions can be thrown (or re-thrown) within a catch block.

When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." message, unless a handler has been defined with set_exception_handler().

Note: Internal PHP functions mainly use Error reporting, only modern Object oriented extensions use exceptions. However, errors can be simply translated to exceptions with ErrorException.

Example Throwing an Exception

getMessage(), "\n";
}

// Continue execution
echo 'Hello World';
?>
The above example will output:

0.2
Caught exception: Division by zero.
Hello World

Example Nested Exception

getMessage());
}
}
}

$foo = new Test;
$foo->testing();

?>
The above example will output:

string(4) "foo!"