Thursday 21 November 2013

Image zoom in and zoom out using Javascript

- Here is the code for simple image zoom in and zoom out using javascript.

Javascript and HTML Code:
---------------------------------------
<html>
<head>
<script language="javascript">
//set the time delay,imgsize,arrsize.
var delay=20;
var imgsize=5;
var timeon;
var wid;
var hei;
var i=0;
function zoom_out(p,q,which)
{
   if(which.width <= p)
      which.width += imgsize;
   if(which.height <= q)
      which.height += imgsize;
   if(which.width <= p)
   {
      var tmp=which.id;
      timeon=eval("setTimeout('zoom_out("+p+","+q+","+tmp+")', delay)");
   }

}

function zoom_in(r,s,asd)
{
 
  if(asd.width >= r)
      asd.width -= imgsize;
  if(asd.height >= s)
      asd.height -= imgsize;

  asd.width=r;
  asd.height=s;
  wid=asd.width;
  hei=asd.height;
}
</script>
</head>
<body>
<table align=center cellspacing=2 cellpadding=2 height=100% width=100%><tr>
<td align=center width=120 height=125 style='cursor:pointer;'>
<img id="myPicture1" src="images/book.gif" width="40" height="48" onMouseover="zoom_out(55,65,this)" onMouseout="zoom_in(40,48,this)"></td>
<td width=10></td>
<td align=center width=120 height=125 style='cursor:pointer;'>
<img id="myPicture2" src="images/globe.gif" width="40" height="48" onMouseover="zoom_out(55,65,this)" onMouseout="zoom_in(40,48,this)"></td>
<td width=10></td>
<td align=center width=120 height=125 style='cursor:pointer;'>
<img id="myPicture3" src="images/email.gif" width="40" height="48" onMouseover="zoom_out(55,65,this)" onMouseout="zoom_in(40,48,this)"></td>
<td width=10></td>
<td align=center width=120 height=125 style='cursor:pointer;'>
<img id="myPicture4" src="images/clock.gif" width="40" height="48" onMouseover="zoom_out(55,65,this)" onMouseout="zoom_in(40,48,this)"></td>
</tr>
<tr><td colspan=7>
</td></tr>
</table>
</body>
</html>

- Don't forget you need 4 images(book,globe,email,clock) in images folder in your local or project.


Wednesday 14 August 2013

Magento - Get Last Insert Id

- To get last inserted in magento there is two ways based on the insert method

First:

$connection    = Mage::getSingleton(’core/resource’)->getConnection(’core_write’);
$sql         = ”INSERT INTO `table` SET field1 = ?, field2 = ?, …”;
$connection->query($sql, array($field1_value, $field2_value, …));
$lastInsertId = $connection->lastInsertId();
echo $lastInsertId;


Second:

  $customAddress = Mage::getModel('customer/address');

         $customAddress->setData($_custom_address)
            ->setCustomerId($customer->getId())
            ->setIsDefaultBilling('0')
            ->setIsDefaultShipping('1')
            ->setSaveInAddressBook('1');

         try {
           $customAddress->save(); 
echo $customAddress->getId();

Sunday 11 August 2013

How to read German characters (äöü߀) in Excel via PHPExcel

- Using PHPExcel we can create excel in php.
- In that excel creation german characters not displayed when given that words directly like " Jörg Blümel "

- For that we need to use,

 - PHPExcel uses UTF-8 internally, so it will render all characters correctly if your html page is set as UTF-8
$value = "Jörg Blümel";
$newValue = iconv("ISO-8859-1", "UTF-8", $value);

Wednesday 31 July 2013

Magento - Magento TIPS

                To instert datat in DB
               ========================      
               $insert_data = array(
               col1 => value
               );
               $_conn = Mage::getSingleton('core/resource')->getConnection('core_write');
            $_conn->insert(Mage::getSingleton('core/resource')->getTableName('table_name'), $insert_data);
           
               =================================
           
               To use session
               ----------------
               protected function _getSession()
               {
                    return Mage::getSingleton('core/session');
               }
               $this->_getSession()->addSuccess(Mage::helper('module_name')->__('message goes here'));
           
               ======================================
               http://www.magentocommerce.com/knowledge-base/entry/magento-for-dev-part-8-varien-data-collections
           
               to select rows based on where
               ------------------------------
           
               var_dump((string)
               Mage::getModel('vendorinfo/favorites')
               ->getCollection()
               ->addFieldToFilter('user_id',$getCustomer['entity_id'])
               ->getSelect());        
               ============================================
Have a look at the helper class: Mage_Customer_Helper_Data
To simply get the customer name, you can write the following code:

$customerName = Mage::helper('customer')->getCustomerName();


For more information about the customer's entity id, website id, email, etc. you can use getCustomer function. The following code shows what you can get from it:-
echo "<pre>"; print_r(Mage::helper('customer')->getCustomer()->getData()); echo "</pre>";

               ============================================

Magento How get customer/user detail by Id

$customer_id = 1; // set this to the ID of the customer.
$customer_data = Mage::getModel('customer/customer')->load($customer_id);
print_r($customer_data);
Now if you want the customer name then you can use the following code:
$customer_data->getFirstname();

=====================================================================
Function to get wishlist items with out login based on wish_id

    public function getWishlistItems($wish_id)
    {
         $get_wishlist_data = Mage::getModel('wishlist/item')->getCollection();
          $get_wishlist_data->addFieldToSelect('product_id');
        return $get_wishlist_data->addFieldToFilter('main_table.wishlist_id', $wish_id);    
    }

Function to get wishlist collect

publicfunction getWishList(){
    $_itemCollection =Mage::helper('wishlist')->getWishlistItemCollection();
    $_itemsInWishList = array();foreach($_itemCollection as $_item){
        $_product = $_item->getProduct();

        $_itemsInWishList[$_product->getId()]= $_item;}return $_itemsInWishList;}
=====================================================================
http://blog.decryptweb.com/product-id-and-product-name/
1) Product details from Product ID.
<?php
$model = Mage::getModel('catalog/product') //getting product model

$_product = $model->load($productid); //getting product object for particular product id

echo $_product->getShortDescription(); //product's short description
echo $_product->getDescription(); // product's long description
echo $_product->getName(); //product name
echo $_product->getPrice(); //product's regular Price
echo $_product->getSpecialPrice(); //product's special Price
echo $_product->getProductUrl(); //product url
echo $_product->getImageUrl(); //product's image url
echo $_product->getSmallImageUrl(); //product's small image url
echo $_product->getThumbnailUrl(); //product's thumbnail image url

?>

==========================================================================
Using Collections in Magento
http://www.magentocommerce.com/wiki/5_-_modules_and_development/catalog/using_collections_in_magento

==========================================================================
Using Display error in Magento

put this in htaccess file
php_flag display_errors on
SetEnv MAGE_IS_DEVELOPER_MODE true
==========================================================================
Create Admin (Backend) Module in Magento with Grids
http://www.webspeaks.in/2010/08/create-admin-backend-module-in-magento.html



call a block in a phtml instead of through a layout?

<?php print $this->getLayout()->createBlock("catalog/product_view")->setTemplate("catalog/product/view/addto.phtml")->toHtml();?>

==========================================================================

To Enable Tag in Admin

go module and enable mage_tag
==========================================================================
To delete the module setup in magento DB, use core_resource table.
==========================================================================

Magento – check if user logged in

<?php
if ($this->helper('customer')->isLoggedIn() ) {
    echo "Welcome!";
} else {
    echo "Please log in.";
}
?>

==========================================================================

 


1. In the Admin Panel, go to System> Configuration
2. In the left column select the Customer Configuration tab under the Customers category.
3. Expand the Login Options bar to display the following options:
4. Redirect Customer to Account Dashboard after Logging in - Select No to allow customer to stay on their current page. Select Yes to redirect customers to the Account Dashboard after they successfully log in.
5. Click the [Save Config] button to save your changes.

==========================================================================

http://linssen.me/entry/extending-the-jquery-sortable-with-ajax-mysql/

=======================================================================

Pass data from controller to view in magento

Controller function:
public function indexAction()
{
  $bla = Mage::getSingleton('Modulename/viewinfo');
  $bla->setMsg("Thank You for your visit!");
  $this->loadLayout();
  $this->renderLayout();
}

Now in your View .phtml file add:
<?php $blas = Mage::getSingleton('Modulename/viewinfo'); ?>
<?php echo $blas->getMsg(); ?>

=========================================================================

Magento: get skin url, get media url, get base url, get store url

http://www.webdosh.net/2011/04/magento-get-skin-url-get-media-url-get.html

=========================================================

To get customer id

$customer = Mage::getSingleton('customer/session')->getCustomer();

$customerid = $customer->getId();

=========================================================

replace base_url

SELECT *
FROM `core_config_data`
WHERE `path` LIKE "%_url%"
LIMIT 0 , 30;

=========================================================

Zend_Debug::dump($this->getLayout()->getUpdate()->getHandles());

=========================================================
Current user in Magento?
down vote
Have a look at the helper class: Mage_Customer_Helper_Data
To simply get the customer name, you can write the following code:-
$customerName =Mage::helper('customer')->getCustomerName();

For more information about the customer's entity id, website id, email, etc. you can use getCustomer function. The following code shows what you can get from it:-
echo "<pre>"; print_r(Mage::helper('customer')->getCustomer()->getData()); echo "</pre>";
From the helper class, you can also get information about customer login url, register url, logout url, etc.
From the isLoggedIn function in the helper class, you can also check whether a customer is logged in or not.



=========================================================

<div class="block-content">
        <ol id="recently-viewed-items" class="mini-products-list">
        <?php foreach ($_products as $_item): ?>
            <li class="item">
                <a href="<?php echo $this->getProductUrl($_item) ?>" class="product-image"><img src="<?php echo $this->helper('catalog/image')->init($_item, 'small_image')->resize(50, 50) ?>" width="50" height="50" alt="<?php echo $this->htmlEscape($_item->getName()) ?>" /> </a>
                <div class="product-details"><p class="product-name"><a href="<?php echo $this->getProductUrl($_item) ?>"><?php echo $this->htmlEscape($_item->getName()) ?></a></p></div>
            </li>
        <?php endforeach; ?>
        </ol>
        <script type="text/javascript">decorateList('recently-viewed-items');</script>
    </div>
================================================

http://www.catgento.com/adding-configurable-product-options-to-category-list-in-magento/

================================================
http://www.magentocommerce.com/wiki/5_-_modules_and_development/search_and_advanced_search/how_to_add_search_by_category_to_advanced_search
================================================

How to Import multiple images through CSV,
Then we need to make a small change in app/code/core/Mage/Catalog/Model/Convert/Adapter/Product.php (Do keep a backup of original).
post the code just above:
$product->setIsMassupdate(true);

$galleryData = explode(',',$importData['gallery']);
        foreach($galleryData as $gallery_img)
        {
            if(!empty($gallery_img)){
                try {
                    $product->addImageToMediaGallery(Mage::getBaseDir('media') . DS . 'import' . $gallery_img, null, false, false);
                }
            catch (Exception $e) {}
            }
        }

http://go.magento.com/support/kb/entry/name/working-with-product-csv-files/
================================================
http://www.excellencemagentoblog.com/useful-code-snippets
==================================================
Create Order

 Below is the php code to create an order in magento. It requires a valid customer account with shipping and billing address setup.
$id=1; // get Customer Id
$customer = Mage::getModel('customer/customer')->load($id);

$transaction = Mage::getModel('core/resource_transaction');
$storeId = $customer->getStoreId();
$reservedOrderId = Mage::getSingleton('eav/config')->getEntityType('order')->fetchNewIncrementId($storeId);

$order = Mage::getModel('sales/order')
->setIncrementId($reservedOrderId)
->setStoreId($storeId)
->setQuoteId(0)
->setGlobal_currency_code('USD')
->setBase_currency_code('USD')
->setStore_currency_code('USD')
->setOrder_currency_code('USD');
//Set your store currency USD or any other

// set Customer data
$order->setCustomer_email($customer->getEmail())
->setCustomerFirstname($customer->getFirstname())
->setCustomerLastname($customer->getLastname())
->setCustomerGroupId($customer->getGroupId())
->setCustomer_is_guest(0)
->setCustomer($customer);

// set Billing Address
$billing = $customer->getDefaultBillingAddress();
$billingAddress = Mage::getModel('sales/order_address')
->setStoreId($storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_BILLING)
->setCustomerId($customer->getId())
->setCustomerAddressId($customer->getDefaultBilling())
->setCustomer_address_id($billing->getEntityId())
->setPrefix($billing->getPrefix())
->setFirstname($billing->getFirstname())
->setMiddlename($billing->getMiddlename())
->setLastname($billing->getLastname())
->setSuffix($billing->getSuffix())
->setCompany($billing->getCompany())
->setStreet($billing->getStreet())
->setCity($billing->getCity())
->setCountry_id($billing->getCountryId())
->setRegion($billing->getRegion())
->setRegion_id($billing->getRegionId())
->setPostcode($billing->getPostcode())
->setTelephone($billing->getTelephone())
->setFax($billing->getFax());
$order->setBillingAddress($billingAddress);

$shipping = $customer->getDefaultShippingAddress();
$shippingAddress = Mage::getModel('sales/order_address')
->setStoreId($storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_SHIPPING)
->setCustomerId($customer->getId())
->setCustomerAddressId($customer->getDefaultShipping())
->setCustomer_address_id($shipping->getEntityId())
->setPrefix($shipping->getPrefix())
->setFirstname($shipping->getFirstname())
->setMiddlename($shipping->getMiddlename())
->setLastname($shipping->getLastname())
->setSuffix($shipping->getSuffix())
->setCompany($shipping->getCompany())
->setStreet($shipping->getStreet())
->setCity($shipping->getCity())
->setCountry_id($shipping->getCountryId())
->setRegion($shipping->getRegion())
->setRegion_id($shipping->getRegionId())
->setPostcode($shipping->getPostcode())
->setTelephone($shipping->getTelephone())
->setFax($shipping->getFax());

$order->setShippingAddress($shippingAddress)
->setShipping_method('flatrate_flatrate');
/*->setShippingDescription($this->getCarrierName('flatrate'));*/
/*some error i am getting here need to solve further*/

//you can set your payment method name here as per your need
$orderPayment = Mage::getModel('sales/order_payment')
->setStoreId($storeId)
->setCustomerPaymentId(0)
->setMethod('purchaseorder')
->setPo_number(' – ');
$order->setPayment($orderPayment);

// let say, we have 1 product
//check that your products exists
//need to add code for configurable products if any
$subTotal = 0;
$products = array(
    '1' => array(
    'qty' => 2
    )
);

foreach ($products as $productId=>$product) {
$_product = Mage::getModel('catalog/product')->load($productId);
$rowTotal = $_product->getPrice() * $product['qty'];
$orderItem = Mage::getModel('sales/order_item')
->setStoreId($storeId)
->setQuoteItemId(0)
->setQuoteParentItemId(NULL)
->setProductId($productId)
->setProductType($_product->getTypeId())
->setQtyBackordered(NULL)
->setTotalQtyOrdered($product['rqty'])
->setQtyOrdered($product['qty'])
->setName($_product->getName())
->setSku($_product->getSku())
->setPrice($_product->getPrice())
->setBasePrice($_product->getPrice())
->setOriginalPrice($_product->getPrice())
->setRowTotal($rowTotal)
->setBaseRowTotal($rowTotal);

$subTotal += $rowTotal;
$order->addItem($orderItem);
}

$order->setSubtotal($subTotal)
->setBaseSubtotal($subTotal)
->setGrandTotal($subTotal)
->setBaseGrandTotal($subTotal);

$transaction->addObject($order);
$transaction->addCommitCallback(array($order, 'place'));
$transaction->addCommitCallback(array($order, 'save'));
$transaction->save();
===========================================================

Creating Customer

Below is a php code to create a customer account in magento.
$customer = Mage::getModel('customer/customer');
$password = 'test1234';
$email = 'dtest@gmail.com<script type="text/javascript">
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName("script");l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>';
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);
if(!$customer->getId()) {
    $groups = Mage::getResourceModel('customer/group_collection')->getData();
    $groupID = '3';

    $customer->setData( 'group_id', $groupID );
    $customer->setEmail($email);
    $customer->setFirstname('test');
    $customer->setLastname('testing');
    $customer->setPassword($password);

    $customer->setConfirmation(null);
    $customer->save();

    echo $customer->getId();
}

 ==================================================
Creating Invoice

Below is a php code to create invoice for an order in magento.
$order = Mage::getModel('sales/order')->loadByIncrementId('100000001');
try {
if(!$order->canInvoice())
{
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice.'));
}

$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();

if (!$invoice->getTotalQty()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
}

$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
//Or you can use
//$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
$invoice->register();
$invoice->sendEmail(); $invoice->setEmailSent(true);
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());

$transactionSave->save();
}
catch (Mage_Core_Exception $e) {

}
============================================================
Create Shipment

Below is a php code to create a shipment for an order in magento.
$order = Mage::getModel('sales/order')->loadByIncrementId('100000001');
try {
    if($order->canShip()) {
        //Create shipment
        $shipmentid = Mage::getModel('sales/order_shipment_api')
                        ->create($order->getIncrementId(), array());
        //Add tracking information
        $ship = Mage::getModel('sales/order_shipment_api')
                        ->addTrack($order->getIncrementId(), array());    
    }
}catch (Mage_Core_Exception $e) {
 print_r($e);
}

Creating Credit Memo

Below is a php code to create a credit memo for an order in magento.
$order = Mage::getModel('sales/order')->load('100000001', 'increment_id');
        if (!$order->getId()) {
            $this->_fault('order_not_exists');
        }
        if (!$order->canCreditmemo()) {
            $this->_fault('cannot_create_creditmemo');
        }
        $data = array();

       
        $service = Mage::getModel('sales/service_order', $order);
     
        $creditmemo = $service->prepareCreditmemo($data);

        // refund to Store Credit
        if ($refundToStoreCreditAmount) {
            // check if refund to Store Credit is available
            if ($order->getCustomerIsGuest()) {
                $this->_fault('cannot_refund_to_storecredit');
            }
            $refundToStoreCreditAmount = max(
                0,
                min($creditmemo->getBaseCustomerBalanceReturnMax(), $refundToStoreCreditAmount)
            );
            if ($refundToStoreCreditAmount) {
                $refundToStoreCreditAmount = $creditmemo->getStore()->roundPrice($refundToStoreCreditAmount);
                $creditmemo->setBaseCustomerBalanceTotalRefunded($refundToStoreCreditAmount);
                $refundToStoreCreditAmount = $creditmemo->getStore()->roundPrice(
                    $refundToStoreCreditAmount*$order->getStoreToOrderRate()
                );
                // this field can be used by customer balance observer
                $creditmemo->setBsCustomerBalTotalRefunded($refundToStoreCreditAmount);
                // setting flag to make actual refund to customer balance after credit memo save
                $creditmemo->setCustomerBalanceRefundFlag(true);
            }
        }
        $creditmemo->setPaymentRefundDisallowed(true)->register();
        // add comment to creditmemo
        if (!empty($comment)) {
            $creditmemo->addComment($comment, $notifyCustomer);
        }
        try {
            Mage::getModel('core/resource_transaction')
                ->addObject($creditmemo)
                ->addObject($order)
                ->save();
            // send email notification
            $creditmemo->sendEmail($notifyCustomer, ($includeComment ? $comment : ''));
        } catch (Mage_Core_Exception $e) {
            $this->_fault('data_invalid', $e->getMessage());
        }
        echo $creditmemo->getIncrementId();
============================================================================
Magento Change order status to complete without invoicing

$orderOBJ = Mage::getModel('sales/order')->load($order->getId());
$orderOBJ->setStatus('complete');
$orderOBJ->save();

============================================================================
 $rClass = new ReflectionClass($this);
var_dump($rClass->getFilename());

============================================================================

PHP Class to find out country,city and state using the Google Geocoding API

This is a simple class which uses the the Google Geocoding API to find out a location information based on the zip code. You will get the following using this class:
  • City
  • State
  • Country
  • Longitude
  • Latitude

NOTE:

- Here the backdrop is some of the countries zip codes  are same. so if we pass only zip code then it returns any one of the matching country details.

- So better we need to pass city with zip code. it results accurate country details.

- For example we need to pass ' 625106,Madurai '

Example:

include 'GoogleAddressLookup.php';
$zipCode = 625106; // 625106,Madurai for accurate result
$lookup = new GoogleAddressLookup();
$lookup->setZipCode($zipCode);
echo 'City: ' . $lookup->getCity() . '('. $lookup->getCityShortName().')<br>';
echo 'State: ' . $lookup->getState() . '('. $lookup->getStateShortName().')<br>';
echo 'Country: ' . $lookup->getCountry() . '('. $lookup->getCountryShortName().')<br>';
echo 'LAT: ' . $lookup->getLatitude().'-- LNG: ' . $lookup->getLongitude();


GoogleAddressLookup.php

<?php
/**
 * This class can be used to lookup city/state/country using zip code in Google Geo Lookup service.
 * This class uses the JSON API provided by Google Geo Lookup.
 *
 * @author Mohammad Sajjad Hossain
 * @version 1.0
 */
class GoogleAddressLookup{
    /**
     * Response
     * @var array
     */
    private $response;

    /**
     * Constructor
     */
    public function __construct(){
        $this->initialize();
    }

    /**
     * Initialize variables
     */
    private function initialize(){
        $this->response = array(
            'zip_code' => '',
            'state' => '',
            'state_short' => '',
            'city' => '',
            'city_short' => '',
            'country' => '',
            'country_short' => '',
            'latitude' => '',
            'longitude' => '',
            'raw_response' => ''
        );
    }

    /**
     * Sets Zup Code
     * @param int $zipCode
     */
    public function setZipCode($zipCode){
        $this->response['zip_code'] = $zipCode;

        $this->processResponse();
    }

    /**
     * Returns City full name
     *
     * @return string
     */
    public function getCity(){
        return $this->response['city'];
    }

    /**
     * Returns City short name
     *
     * @return string
     */
    public function getCityShortName(){
        return $this->response['city_short'];
    }

    /**
     * Returns State full name
     *
     * @return string
     */
    public function getState(){
        return $this->response['state'];
    }

    /**
     * Returns State short name
     *
     * @return string
     */
    public function getStateShortName(){
        return $this->response['state_short'];
    }

    /**
     * Returns Country full name
     *
     * @return string
     */
    public function getCountry(){
        return $this->response['country'];
    }

    /**
     * Returns Country short name
     *
     * @return string
     */
    public function getCountryShortName(){
        return $this->response['country_short'];
    }

    /**
     * Returns Latitude
     *
     * @return int
     */
    public function getLatitude(){
        return $this->response['latitude'];
    }

    /**
     * Returns Longitude
     *
     * @return int
     */
    public function getLongitude(){
        return $this->response['longitude'];
    }

    /**
     * Makes call to the API
     */
    private function makeCall(){
        if($this->response['zip_code']){
            $url = "http://maps.googleapis.com/maps/api/geocode/json?address={$this->response['zip_code']}&sensor=true";

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_VERBOSE, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
            curl_setopt($ch, CURLOPT_URL, $url);

            $this->response['raw_response'] = curl_exec($ch);
        }
    }

    /**
     * Processes the response received
     */
    private function processResponse(){
        $this->makeCall();

        if($this->response['raw_response']){
            $result = json_decode($this->response['raw_response']);

            if($result->status == 'OK'){
                if(!empty($result->results[0]->address_components)){
                    foreach($result->results[0]->address_components as $add_comp){
                        if(in_array('locality', $add_comp->types)){
                            $this->response['city'] = $add_comp->long_name;
                            $this->response['city_short'] = $add_comp->short_name;
                        }
                        elseif (in_array('administrative_area_level_1', $add_comp->types)) {
                            $this->response['state'] = $add_comp->long_name;
                            $this->response['state_short'] = $add_comp->short_name;
                        }
                        elseif (in_array('country', $add_comp->types)) {
                            $this->response['country'] = $add_comp->long_name;
                            $this->response['country_short'] = $add_comp->short_name;
                        }
                    }
                }

                if(!empty($result->results[0]->geometry)){
                    $this->response['longitude'] = $result->results[0]->geometry->location->lng;
                    $this->response['latitude'] = $result->results[0]->geometry->location->lat;
                }
            }
        }
    }
}