Google geocoding using v3 not showing error - google-maps-api-3

Kindly help on the code below. What happens is that I get the latitude and longitude of the name of a place when I click on a button. However, of late, it is not working. It prints that "Address x failed to Geocode. Received status " Note that x is a given address and no status code is given.
$id=$_REQUEST['id'];
define("MAPS_HOST", "maps.googleapis.com");
define("KEY", "xxxxxxx");
$query = "SELECT * FROM markers WHERE mid = $id LIMIT 1";
$result = mysql_query($query);
if (!$result) {
die("Invalid query: " . mysql_error());
}
// Initialize delay in geocode speed
$delay = 0;
$base_url = "http://" . MAPS_HOST . "/maps/api/geocode/xml?address=";
if($row = #mysql_fetch_assoc($result)){
$geocode_pending = true;
$address = $row["address"];
while ($geocode_pending) {
$request_url = $base_url . urlencode($address) . "&sensor=false&key=" . KEY;
$xml = simplexml_load_file($request_url) or die("url not loading");
$status = $xml->Response->Status->code;
if (strcmp($status, "200") == 0) {
// Successful geocode
$geocode_pending = false;
$coordinates = $xml->Response->Placemark->Point->coordinates;
//$coordinatesSplit = split(",", $coordinates);
// Format: Longitude, Latitude, Altitude
//$lat = $coordinatesSplit[1];
//$lng = $coordinatesSplit[0];
list($lat,$lng) = explode(",",$coordinates);
$query = sprintf("UPDATE markers " .
" SET lat = '%s', lng = '%s' " .
" WHERE mid = '%s' LIMIT 1;",
mysql_real_escape_string($lng),
mysql_real_escape_string($lat),
mysql_real_escape_string($id));
$update_result = mysql_query($query);
if (!$update_result) {
die("Invalid query: " . mysql_error());
}else{
echo "$lat;$lng";
}
} else if (strcmp($status, "620") == 0) {
// sent geocodes too fast
$delay += 100000;
} else {
// failure to geocode
$geocode_pending = false;
echo "Address " . $address . " failed to geocode. ";
echo "Received status " . $status . "
\n";
}
usleep($delay);
}
}

I'm not sure on which API your code is based on, but the response of the current API will not work with these lines:
$status = $xml->Response->Status->code;
if (strcmp($status, "200") == 0) {
There are no elements Response,Status or code, furthermore the response will not contain a numeric status-code.
use this instead:
$status = $xml->status;
if (strcmp($status, "OK") == 0) {
To fix the rest of the code please take a look at the structure of the returned XML, there are also no elements Placemark,Point and coordinates.
it should be:
$lat = $xml->result->geometry->location->lat;
$lng = $xml->result->geometry->location->lng;

Related

Invalid parameter: token 1 is not defined in the query

Here is my code to filter pets base on a JSON ajax Query
I am getting error follwoing image
public function filter($object, $active=true){
$query = $this->createQueryBuilder('p');
$query->innerjoin('TadpetProfessionalBundle:ProPet', 'pp', 'WITH', 'pp.professionalId = p.id');
$query->innerjoin('TadpetManagerBundle:Pet', 'ppp', 'WITH', 'ppp.id = pp.petId');
$query->where('p.isActive = :active')
->setParameter('active', $active);
if(!empty($object->pets)){
$qString = "";
for($i=1; $i<=sizeof($object->pets); $i++){
if($i == 1){
$qString .= "ppp.name = :petname".$i;
}else{
$qString .= " OR ppp.name = :petname".$i;
}
}
$query->andWhere($qString);
$query->setParameter('petname'+1,$object->pets[0]);
$query->setParameter('petname'+2,$object->pets[1]);
$query->setParameter('petname'+3,$object->pets[2]);
}
return $query->getQuery()->getResult();
}
Help me please
In these lines:
$query->setParameter('petname'+1,$object->pets[0]);
$query->setParameter('petname'+2,$object->pets[1]);
$query->setParameter('petname'+3,$object->pets[2]);
You are adding 'petname' to the numbers, but you should concatenate them:
$query->setParameter('petname'.1,$object->pets[0]);
$query->setParameter('petname'.2,$object->pets[1]);
$query->setParameter('petname'.3,$object->pets[2]);
Also, you could use a loop:
for($i=1; $i<=sizeof($object->pets); $i++){
$query->setParameter('petname'.$i,$object->pets[$i-1]);
}

How to get all data from easyui datagrid

I had try to use the getData e.g.
data = $("#dg").datagrid("getData");`
var total = data.total; (total is 100)`
var rows = data.rows; (rows.length is 25)`
It can result: the total number is correct like 100 records
but the rows return only get the current page rows like 25 rows.
I need to get all of the records (100 rows).
Is there something i missed ? Or how can we do this ? Please help me.
This is because of pagination. let me describe model with pagination for showing 100 row in php.
function get_invoiceinfoList($search_keyword,$custID){
$page = 1;
$rows = 100;
$sort = '';
$order = 'asc';
$offset = ($page - 1) * $rows;
if($custID > 0 && $search_keyword == 0){
$search = " and a.customer_id =$custID";
}else{
$search = "and (b.name like '%$search_keyword%' || a.inv_no like '%$search_keyword%')" ;
}
$vQuery=$this->db->query("SELECT a.inv_id,a.inv_no,a.inv_org,a.inv_date,
a.customer_id,a.heading,a.quot_id,a.total_cost as total_amount,
a.paid_amount,(a.total_cost-a.paid_amount)as due_amount,b.name
from sales_invoice a,view_customer_info b
where
a.customer_id = b.customer_id $search order by a.inv_date DESC limit $offset, $rows");
$result = $vQuery->result();
$rows = array();
foreach ($result as $rowData){
array_push($rows, $rowData);
}
$data['rows'] = $rows;
return $data;
}

Changing a long imperative block of code into a more functional programming style

I am new to functional programming and I want to learn how to structure my programs by composing functions (so that I can choose which ones to use a-la-carte based on my needs)
I have a long block of imperative code that goes like this in pseudo-code:
function do_complicated_stuff(input) {
//do some DB stuff and get information about A,B,C,D
//prepare Output A
//prepare Output B
//prepare Output C
//prepare Output D
if(condition) {
A = "I am A1"
B = "I am B1"
C = "I am C1"
D = "I am D1"
} else {
//do the same as above, but change to I am A2, B2, C2, D2
}
array = {A, B, C, D};
return array;
}
Is there a way to write this as function application instead of imperative code? Things I want to simplify: I don't want to handle A, B, C, D explicitly so I don't want to make function calls like do_other_stuff(A, B, C, D, db_stuff_required_for_A, db_stuff_required_for_B)
So clearly I want to have a function like do_other_stuff(one_item), but the eventual return value should be something like "I am A1" if one_item is A and condition is true and "I am B2" if condition is false and one_item is B.
I know how I would do this in an OOP way, I guess I'd have a bunch of objects that know what to do with their own data where I just need to call item.other_stuff() and it figures it out. How would I write the same thing in a more functional style, composing many short functions that do one thing to give me the desired "I am L#" result in the end? Note that you need different DB information for each of the eight cases that sometimes overlaps and is sometimes completely different between each case. So it's currently very complected and not very simple, since the function in my current code is over 100 lines and handles all eight cases explicitly. Worse, the same thing is done again in a different way with a different output format like "This is A1" somewhere else. So I'd like to separate the output from the processing and from the DB calls. Let's assume I could pick any language to re-implement this in, so take any functional feature you want. How would I do this and which abstractions/language features do I need?
Brace yourself, this is the ACTUAL php code and it's not pretty and handles only half of the cases (but I want to extend it to cover everything, of course, instead of using the old code)
function do_complicated_stuff(Buysellitem $item) {
$result = new stdClass();
global $user_currency;
$curr_obj = get_cached('getCurrenciesDAO', 'load', array($item->currencyID));
$price = CurrencyConverter::convert($curr_obj->abbr, $user_currency->abbr, $item->price);
$dollarPrice = CurrencyConverter::convert($curr_obj->abbr, 'USD', $item->price);
$item_cat_id = $item->categoryId;
if(!empty($item_cat_id)) {
$item_cat = DAOFactory::getCategoryDetailsDAO()->load($item_cat_id)->categoryNameEn;
}
$designer_obj = DAOFactory::getUsersDAO()->load($item->userID);
$item_images = DAOFactory::getBuysellitemimagesDAO()->queryByBuySellID($item->buySellID);
foreach($item_images as $cur_image) {
if($cur_image->isDefault) {
if(!empty($cur_image->aspectRatio) && $cur_image->aspectRatio > 0){
$main_image_height = round(498 / $cur_image->aspectRatio);
$main_image = DOMAIN . SELLIMG_PATH .
File_Controller::getImage($cur_image->buySellItemImagePath, 498, $main_image_height);
}else{
$main_image = '';
}
}
}
$designerName = decode_entities($designer_obj->companyName);
$trim_cat = !empty($item_cat) ? ' #' . strtolower(preg_replace('/\s+/', '', $item_cat)) : '';
$desc = decode_entities($item->description);
$trim_desc = str_short($desc, SHARE_LENGTH);
$item_link = SHARE_ITEM_LINK . $item->buySellID;
$item_name = str_short(decode_entities($item->buySellName), TW_SHARE);
if(!empty($price)) {
$decimals = $price < 10 ? 2 : 0;
$dollarDecimals = $price < 10 ? 2 : 0;
$priceFormatted = number_format($price, $decimals, '.', '');
$dollarPriceFormatted = number_format($dollarPrice, $dollarDecimals, '.', '');
//if the currency is SEK it doesn't have a sign, so show the abbreviation instead
$curr_abbr = empty($curr_obj->sign) ? $curr_obj->abbr : '';
$price_tag = ($item->discount > 0) ?
", at {$item->discount}% off":
" - {$curr_obj->sign}$priceFormatted$curr_abbr";
$d_price_tag = ($item->discount > 0) ?
", at {$item->discount}% off":
" - \$$dollarPriceFormatted";
} else {
$price_tag = '';
$d_price_tag = '';
}
$text = "{$item_name}$price_tag by $designerName";
$pi_html = "$item_link \n {$item_name}$d_price_tag by $designerName \n $trim_desc";
$tw_text = "$text$trim_cat #design";
$tu_html = "<a href='$item_link'><strong>$text</strong></a><br/>$desc";
$result->facebook = new stdClass();
$result->twitter = new stdClass();
$result->tumblr = new stdClass();
$result->pinterest = new stdClass();
if(empty($item->video)) {
$result->facebook->link = FB_LINK . '?' . http_build_query(array(
'u'=>$item_link,
'display'=>'popup',
'redirect_uri'=>FACEBOOK_TRACK
), '', '&');
$result->twitter->link = TW_LINK . '?' . http_build_query(array(
'original_referrer'=> DOMAIN . $_SERVER['PHP_SELF'],
'url'=>$item_link,
'related'=>'CityBlis',
'via'=>'CityBlis',
'text'=>$tw_text
), '', '&');
$result->tumblr->link = TU_LINK . '?' . http_build_query(array(
'source'=>$main_image,
'caption'=>$tu_html,
'clickthru'=> $item_link
), '', '&');
$result->pinterest->link = PI_LINK . '?' . http_build_query(array(
'url'=>$item_link,
'media'=>$main_image,
'description'=>$pi_html
), '', '&');
} else {
$video_link = youtube_vimeo($item->video);
$result->facebook->link = FB_LINK . '?' . http_build_query(array(
'link'=>$item_link,
'display'=>'popup',
'source'=>$video_link,
'picture'=>$main_image,
'redirect_uri'=>FACEBOOK_TRACK
), '', '&');
$result->twitter->link = TW_LINK . '?' . http_build_query(array(
'original_referrer'=> DOMAIN . $_SERVER['PHP_SELF'],
'url'=>$item_link,
'related'=>'CityBlis',
'via'=>'CityBlis',
'text'=>$tw_text
), '', '&');
$result->tumblr->link = TU_LINK . '?' . http_build_query(array(
'embed'=>$video_link,
'caption'=>$tu_html
), '', '&');
$result->pinterest->link = PI_LINK . '?' . http_build_query(array(
'url'=>$video_link,
'media'=>$main_image,
'description'=>$pi_html,
'is_video'=>'true'
), '', '&');
}
return $result;
}
function inline_product_share($input) {
$item = do_complicated_stuff($input);
$item->facebook->title = FB_TITLE;
$item->facebook->innerStyle = '';
$item->facebook->dimensions = '';
$item->facebook->follow = '';
$item->twitter->title = TW_TITLE;
$item->twitter->innerStyle = '';
$item->twitter->dimensions = '';
$item->twitter->follow = '';
$item->tumblr->title = TU_TITLE;
$item->tumblr->innerStyle = '';
$item->tumblr->dimensions = '';
$item->tumblr->follow = '';
$item->pinterest->title = PI_TITLE;
$item->pinterest->innerStyle = '';
$item->pinterest->dimensions = '';
$item->pinterest->follow = '';
return order_output($item);
}
//does the ordering of the output and returns the resultant string
function order_output($item) {
$style_string = "position:relative;display:inline-block;width:25px;height:25px;
overflow:hidden;margin-left:4px;vertical-align:top;border-radius:17px;
background-image: url(\"/i/iSpr.png\");"; //TODO: make it an absolute path when we put it up
$style = " style='$style_string;";
$item->facebook->style = $style . "background-color:#3c5897;background-position:-28px 0px;'";
$item->twitter->style = $style . "background-color:#2daae0;background-position:-55px 0px;'";
$item->tumblr->style = $style . "background-color:#2a4361;background-position:-82px 0px;'";
$item->pinterest->style = $style . "background-color:#ca1f25;background-position:-108px 0px;'";
return output_item($item->facebook) .
output_item($item->twitter) .
output_item($item->tumblr) .
output_item($item->pinterest);
}
//its only responsibility is to accept an object to return the output html
function output_item($item) {
ob_start();
?><div<?php echo $item->style?>><a target="_blank" title="<?php
echo $item->title?>"<?php
echo $item->innerStyle?> href="<?php
echo $item->link
?>"<?php
echo $item->follow?><?php
echo $item->dimensions?>><?php
echo $item->title?></a></div><?php
$output = ob_get_contents();
ob_end_clean();
return $output;
}
I don't belive I got enough information to hit the nail on the head since you didn't say anything about the nature of A, B, C and D. However, if they are anything like sub classes and we want to perform some kind of operation on all of them that are inherited we have the iam function that treats them similar. The condition I don't know where came from so I added it as an argument and in the anonymous function index, which is derievd from condition, is's closed in from the scope of which the function is created.
function iam(item, index)
{
return "I am " . item . index; // Might be more advanced than this
}
function do_complicated_stuff(input, condition) {
array_of_abcd = db_readabcd(input);
index = (condition ? 1 : 2);
handle = function(item)
{
// function has index as free variable
return iam( item, index );
}
// Use map to iterate over the elelemts of the array
// applying handle on each one
return map(handle array_of_abcd);
}
This example shows two properties of functional programming. Closures and higher order functions. Here is the same in Scheme:
(define (iam item index)
(string-append "I am "
item
index))
(define (do-complecated-stuff input condition)
(let ([array-of-abcd (db-readabcd input)] ; get data
[index (number->string (if condition 1 2))]) ; get index
; use map to iterate over elements with an anonymous function
(map (lambda (item) (iam item index)) array-of-abcd)))

Counts and left join not working right

Trying to do a count on these lines COUNT(engineerName) AS engineerCount,
Count(managerName) as managerCount,
Count(isContractor) as contractorCount
but it keeps returning the same numbers for all three. So I'm trying to add a Where for each one, Example Count(isContractor where isContractor = 'yes') as contractorCount but getting errors please help, thank you.
<?php
clASs EfficiencyController extends DooController
{
function getEfficiency(){
include './protected/config/db.conf.php';
Doo::db()->setDb($dbconfig, 'local_network');
$Vendor = ($_SERVER['REQUEST_METHOD'] == "POST") ? $_POST['Vendor'] : $_GET['Vendor'];
$date = ($_SERVER['REQUEST_METHOD'] == "POST") ? $_POST['date'] : $_GET['date'];
$level = ($_SERVER['REQUEST_METHOD'] == "POST") ? $_POST['level'] : $_GET['level'];
switch($level) {
case "Region":
case "area":
$Market99="";
break;
default:
$Market99=$level;
break;
}
{
//
// LUCENT,NORTEL
//
$query = " SELECT
DayKey,
Market99,
Region,
areaName,
Sum(Total_Sites) as totalCount,
Max(engineerCount) AS engineerCount,
Max(managerCount) AS managerCount,
Max(contractorCount) AS contractorCount,
SC_Type,
Sum(Total_Carriers),
Sum(Total_Sectors),
Vendor
FROM
network.envEquipSummaryConfig a
Left Join
(SELECT
market,
areaName,
COUNT(engineerName) AS engineerCount,
Count(managerName) as managerCount,
Count(isContractor) as contractorCount
FROM
employee.employees
GROUP BY market
ORDER BY COUNT(market) DESC) b ON a.Market99 = b.market
Where
a.DayKey <= \"$date\" and a.Vendor = \"$Vendor\"
Group By Market99 asc";
switch($level) {
case "region":
$query = $query. " order by region ASC";
break;
case "area":
$query = $query. " order by areaName ASC";
break;
default;
$query = $query. " order by Market99 ASC";
break;
}
}
//echo $query; exit;
$this->setContentType('xml');
$result = Doo::db()->fetchAll($query);
printf("<root>\n");
if(count($result) > 0)
foreach($result AS $row) {
printf("\t<data>\n");
printf("\t\t<date>%s</date>\n",$row["DayKey"]);
printf("\t\t<vName>%s</vName>\n",$row["Vendor"]);
printf("\t\t<location>%s</location>\n",$row["Market99"]);
printf("\t\t<toCount>%s</toCount>\n",$row["totalCount"]);
printf("\t\t<enCount>%s</enCount>\n",$row["engineerCount"]);
printf("\t\t<mnCount>%s</mnCount>\n",$row["managerCount"]);
printf("\t\t<cnCount>%s</cnCount>\n",$row["contractorCount"]);
printf("\t</data>\n");
}
printf("</root>\n");
}
}
?>
SELECT
market,
areaName,
COUNT(engineerName) AS engineerCount,
Count(managerName) as managerCount,
Count(isContractor) as contractorCount
FROM
employee.employees
GROUP BY market
should be
Group By market,areaName at a guess.
Which is all it can be seeing as you've provided next to no useful information.

Drupal db_query_range SQL query

I'm trying to get this working and the query executes but nothing comes back. I've tried everything I can think of, can you spot what I'm doing wrong?
$nido = $node->nid;
$result = db_query_range('
SELECT i.nid, i.iid, a.fid, p.filename, p.filepath
FROM {drup_image_attach} i
LEFT JOIN {drup_image} a ON i.iid = a.nid
LEFT JOIN {drup_files} p ON a.fid = p.fid
WHERE i.nid = %d AND p.filename = "recipe_thumb"', $nido, 0, 10);
echo "Filepath = " . $result ->filepath. "<br>";
echo "Filepath = " . $result ->filename . "<br>";
echo "IID = " . $result ->iid. "<br>";
echo "NID = " . $result ->nid . "<br>";
}
EDIT - I sorted out a couple of bits, but the output is still empty!
EDIT - this is the working code:
$nodeid = $node->nid;
$get_image = db_query('
SELECT p.filepath as imagefilename
FROM {image_attach} i
LEFT JOIN {image} a ON i.iid = a.nid
LEFT JOIN {files} p ON a.fid = p.fid
WHERE i.nid = %d AND p.filename = "recipe_thumb"', $nodeid);
$obj_image = db_fetch_object($get_image);
$imagefilename = $obj_image->imagefilename;
$result is a mysql(i) resource only. You first have to fetch the row/object.
$result = db_query_range(....);
$object = db_fetch_object($result);
print_r $object;
Assuming you have a range ob results not a single result this should work. You need to store the results in an array or process them in a different manner. for a single result see db_result()
$nodeid = $node->nid;
$get_image = db_query('
SELECT p.filepath as imagefilename
FROM {image_attach} i
LEFT JOIN {image} a ON i.iid = a.nid
LEFT JOIN {files} p ON a.fid = p.fid
WHERE i.nid = %d AND p.filename = "recipe_thumb"', $nodeid);
while(($obj_image = db_fetch_object($obj_image)) == TRUE){
$imagefilename[] = $obj_image->imagefilename;
}

Resources