Google geocoder v2 and v3 - google-maps-api-3

Until recently I've been using google geocoding to provide coordinates to be saved in a database. However, when I recently tried to do this it failed, with error 610. I was still using v2 and I understand this is phasing out. So, I came on this website and had a look at this thread: Changing from Google maps api v2 to v3. I updated my code in line with the following (which I understand from the feedback worked) from this thread:
These are, changing the address for v3 geocoding
define("MAPS_HOST", "maps.googleapis.com");
$base_url = "http://" . MAPS_HOST . "/maps/api/geocode/xml?";
$request_url = $base_url . "address=" . urlencode($address) . "&sensor=false";
And secondly changing the path in the returned xml file for setting lat/long
$coordinates = $xml->Response->Placemark->Point->coordinates;
$coordinatesSplit = split(",", $coordinates);
// Format: Longitude, Latitude, Altitude
$lat = $coordinatesSplit[1];
$lng = $coordinatesSplit[0];
Can be completely replaced with
$lat = $xml->result->geometry->location->lat;
$lng = $xml->result->geometry->location->lng;
But still not working for me. I no longer get error 610 when I try to run it, just "failed to geocode, error code ".
Apologies I'm still relatively novice with this stuff, learning as I go really, so I appreciate any help you can give. It may be the simplest thing I'm missing. Here's my code currently:
<?php
require("phpsqlgeocode_dbinfo.php");
define("MAPS_HOST", "maps.googleapis.com");
define("KEY", *my key*);
// Opens a connection to a MySQL server
$connection = mysql_connect('*name*', $username, $password);
if (!$connection) {
die("Not connected : " . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die("Can\'t use db : " . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 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?";
// Iterate through the rows, geocoding each address
while ($row = #mysql_fetch_assoc($result)) {
$geocode_pending = true;
while ($geocode_pending) {
$address = $row["address"];
$id = $row["id"];
$request_url = $base_url . "address=" . urlencode($address) . "&sensor=false";
$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;
$lat = $xml->result->geometry->location->lat;
$lng = $xml->result->geometry->location->lng;
$query = sprintf("UPDATE markers " .
" SET lat = '%s', lng = '%s' " .
" WHERE id = '%s' LIMIT 1;",
mysql_real_escape_string($lat),
mysql_real_escape_string($lng),
mysql_real_escape_string($id));
$update_result = mysql_query($query);
if (!$update_result) {
die("Invalid query: " . mysql_error());
}
} else if (strcmp($status, "620") == 0) {
// sent geocodes too fast
$delay += 100000;
} else {
// failure to geocode
$geocode_pending = false;
echo "Address " . $address . " failed to geocoded. ";
echo "Received status " . $status . "
\n";
}
usleep($delay);
}
}
?>
Thanks so much!

This is what I did. I was having the same problem and now everything works perfectly.
<?php
$sql = "SELECT * FROM locations WHERE lat IS NULL AND lng IS NULL";
$res = mysql_query( $sql );
while( $row = mysql_fetch_assoc( $res ) ) {
$address = $row['address_1'] . ", " . $row['city'] . " " . $row['state'] . " " . $row['zip'];
$latlng = geocode( $address );
echo $address . "<br />";
if( $latlng[0] && $latlng[1] ) {
print_r( $latlng );
echo "<br />";
$update = "UPDATE locations SET lat = '" . $latlng[0] . "', lng = '" . $latlng[1] . "' WHERE id = " . $row['id'] . " LIMIT 1";
$update_res = mysql_query( $update );
echo $update . "<br />";
} else {
echo $latlng[2] . "<br />";
}
echo "<br />";
}
function geocode( $address ) {
if( empty( $address ) ) {
return array("", "", "");
}
$base_url = "http://maps.googleapis.com/maps/api/geocode/xml";
$request_url = $base_url . "?address=" . urlencode( $address ) . "&sensor=false" ;
$xml = simplexml_load_file( $request_url );
$status = $xml->status;
if (strcmp($status, "OK") == 0) {
$lat = $xml->result->geometry->location->lat;
$lng = $xml->result->geometry->location->lng;
return array( $lat, $lng, $request_url );
} else {
return array("", "", $request_url);
}
}
?>

Related

Wordpress plugin WP_error

I installed ISMS Plugin into my wordpress in order to try out the SMS service through Wordpress. However an error appeared when I click on the iSMS setting on the plugin menu.
Here is the error:
**
Fatal error: Cannot use object of type WP_Error as array in C:\wamp\www\wordpress\wp-content\plugins\isms\isms-model.php on line 17**
and here's the code for line 17:
$result = $response[body];
here is the full code for isms-model.php
<?php
class Mobiweb_ISMS_Model {
// iSMS API
protected static $api_balance = 'https://www.isms.com.my/isms_balance.php';
protected static $api_send = 'https://www.isms.com.my/isms_send.php';
public static function get_balance() {
$username = get_option('setting_username');
$password = get_option('setting_password');
$link = self::$api_balance.'?';
$link .= "un=".urlencode($username);
$link .= "&pwd=".urlencode($password);
$response = wp_remote_get($link);
$result = $response[body];
$balance = (float)$result;
if ($balance < 0) return substr($result, 8);
else return $result;
}
public static function send_isms($destination, $message, $messageType, $senderID = '') {
$username = get_option('setting_username');
$password = get_option('setting_password');
$link = self::$api_send.'?';
$link .= "un=".urlencode($username);
$link .= "&pwd=".urlencode($password);
$link .= "&dstno=".urlencode($destination);
$link .= "&msg=".urlencode($message);
$link .= "&type=".urlencode($messageType);
$link .= "&sendid=".urlencode($senderID);
$response = wp_remote_get($link);
try {
$result = $response[body];
$resultValue = (float)$result;
if ($resultValue < 0) {
return array(
'code'=>$resultValue,
'message'=>substr($result, 8)
);
} else {
return array(
'code'=>'2000',
'message'=>$result
);
}
} catch (Exception $e) {
$message = $e->getMessage();
return array(
'code'=>'-9999',
'message'=>$message
);
}
}
}
?>
What should I do to fix it? Any advise?
This plugin is badly written.
wp_remote_get() returns a WP_Error object when there's an error. Therefore, at least for debugging it and seeing what the error is, I would suggest you change it from:
$response = wp_remote_get($link);
$result = $response[body];
to
$response = wp_remote_get($link);
if (is_wp_error($response)) {
die($response->get_error_message());
}
$result = $response['body'];

Using a loop to fill excel file instead of hard coding cell co-ordinates

I have this code listing which exports data to an excel file shown here!, I would like to use a loop that does the same thing instead of hard coding it, suggestions!
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load("workbooks/" . $labref . "/" . $labref . ".xlsx");
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()
->setCellValue('I3', $heading)
->setCellValue('I5', 'Standard Preparation For Assay')
->setCellValue('B7', 'Weight')
…………
//Assay Standard Preparation desired
->setCellValue('A8', 'Desired Weight')
->setCellValue('B8', $weight)
->setCellValue('C8', $vf1)
…………………..
//Other values used
->setCellValue('D22', 'Label Claim')
->setCellValue('D23', 'Tabs or Caps Average')
……..
$objPHPExcel->getActiveSheet()->setTitle($heading);
$dir = "workbooks";
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save("workbooks/" . $labref . "/" . $labref . ".xlsx");
}
}
Try something like this
$data = R::getAll('SELECT * FROM form'); //Im using redbean
$url = // Your url from the root dir -> the folder you wanna save to
$header = array();
$index = 0;
foreach ($data[0] as $key => $value) {
$header[$index] = $key;
$index += 1;
}
try {
$sheet = new PHPExcel();
$sheet->getProperties()->setCreator('Username')
->setLastModifiedBy('Username')
->setTitle('Title');
$sheet->getDefaultStyle()->getAlignment()->setVertical(
PHPExcel_Style_Alignment::VERTICAL_TOP);
$sheet->getDefaultStyle()->getAlignment()->setHorizontal(
PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$sheet->getDefaultStyle()->getFont()->setName('Calibri');
$sheet->getDefaultStyle()->getFont()->setSize(12);
$sheet->setActiveSheetIndex(0);
$activeSheet = $sheet->getActiveSheet();
$colHeaders = $header;
$col = 'B';
$rownum = 2;
foreach ($colHeaders as $h) {
$activeSheet->setCellValue($col . $rownum, $h);
$activeSheet->getStyle($col . $rownum)->getFont()->setBold(true);
$activeSheet->getColumnDimension($col)->setAutoSize(true);
$col++;
}
foreach ($data as $k => $v) {
$col = 'B';
$rownum++;
if ($k != count($data)) {
foreach ($v as $value) {
$activeSheet->setCellValue($col++ . $rownum, $value);
}
} else {
foreach ($v as $value) {
$rownum++;
$activeSheet->setCellValue($col++ . $rownum, $value);
}
}
}
$writer = PHPExcel_IOFactory::createWriter($sheet, 'Excel2007');
// The URL needs to be a absolute path from the root folder to the save folder
// time() makes sure that the file has a uniq name and allso makes it easy to
// see the leatest verson of it.
$saveObj = $url . time() . '';
$writer->save($saveObj);
exit();
} catch (Exception $e) {
$error = $e->getMessage();
// print("<pre>".print_r($error,true)."</pre>");
}
print("<pre>".print_r($error,true)."</pre>");
exit();

IPN - not working

I have problem to get the IPN from PayPal.
This is the server log error:
[22-Aug-2013 19:45:34 Asia/Jerusalem] PHP Warning: mysql_query() [function.mysql-query]: Access denied for user 'reshopco'#'localhost' (using password: NO) in /home/reshopco/public_html/8813/paypal3.php on line 61
[22-Aug-2013 19:45:34 Asia/Jerusalem] PHP Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /home/reshopco/public_html/8813/paypal3.php on line 61
Is there a problem with the code or possibly a problem in our server?
This is the code that I got from the PayPal example:
<?
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value)
{
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
// post back to PayPal system to validate
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Host: www.paypal.com\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$header .= "Connection: close\r\n\r\n";
$fp = fsockopen ('www.paypal.com', 80, $errno, $errstr, 30);
$payment_status = $_POST['payment_status'];
$custom = $_POST["custom"];
$txn_type = $_POST["txn_type"];
// YOU CAN ALSO RETRIEVE ADDITIONAL FIELDS SUCH AS:
// $payment_currency = $_POST['mc_currency'];
// $txn_id = $_POST['txn_id'];
// $receiver_email = $_POST['receiver_email'];
// $payer_email = $_POST['payer_email'];
// $invoice = $_POST['invoice'];
// $firstName = $_POST["first_name"];
// $lastName = $_POST["last_name"];
// $street = $_POST["address_street"];
// $city = $_POST["address_city"];
// $pcode = $_POST["address_zip"];
// $county = $_POST["address_state"];
// $country = $_POST["address_country"];
if (!$fp)
{
echo "HTTP ERROR";
}
else
{ // start 1
fputs ($fp, $header . $req);
while (!feof($fp))
{ // start 2
$res = fgets ($fp, 1024);
if (strcmp ($res, "VERIFIED") == 0)
{ // start 3
// ONLY DO THE PROCESSING IF THE STATIS IS COMPLETED (REFUNDS ALSO HIT THE IPN)
if ($payment_status == "Completed")
{ // start 4
// IF THE PAYMENT HAS BEEN MADE UPDATE OUR OIRDERS TABLE
// WE PASSED OUR ORDER NUMBER TO PAYPAL IN THE custom FIELD AND USE THIS TO UPDATE THE CORRECT ORDER
$sql = "Update orderstaable set processed = 0, paymentmethod = 'PAYPAL', orderdate = NOW() where orderid = $custom";
$execute = MYSQL_QUERY($sql);
// SEND CUSTOMER EMAIL OR WHATEVER
} // end 4
} // end 3
else if (strcmp ($res, "INVALID") == 1)
{ // start 6
// log for manual investigation
// email technical support
} // end 6
} // end 2
fclose ($fp);
}// end 1
?>
The error that you're getting in your log is because the user/password combo you're using to connect to your MySQL database is incorrect.

Print data from database to a particular block content

I need to print a simple data from database to a particular block, I have used the code given below and got the text out put but it is not located in the block specified(hello_world).
function hello_world_block_view($delta = '') {
$block = array();
if ($delta == 'hello_world') {
$sql = "SELECT Test_name FROM Test_table";
$result = db_query($sql);
$record = $result->fetch();
foreach ($record as $records) {
echo $records;
}
$block['subject'] = t('Hello world Subject');
$block['content'] = t('Need to print database content');
}
return $block;
}
You need to connect variable $records with $block['content']. So it can looks like:
function hello_world_block_view($delta = '') {
$block = array();
if ($delta == 'hello_world') {
$output = '';
$sql = "SELECT Test_name FROM Test_table";
$result = db_query($sql);
$record = $result->fetch();
foreach ($record as $records) {
$output .= $records;
}
$block['subject'] = t('Hello world Subject');
$block['content'] = $output;
}
return $block;
}

Opencart session info in Wordpress

I have a site that is using both WordPress and Opencart. The main site is built off of WP and then there is an OC site in a sub-directory.
I would like to bring the session data from OC into the wordpress site so I can have the Wishlist, Shopping Cart, Checkout, Login status and My Account info throughout the site.
Does anyone know what code I can add to WP to bring in this info?
Thanks again in advance,
Matt
There are already many articles regarding module development and export and session building in OpenCart.
Given your existing pages:
yoursite.com/wordpress
yoursite.com/wordpress/page.php (i.e. your page outside the shop),
yoursite.com/products/catalog/controller/common/header.php -and-
yoursite/products/catalog/view/theme/default/template/common/header.tpl
1. Create file headerXYZ.php using the following code and save it to the root directory of your main site (or other location of your choosing outside your OC shop).
<?php
// Config
require_once('shop/config.php');
// VirtualQMOD
require_once('shop/vqmod/vqmod.php');
$vqmod = new VQMod();
// VQMODDED Startup
require_once($vqmod->modCheck(DIR_SYSTEM . 'startup.php'));
// Application Classes
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/customer.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/affiliate.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/currency.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/tax.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/weight.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/length.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/cart.php'));
$myVar = array();
$myVar = array();
// Registry
$registry = new Registry();
// Loader
$loader = new Loader($registry);
$registry->set('load', $loader);
// Config
$config = new Config();
$registry->set('config', $config);
// Database
$db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
$registry->set('db', $db);
// Url
$url = new Url($config->get('config_url'), $config->get('config_use_ssl') ? $config->get('config_ssl') :
$config->get('config_url'));
$registry->set('url', $url);
// Log
$log = new Log($config->get('config_error_filename'));
$registry->set('log', $log);
function error_handler($errno, $errstr, $errfile, $errline) {
global $log, $config;
switch ($errno) {
case E_NOTICE:
case E_USER_NOTICE:
$error = 'Notice';
break;
case E_WARNING:
case E_USER_WARNING:
$error = 'Warning';
break;
case E_ERROR:
case E_USER_ERROR:
$error = 'Fatal Error';
break;
default:
$error = 'Unknown';
break;
}
if ($config->get('config_error_display')) {
echo '<b>' . $error . '</b>: ' . $errstr . ' in <b>' . $errfile . '</b> on line <b>' . $errline . '</b>';
}
if ($config->get('config_error_log')) {
$log->write('PHP ' . $error . ': ' . $errstr . ' in ' . $errfile . ' on line ' . $errline);
}
return true;
}
// Error Handler
set_error_handler('error_handler');
// Request
$request = new Request();
$registry->set('request', $request);
// Response
$response = new Response();
$response->addHeader('Content-Type: text/html; charset=utf-8');
$response->setCompression($config->get('config_compression'));
$registry->set('response', $response);
// Cache
$cache = new Cache();
$registry->set('cache', $cache);
// Session
$session = new Session();
$registry->set('session', $session);
// Language Detection
$languages = array();
$query = $db->query("SELECT * FROM " . DB_PREFIX . "language");
foreach ($query->rows as $result) {
$languages[$result['code']] = $result;
}
$detect = '';
if (isset($request->server['HTTP_ACCEPT_LANGUAGE']) && ($request->server['HTTP_ACCEPT_LANGUAGE'])) {
$browser_languages = explode(',', $request->server['HTTP_ACCEPT_LANGUAGE']);
foreach ($browser_languages as $browser_language) {
foreach ($languages as $key => $value) {
if ($value['status']) {
$locale = explode(',', $value['locale']);
if (in_array($browser_language, $locale)) {
$detect = $key;
}
}
}
}
}
if (isset($request->get['language']) && array_key_exists($request->get['language'], $languages) &&
$languages[$request->get['language']]['status']) {
$code = $request->get['language'];
} elseif (isset($session->data['language']) && array_key_exists($session->data['language'], $languages)) {
$code = $session->data['language'];
} elseif (isset($request->cookie['language']) && array_key_exists($request->cookie['language'], $languages)) {
$code = $request->cookie['language'];
} elseif ($detect) {
$code = $detect;
} else {
$code = $config->get('config_language');
}
if (!isset($session->data['language']) || $session->data['language'] != $code) {
$session->data['language'] = $code;
}
if (!isset($request->cookie['language']) || $request->cookie['language'] != $code) {
setcookie('language', $code, time() + 60 * 60 * 24 * 30, '/', $request->server['HTTP_HOST']);
}
$config->set('config_language_id', $languages[$code]['language_id']);
$config->set('config_language', $languages[$code]['code']);
// Language
$language = new Language($languages[$code]['directory']);
$language->load($languages[$code]['filename']);
$registry->set('language', $language);
// Document
$document = new Document();
$registry->set('document', $document);
// Customer
$registry->set('customer', new Customer($registry));
// Affiliate
$affiliate = new Affiliate($registry);
$registry->set('affiliate', $affiliate);
if (isset($request->get['tracking']) && !isset($request->cookie['tracking'])) {
setcookie('tracking', $request->get['tracking'], time() + 3600 * 24 * 1000, '/');
}
// Currency
$registry->set('currency', new Currency($registry));
// Tax
$tax = new Tax($registry);
$registry->set('tax', $tax);
// Weight
$registry->set('weight', new Weight($registry));
// Length
$registry->set('length', new Length($registry));
// Cart
$registry->set('cart', new Cart($registry));
// Front Controller
$controller = new Front($registry);
// Maintenance Mode
$controller->addPreAction(new Action('common/maintenance'));
// SEO URL's
$controller->addPreAction(new Action('common/seo_url'));
// Router
if (isset($request->get['route'])) {
$action = new Action($request->get['route']);
} else {
$action = new Action('common/home');
}
// Dispatch
$controller->dispatch($action, new Action('error/not_found'));
2. Now, include headerXYZ.php in page.php i.e. Place the statement below on line 1 at the very top of page.php
<?php require_once ('headerXYZ.php');?>
3. Finally, right after the opening body tag of your external page.php page add the following list of statements
<?php
require_once('shop/catalog/model/total/sub_total.php');
require_once('shop/catalog/language/english/total/sub_total.php');
require_once('shop/catalog/model/total/reward.php');
require_once('shop/catalog/model/total/shipping.php');
require_once('shop/catalog/model/total/coupon.php');
require_once('shop/catalog/model/total/tax.php');
require_once('shop/catalog/model/total/credit.php');
require_once('shop/catalog/language/english/total/credit.php');
require_once('shop/catalog/model/total/voucher.php');
require_once('shop/catalog/model/total/total.php');
require_once('shop/catalog/language/english/total/total.php');
foreach($myVar as $key=>$value)
{
$$key = $value;
}
require_once('shop/catalog/controller/common/header.php');
require_once('shop/catalog/view/theme/default/template/common/header.tpl');
?>
That's it... You're done! You should now have a fully functional header (with working cart, login, etc.) in your page located outside of your Opencart shop.
SIDE NOTE: You could also just plug the entire code (including the content of headerXYZ.php and the 13 require_once statements) directly into the your external page.
I was looking for something similar, what I did was to write same html/css for footer and header in both systems, after that, I wrote an additional Wordpress plugin to show user and cart info when user is logged in opencart.
https://github.com/saRca/op2wp

Resources