Archive for the ‘google’ Category

 

 

Folks like me are using free web hosting for personal website. And one of the main headaches for free hosting is that, it does not provide SMTP server for free. I am using bytehost for my wordpress blog hosting. Everything seems fine so far, but the problem is always the SMTP server. For example I am using a contact form, and user can leave messages to me through email. the original code reads:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$email_to = trim($_POST['your_email']);
$your_web_site_name = trim($_POST['your_web_site_name']);

$headers = 'From: ' . $your_web_site_name . ' <' . $email_to . '>' . "\r\n" . 'Reply-To: ' . $email;

if (mail($email_to, $subject, $message, $headers)) {
    echo 'sent'; // we are sending this text to the ajax request telling it that the mail is sent..      
} else {
    echo 'failed'; // ... or this one to tell it that it wasn't sent    
}

but, we can not use PHP’s mail function if it is not enabled by the hosting provider. Fortunately enough, Google’s Gmail is coming to save us. It is totally free, and more stable than any other providers. And overall, it is very easy to setup.
1. use phpmailer class to send email.
2. use smtp configuration for email.

the changed file is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
include ('../../../wp-includes/class-phpmailer.php'); 		
include ('../../../wp-includes/class-smtp.php'); 
    //we need to get our variables first
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$email_to = trim($_POST['your_email']);
$your_web_site_name = trim($_POST['your_web_site_name']);

    $mail=new PHPMailer();  		
    // Let PHPMailer use remote SMTP Server to send Email 		
    $mail->IsSMTP();  		
    // Set the charactor set. The default is 'UTF-8' 		
    $mail->CharSet='UTF-8';  		
    // Add an recipients. You can add more recipients 		// by using this method repeatedly. 		
    $mail->AddAddress($email_to);  		
    // Set the body of the Email. 		
    $mail->Body=$message;  		
    // Set "From" segment of header. 		
    $mail->From=$email;  		
    $mail->AddReplyTo($email, $email);  		
    // Set addresser's name 		
    $mail->FromName=$name;  		
    // Set the title 		
    $mail->Subject=$subject;  		
    // Set the SMTP server. 		
    $mail->Host='smtp.gmail.com'; 		
    $mail->Port= 465; 		
    $mail->SMTPAuth = true; 		
    $mail->SMTPSecure = "ssl";   		
    $mail->Username='youraccount@gmail.com'; 		
    $mail->Password='yourpassword'; 		 		
    // Send Email. 		
    if($mail->Send()){
        echo 'sent'; // we are sending this text to the ajax request telling it that the mail is sent..      
    } else {
        echo 'failed'; // ... or this one to tell it that it wasn't sent    
    }

The following settings specify using gmail’s smtp.

// Set the SMTP server.
$mail->Host=’smtp.gmail.com’;
$mail->Port= 465;
$mail->SMTPAuth = true;
$mail->SMTPSecure = “ssl”;
$mail->Username=’youraccount@gmail.com’;
$mail->Password=’yourpassword’;

Now you can send me messages through the contact form in the contact page!!

And if you are using my Aurelius theme, you can replace the send_mail.php with the code above to send email.

Thanks for reading.

the end!!

Advertisements

Posted: December 28, 2012 in google
Tags:

 

How to create simple map using google map javascript api v3

Start to create google maps using api

Simple way to start develop the Google Maps API is to see a simple example.people familiar with JavaScript programming and object-oriented programming concepts can easily capture

<html>
  <head>

    <meta name="viewport"
        content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      html, body, #map_canvas {
        margin: 0;
        padding: 0;
        height: 100%;
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>

    <script>
      var map;
      function initialize() {
        var mapOptions = {
          zoom: 8,
          center: new google.maps.LatLng(8.560058,76.881108),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('map_canvas'),
            mapOptions);
      }

      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
    <div id="map_canvas"></div>
  </body>
</html>

Declared our applications as HTML5 using the simple HTML5 DOCTYPE

<!DOCTYPE html>

Loading the Google Maps API script

 <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>

Initialize the google map on window.onload to show map on our page

 function initialize() {
  var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(8.560058,76.881108),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}

function loadScript() {
  var script = document.createElement("script");
  script.type = "text/javascript";
  script.src = "http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=TRUE_OR_FALSE&callback=initialize";
  document.body.appendChild(script);
}

window.onload = loadScript;

Setting the map options

var mapOptions = {
  center: new google.maps.LatLng(8.560058,76.881108),
  zoom: 8,
  mapTypeId: google.maps.MapTypeId.ROADMAP
};
    • center

center the map on a specific point, we create a LatLng object to hold this location by passing the location’s coordinates in the order { latitude, longitude }:

center: new google.maps.LatLng(8.560058,76.881108),
    • Zoom Levels

The initial resolution at which to display the map is set by the zoom property, where zoom 0 corresponds to a map of the Earth fully zoomed out, and higher zoom levels zoom in at a higher resolution.

zoom: 8
    • Map Types

The following map types are supported:.

      • ROADMAP displays the normal, default 2D tiles of Google

        Maps.

      • SATELLITE displays photographic tiles.
      • HYBRID displays a mix of photographic tiles and a tile layer

        for prominent features (roads, city names).

      • TERRAIN displays physical relief tiles for displaying

        elevation and water features (mountains, rivers, etc.).

mapTypeId: google.maps.MapTypeId.ROADMAP

Create map object

var map = new google.maps.Map(document.getElementById("map_canvas"),
    mapOptions);

Loading Google Map

 <body onload="initialize()">

Google Plus API Tutorial

Posted: December 27, 2012 in google
Tags:

rating Google Plus API Tutorial | w3resource has average rating 6 out of 10. Total 67 users rated.

Introduction

Google Plus API for developers allows you to fetch public data form Google+. In this tutorial w3resource discusses an overview of Google Plus API, followed by detail tutorial of all the necessary steps one need to perform to successfully fetch public data from Google+.

Google Plus

Overview of Google+ API

Purpose of Google+ API is to provide a programming interface so that you can integrate application or website with Google+.

Google implies a limit to the usage of Google+ API – Each developer has a quota. We will see about that when we will discuss about Google API console.

Google uses OAuth2.0 protocol to authorize your application when it tries to access user data.

It mostly uses standard HTTP method by means of RESTful API design to fetch and manipulate user data.

So, to get the profile information of a user, syntax of the command which has to be used is following :

GET https://www.googleapis.com/plus/v1/people/userId

Where userId is the userid of the user whose profile information you want to fetch.

Google uses JSON Data Format to represent the resources in the API.

You may pass several parameters while fetching data using Google+ API. Following table shows the common parameters used :

Parameter Value Description
callback string If you want to use JSONP with the API, this specifies the JavaScript function to which the response data will be passed.
fields string For better performance, if you want to include only certain fields, referred as Partial Response, this specifies the list of fields.
key string API key provided to a registered developer. Used to authorize the corresponding application when it tries to access the user data.
access_token string OAuth 2.0 token for the current user.
prettyPrint boolean You can set it to ‘true’ to make the code more readable by adding indentation and line breaks.
userIp boolean This is to identify the IP address of the user, whose data is sought by making an API call. If a server-side application make an API call, this keeps the restriction implied by user-quota enforced.

Though each API resource (like people, activities) has some unique properties, there are properties which are common to all resources. Following table shows the properties common to all resources :

Property Value Description
displayName string Name of the resource. May be used for displaying data to user.
id string For better performance, if you want to include only certain fields, referred as Partial Response, this specifies the list of fields.
kind string Identifies what kind of resource a JSON object represents. While parsing, a user data(in JSON format), if an unknown object is found, this may help to decide how to parse that programmatically.
url string Primary url or permalink for the associated resource.

If the API returns a large number of collection, then each response comprises of a limited number of items, which may be obtained by ‘maxResults’. By passing the value of ‘nextPageToken’ property of each response to ‘pageToken’ property, next request can be obtained. Repeating this process, you may obtain the full response.

After you finish the above write up, it’s time to get your hands dirty but trying a simple application.

Step 1 : Generate a API key through Google API Console

Point your browser to code.google.com/apis/console/ and it will take you to the login page of the API Console.

Point your browser to code.google.com/apis/console/ and it will take you to the login page of the API Console. Once you logged in with your email and password, following will appear. Click on the ‘Create Project’.

Create Project Google API Console

In the list of services find the Google+ API and Click on ‘off’ to turn it on.

find-Google-plus-API

In the next screen check ‘I Agree..’ and click on ‘Accept’. You will see that the button next to Google+ API has changed to following :

ON-Google-plus-API

Now click on the ‘API Access’ and it will ask you to ‘Create an OAuth 2.0 client id..’.

API-Access-Google-plus-API

In the next screen provide a product name, upload an image as logo of your project, and click ‘Next’.

create-client-id

In the next screen you will get information as following –

information-client-id

This information will be required to make an API call.

Step 2 : Create a simple application to fetch user profile information using Google+ API

We will create a simple form. In that form, if an userid is supplied, it will return certain information regarding that user.

Following is the code of a simple HTML page containing a form :

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <title>Google + API example</title>
  5. </head>
  6. <body>
  7. <p>Insert an ID : </p>
  8. <form method=”POST” action=”example.php”>
  9. <input type=”text” name=”id” /><br />
  10. <input type=”Submit” name=”submit” value=”Submit” />
  11. </form>
  12. </body>
  13. </html>

We will use Google API PHP Client to accomplish the task. So, you need to download that. Point your browser to code.google.com/p/google-api-php-client/ and obtain the Google API PHP Client. Unzip it and save it to the folder where your application’s html and php file will reside.

Following is the PHP code of our application.

  1.  <?php
  2.   /* * Copyright 2011 Google Inc.
  3.   *
  4.   * Licensed under the Apache License, Version 2.0 (the “License”);
  5.   * you may not use this file except in compliance with the License.
  6.   * You may obtain a copy of the License at
  7.   *
  8.   * http://www.apache.org/licenses/LICENSE-2.0
  9.   *
  10.   * Unless required by applicable law or agreed to in writing, software
  11.   * distributed under the License is distributed on an “AS IS” BASIS,
  12.   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.   * See the License for the specific language governing permissions and
  14.   * limitations under the License.
  15.   */
  16.   require_once ‘google-api-php-client/src/apiClient.php’;
  17.   require_once ‘google-api-php-client/src/contrib/apiPlusService.php’;
  18. session_start();
  19. $id = $_POST[‘id’];
  20. $client = new apiClient();
  21.   $client->setApplicationName(“Google+ PHP Starter Application”);
  22.   // oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.
  23.   $client->setClientId(‘357142505911.apps.googleusercontent.com’);
  24.   $client->setClientSecret(‘LbJa7YOJ1Th-e-TOosEJxI4A’);
  25.   $client->setRedirectUri(‘http://www.w3resource.com/API/google-plus/example.php&#8217;);
  26.   $client->setDeveloperKey(‘AIzaSyD3stLpkt7jJw0mkMsJtM9m_zrgg26rrsI’);
  27.   $plus = new apiPlusService($client);
  28. if (isset($_REQUEST[‘logout’])) {
  29.   unset($_SESSION[‘access_token’]);
  30.   }
  31. if (isset($_GET[‘code’])) {
  32.   $client->authenticate();
  33.   $_SESSION[‘access_token’] = $client->getAccessToken();
  34.   header(‘Location: http://’ . $_SERVER[‘HTTP_HOST’] . $_SERVER[‘PHP_SELF’]);
  35.   }
  36. if (isset($_SESSION[‘access_token’])) {
  37.   $client->setAccessToken($_SESSION[‘access_token’]);
  38.   }
  39. if ($client->getAccessToken()) {
  40.   $me = $plus->people->get($id);
  41. $optParams = array(‘maxResults’ => 100);
  42.   $activities = $plus->activities->listActivities($id, ‘public’, $optParams);
  43. // The access token may have been updated lazily.
  44.   $_SESSION[‘access_token’] = $client->getAccessToken();
  45.   } else {
  46.   $authUrl = $client->createAuthUrl();
  47.   }
  48.   ?>
  49. <!doctype html>
  50.   <html>
  51.   <head><link rel=’stylesheet’ href=’style.css’ /></head>
  52.   <body>
  53.   <header><h1>Google+ Sample App</h1></header>
  54.   <div class=”box”>
  55. <?php if(isset($me) && isset($activities)): ?>
  56.   <div class=”me”>
  57.   <p><a rel=”me” href=”<?php echo $me[‘url’] ?>”><?php print $me[‘displayName’] ?></a></p>
  58.   <p><?php print $me[‘tagline’] ?></p>
  59.   <p><?php print $me[‘aboutMe’] ?></p>
  60.   <div><img src=”<?php echo $me[‘image’][‘url’]; ?>?sz=82″ /></div>
  61.   </div>
  62.   <div class=”activities”>Your Activities:
  63.   <?php foreach($activities[‘items’] as $activity): ?>
  64.   <div class=”activity”>
  65.   <p><a href=”<?php print $activity[‘url’] ?>”><?php print $activity[‘title’] ?></a></p>
  66.   </div>
  67.   <?php endforeach ?>
  68.   </div>
  69.   <?php endif ?>
  70.   <?php
  71.   if(isset($authUrl)) {
  72.   print “<a class=’login’ href=’$authUrl’>Connect Me!</a>”;
  73.   } else {
  74.   //print “<a class=’logout’ href=’?logout’>Logout</a>”;
  75.   }
  76.   ?>
  77.   </div>
  78.   </body>
  79.   </html>

There is a style sheet attached to the HTML code. Here it is

  1.     /*
  2.  * Copyright 2011 Google Inc.
  3.  * Licensed under the Apache License, Version 2.0 (the “License”);
  4.  * you may not use this file except in compliance with the License.
  5.  * You may obtain a copy of the License at
  6.  *
  7.  *     http://www.apache.org/licenses/LICENSE-2.0
  8.  *
  9.  * Unless required by applicable law or agreed to in writing, software
  10.  * distributed under the License is distributed on an “AS IS” BASIS,
  11.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12.  * See the License for the specific language governing permissions and
  13.  * limitations under the License.
  14.  */
  15. body {
  16.   font-family: Arial,sans-serif;
  17.   margin: auto;
  18. }
  19. .box {
  20.   border: .5em solid #E3E9FF;
  21.   -webkit-box-orient: vertical;
  22.   -webkit-box-align: center;
  23.   -moz-box-orient: vertical;
  24.   -moz-box-align: center;
  25.   display: block;
  26.   box-orient: vertical;
  27.   box-align: center;
  28.   width: 750px;
  29.   height: auto;
  30.   margin: auto;
  31.   padding: 10px;
  32.   word-wrap: break-word;
  33.   text-overflow: ellipsis;
  34. }
  35. .me {
  36.   -webkit-box-flex: 1;
  37.   -moz-box-flex: 1;
  38.   box-flex: 1;
  39.   width: 700px;
  40. }
  41. .activities {
  42.   -webkit-box-flex: 2;
  43.   -moz-box-flex: 2;
  44.   box-flex: 2;
  45.   width:100%;
  46. }
  47. .activity {
  48.   margin: 10px;
  49. }
  50. header {
  51.   color:#000;
  52.   padding:2px 5px;
  53.   font-size:100%;
  54.   width: 400px;
  55.   margin: auto;
  56.   text-align: center
  57. }
  58. header h1.logo {
  59.   margin:6px 0;
  60.   padding:0;
  61.   cursor:pointer;
  62.   font-size:24px;
  63.   line-height:20px;
  64. }
  65. .login {
  66.   font-size: 200%;
  67.   display: block;
  68.   margin: auto;
  69.   cursor: pointer;
  70.   text-align: center;
  71.   font-weight: bold;
  72.   color: #2779AA;
  73.   line-height: normal;
  74. }
  75. .logout {
  76.   font-weight: normal;
  77.   padding-top: -5px;
  78.   margin-top: 0px;
  79. }

In the PHP code above, change clientId at line number 28, change ClientSecret at line number 29, change RedirectUri at line number 30, change DeveloperKey at line number 31, with your own. Also remember that in Google API Console, change the RedirectUri as you have given in you app’s php code.

Now point your browser to the url of your application and supply an userid. You can obtain a userid by googling ‘google profile username’ where username is an existing username. You will get an url like ‘https://plus.google.com/XXXXXXXXXXXXXXX&#8217;. ‘xx..’ is a number and this is the userid of that user. The application will return you the name, tagline, aboutme information regarding the user whose id you have supplied.

In the next part of the tutorial we will tweak this application to a better one and also we will see to fetch some other resources from the API.

Online demo of this simple Google PLUS API Example