<?php
/**
* GoogleLocalAPI.class.php
* Clark Freifeld 5 Apr 06
* Class to provide programmatic access to Google Local
* Part of the Smoot project, released individually under the terms of the LGPL.
*
* How to use this class:
*
* $gl = new GoogleLocalAPI();
* // query is 'pizza boston', max results 50
* $gl->query('pizza boston', 50);
* while($r = $gl->getNext()) {
*   print 'name: ' . $r['name'] . "\n";
*   print 'address: ' . $r['addr'] . "\n";
*   print 'latitude: ' . $r['lat'] . "\n";
*   print 'longitude: ' . $r['longitude'] . "\n";
* }
* $gl->reset();
*/

class GoogleLocalAPI
{
    
/* private */ var $url;
    
/* private */ var $r;
    
/* private */ var $i;
    
/* private */ var $matches; // assoc array of matches
    
    
function GoogleLocalAPI($url = 'http://www.google.com/local')
    {
        
$this->url = $url;
        
$this->r = 0;        // index to new results
        
$this->i = 0;        // current result
    
}
    
    function
query($query, $max_results = 10, $start = 0)
    {
        
//$log = Log::factory('file', '/tmp/gl.log', 'GLAPI');
        
$this->query = $query;
        
$this->start = $start;
        
$this->max_results = $max_results;
        
$result = file_get_contents($this->url . '?q=' . urlencode($query) . "&start=$start");
        
// NOTE: php bug: double quotes are not handled as they are in perl; you need a \ in php that you don't need in perl
        
preg_match_all('/<input value=\\\"(.+?)\\\" name=\\\"saddr\\\" type=.+?\/>/', $result, $matches);
        
$len = count($matches[1]);
        for(
$i = 0; $i < $len; $i++) {
            
// my regexp gives me extraneous matches so we take every other one
            
if($i % 2 == 0) {
                
$elts = preg_split('/\(|\)/', $matches[1][$i]);
                
//$log->log(print_r($matches[1][$i], true));
                //$log->log(print_r($elts, true));
                
$this->matches[$this->r]['addr'] = trim($elts[0]);
                
$this->matches[$this->r]['name'] = trim($elts[1]);
                
$latlon = str_replace('@', '', $elts[2]);
                list(
$this->matches[$this->r]['lat'], $this->matches[$this->r]['lon']) = explode(',', trim($latlon));
                
$this->r++;
            }
        }
    }
    
    
//get the next 10 results of query and add them to the matches list
    
function queryNextPage()
    {
        
$this->query($this->query, $this->max_results, $this->start + 10);
    }
    
    function
getNext($f = '')
    {
        
$j = $this->i;
        
$this->i++;
        if(empty(
$this->matches[$j]) && $j < $this->max_results) {
            
$this->queryNextPage();
        }
        if(
$f) {
            return
$this->matches[$j][$f];
        } else {
            return
$this->matches[$j];
        }
    }
    
    function
reset()
    {
        
$this->i = 0;
    }
}
?>