Showing posts with label Google. Show all posts
Showing posts with label Google. Show all posts

Tuesday, August 27, 2013

Magento: Store locator in Magento using Google Map API

First you need to create a custom module with single model (one model-one table).
Suppose Bd_Storelocator is a custom module and Storelocator is a model,
Then use following code in any phtml file as
<?php
$requireData = Mage::getModel('storelocator/storelocator')->getStore();
//print_r($requireData->getData());
$markers = "";
$messages = "";
foreach ($requireData as $data) {
    $markers .= '{lat:' . $data["latitude"] . ',lng:' . $data["longitude"] . ',name:' . '"' . $data["storename"] . '"},';
    $messages .= "'" . addslashes($data["storename"]) . "<br/ >" . addslashes($data["address"]) . "<br />" . $data["telephone"] . "', ";    }
$markers1 = rtrim($markers, ",");
$messages1 = rtrim($messages, ", ");
?>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
    var map;
    google.maps.event.addDomListener(window, "load", initialize);
    function initialize() {
        var map = new google.maps.Map(document.getElementById("map_canvas"), {
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            disableAutoPan: false,
            streetViewControl: false
        });
        var markers = [<?php echo $markers1; ?>];
        var widt = document.body.offsetWidth;
        document.getElementById("map_canvas").width = widt+"px";
        for (index in markers) {
            if(Number(index) != index) break;
            addMarker(markers[index],map,index);
        }
        var bounds = new google.maps.LatLngBounds();
        for (index in markers) {
            if(Number(index) != index) break;
            var data = markers[index];
            bounds.extend(new google.maps.LatLng(data.lat, data.lng));
        }
        // Don't zoom in too far on only one marker
        if (bounds.getNorthEast().equals(bounds.getSouthWest())) {
            var extendPoint1 = new google.maps.LatLng(bounds.getNorthEast().lat() + 0.01, bounds.getNorthEast().lng() + 0.01);
            var extendPoint2 = new google.maps.LatLng(bounds.getNorthEast().lat() - 0.01, bounds.getNorthEast().lng() - 0.01);
            bounds.extend(extendPoint1);
            bounds.extend(extendPoint2);
        }
        map.fitBounds(bounds);
    }
    function addMarker(data,map,index) {
        // Create the marker
        //var image = '<?php //print $base_url . '/' . $themePath . '/images/drupal.png'  ?>';
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(data.lat, data.lng),
            map: map,
            //icon: image,
            title: data.name
        });
        attachSecretMessage(marker,index,map)

    }
    function attachSecretMessage(marker,number,map) {
        var message = [<?php echo $messages1; ?>];

        var infowindow = new google.maps.InfoWindow({
            content: message[number],
            size: new google.maps.Size(50,50)
        });
        google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map,marker);
           jQuery("#showinfo").html(message[number]);

        });
    }
</script>
<div class="mapBlock">
    <div id="map_canvas" style="height: 473px;">
    </div>
</div>
<div id="showinfo">

</div>

Adding a Google Map to your website

Use following code
<!DOCTYPE html>
<html>
  <head>
    <style>
      #map_canvas {
        width: 500px;
        height: 400px;
      }
    </style>
    <script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script>
      function initialize() {
        var map_canvas = document.getElementById('map_canvas');
        var map_options = {
          center: new google.maps.LatLng(44.5403, -78.5463),
          zoom: 8,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        var map = new google.maps.Map(map_canvas, map_options)
      }
      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
    <div id="map_canvas"></div>
  </body>
</html>

Sunday, April 14, 2013

Magento : Import Gmail Contact

1. Define a link in any phtml file as
<?php
    $client_id=  '';                  
    $redirect_uri='test/test/gooledata';
    $scope = "https://www.google.com/m8/feeds/"; //google scope to access
    $state = "profile"; //optional                   
    $loginUrl = sprintf("https://accounts.google.com/o/oauth2/auth?scope=%s&state=%s&redirect_uri=%s&response_type=code&client_id=%s",$scope,$state,$redirect_uri,$client_id);
?>
Import E-mail Addresses From:<br />
<a href="javascript:poptastic('<?php echo $loginUrl; ?>');">Import</a>



<script>
function poptastic(url) {
      var newWindow = window.open(url, 'name', 'height=600,width=450,top=100,left=500');
      if (window.focus) {
        newWindow.focus();
      }
     
 }
function showGmailData(){
       //location.reload();
       jQuery("#gmailloader").css('display', 'block');
            jQuery.ajax({
                    type: "POST",
                    data : jQuery("#form-validate").serialize(),
                    url: '/invitation/index/showgmaildata',
                    success: function(data) {
                    jQuery("#gmailloader").css('display', 'none');
                    result = jQuery.parseJSON(data);
                    if(!result.success) {
                    }
                    else    {

                    }
              }
            });
 }
</script>

2. Define Redirect action in controller
public function googledataAction(){        
              
        $authcode= $this->getRequest()->getParam('code');
        $importcontacts = array();
        if(isset($authcode) && $authcode != ''){
           $importcontacts = Mage::helper('test')->importGmailContacts($authcode);
           //print_r($importcontacts);
           //Mage::getSingleton('core/session')->setImportcontacts($importcontacts);
           echo '<html><body>Please wait....<script type="text/javascript">window.opener.showGmailData(); window.close();</script></body></html>';
           die();
          
        }       
    }

3. Define importGmailContacts() method in helper
public function importGmailContacts($authcode){       
            try{
            $clientid='';
            $clientsecret='';
            $redirecturi='test/test/googledata';
            $fields=array(
            'code'=>  urlencode($authcode),
            'client_id'=>  urlencode($clientid),
            'client_secret'=>  urlencode($clientsecret),
            'redirect_uri'=>  urlencode($redirecturi),
            'grant_type'=>  urlencode('authorization_code')
            );
            $fields_string='';
            foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
            $fields_string=rtrim($fields_string,'&');
            //open connection
            $ch = curl_init();
            //set the url, number of POST vars, POST data
            curl_setopt($ch,CURLOPT_URL,'https://accounts.google.com/o/oauth2/token');
            curl_setopt($ch,CURLOPT_POST,5);
            curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
            // Set so curl_exec returns the result instead of outputting it.
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            //to trust any ssl certificates
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            //execute post
            $result = curl_exec($ch);
            //close connection
            curl_close($ch);
            //extracting access_token from response string
            $response   =  json_decode($result);
            $accesstoken= $response->access_token;
            if( $accesstoken!='')
           
            $xmlresponse=  file_get_contents('https://www.google.com/m8/feeds/contacts/default/full?max-results=100&oauth_token='. $accesstoken);
            //reading xml using SimpleXML
            $xml=  new SimpleXMLElement($xmlresponse);
            $xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005');
            $result = $xml->xpath('//gd:email');
            foreach ($result as $title) {
                $importcontact[] = (string)$title->attributes()->address;
            }
            Mage::getSingleton('core/session')->setImportcontacts($importcontact);
            //return $importcontact;
            }  catch (Exception $e){ echo $e->getMessage();}
    }

4.Then use according to requirement in following action
public function showGmailDataAction(){
        $result = array(
                'success' => false,
                'message' => false,
                'count' => false,
            );
$importcontacts = Mage::getSingleton('core/session')->getImportcontacts();
$this->getResponse()->setBody(Zend_Json::encode($result));
        return;
    }
               

Wednesday, September 19, 2012

Magento: Add google translator in website


Add following script in any template file

<div id="google_translate_element"></div><script>
function googleTranslateElementInit() {
  new google.translate.TranslateElement({
    pageLanguage: 'en'
  }, 'google_translate_element');
}
</script><script src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>