Tag Archives: twitter

I Just Moved – A Friendly Reminder

moving-wordpress-blog

I am creating this post to let you know that I have started the process of migrating from this wordpress-hosted blog to a self-hosted one which is located at, well, Simple Developer. I am still fixing a few errors like syntax highlighting and things like that.

Besides that, everything should be fine now. I humbly request those who had subscribed to this blog to consider subscribing to my new blog which is still a wordpress platform.

Thank you for your loyalty as readers and I hope we can connect with each other as time as goes by.

Take care and see you at http://www.simpledeveloper.com !

Advertisements

Programming With Google Maps APIs – Part VI

Hello! Nice to see you and thanks for stopping by. In the last two days I took a detour from programming but today I am going to pick up from where I left Google Maps APIs – Part V . Today’s post will be relatively shorter than previous ones because I am completing a section (at the end, I will give an app idea). Let us get to it. We should start with our previous finishing code:

(function () {
    window.onload = function () {
        var mapDiv = document.getElementById('map');

        var options = {
            zoom: 3,
            center: new google.maps.LatLng(37.09, -95.71),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(mapDiv, options);

        var cities = [];
        cities.push(new google.maps.LatLng(40.756, -73.986));
        cities.push(new google.maps.LatLng(37.775, -122.419));
        cities.push(new google.maps.LatLng(47.620, -122.347));

        var infowindow;
        for (var i = 0; i<cities.length; i++) {
            //create markers for each city
            var marker = new google.maps.Marker({
                position: cities[i],
                map: map,
                title: "City Number " + i
            });

            (function (i, marker) {
                //create even listeners (closures at work)
                google.maps.event.addListener(marker, 'click', function () {
                    if (!infowindow) {
                        infowindow = new google.maps.InfoWindow();
                    }
                    //set content
                    infowindow.setContent('City number ' + i);
                    //open the window
                    infowindow.open(map, marker);
                });
            })(i, marker);
        }
    };
})();

Automatically adjusting the viewport to fit all markers

Every time you are expecting dynamic data to be added to your map (markers), you want to make sure that none of them appears outside the map. The best way to handle this is by making a map that automatically adjusts to the markers added. In order to achieve that, we use LatLngBounds object.

LatLngBounds Object

A bounding box is simply a rectangle defining an area. Its corners consist of geographical coordinates and everything inside it is within its bounds.  You can use it to calculate the viewport of a map and also determine if an object is in a certain area of the map.

The bounding box is of type google.maps.LatLngBounds object. It takes two optional arguments (southwest and northeast corners of the rectangle). Those arguments are of type google.maps.LatLng. 

In order to manually create a LatLngBounds box, we have to determine the coordinates  of its corners(you will see a better solution soon). Adding to our previous code, just below the line where we created our map, we could do this:

.
.
   var map = new google.maps.Map(mapDiv, options);
   var bounds = google.maps.LatLngBounds(
           new google.maps.LatLng(37.775, -122.419),
           new google.maps.LatLng(47.620, -73.986)
   );
.
.
.

Now our three markers will be within the above coordinates: Here is what am trying to allude to.

google-maps-bounds

Using The APIs For The Heavy Work

In order to extend our example to automatically adjust the viewport to fit the markers, we have established that we need a LatLngBounds object. So, we first create an empty LatLngBounds object somewhere outside our for loop. 

.
.
.
        var infowindow;
        //creating our bounds here
        var bounds = google.maps.LatLngBounds();

        for (var i = 0; i < cities.length; i++) {
            //create markers for each city
            var marker = new google.maps.Marker({
                position: cities[i],
                map: map,
                title: "City Number " + i
            });

.
.
.

After creating our empty bounds, we are going to extend it with each marker added to the map. We do this inside the loop like this:

.
.
.
      for (var i = 0; i < cities.length; i++) {
          [...]

          //extend the bounds here
          bounds.extend(cities[i]);
      }
.
.
.

At last, after iterating through the markers, we are going to adjust our map using fitBounds() method of the map object.

[...]
    window.onload = function () {
        [...]
        var map = new google.maps.Map(mapDiv, options);

        [...]

   //Adjusting the map to the bounding box
   map.fitBounds(bounds);
}

That is it for the above case. We now have a map that fits all the markers perfectly inside the viewport. In fact, you can now add more cities and the map will automatically adjust the viewport. Oh wait, we can do this right now by adding my favorite city: Nairobi, Kenya and let us also represent Asia (seoul, South Korea – let there be peace in the peninsula).

[...]
        [...]
        [...]

        var cities = [];
        cities.push(new google.maps.LatLng(40.756, -73.986));
        cities.push(new google.maps.LatLng(37.775, -122.419));
        cities.push(new google.maps.LatLng(47.620, -122.347));
        cities.push(new google.maps.LatLng(1.2833, 36.8167));
        cities.push(new google.maps.LatLng(37.5833, 127.0000));

        [...]
  [...]

[...]

That should do it and now we can take a look at our awesome map with more markers.

google-maps-api-viewport-scale
There you have it! I hope you had some fun playing around with this example. Within a very short time and few lines of code, we have created a map that shows different cities displayed using markers. Now consider having users enter their cities as you watch the markers increase. I like this so much am starting to think of a cool app.

Let me show you the entire code then give you a cooler idea of an app!

(function () {
    window.onload = function () {
        var mapDiv = document.getElementById('map');

        var options = {
            zoom: 3,
            center: new google.maps.LatLng(37.09, -95.71),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(mapDiv, options);
        var bounds = new google.maps.LatLngBounds();

        var cities = [];
        cities.push(new google.maps.LatLng(40.756, -73.986));
        cities.push(new google.maps.LatLng(37.775, -122.419));
        cities.push(new google.maps.LatLng(47.620, -122.347));
        cities.push(new google.maps.LatLng(1.2833, 36.8167));
        cities.push(new google.maps.LatLng(37.5833, 127.0000));

        var infowindow;

        for (var i = 0; i < cities.length; i++) {
            //create markers for each city
            var marker = new google.maps.Marker({
                position: cities[i],
                map: map,
                title: "City Number " + i
            });

            (function (i, marker) {
                //create even listeners (closures at work)
                google.maps.event.addListener(marker, 'click', function () {
                    if (!infowindow) {
                        infowindow = new google.maps.InfoWindow();
                    }
                    //set content
                    infowindow.setContent('City number ' + i);
                    //open the window
                    infowindow.open(map, marker);
                });
            })(i, marker);
            //extend our bounds here
            bounds.extend(cities[i]);
        }
        map.fitBounds(bounds);
    };
})();

There you go. You can do whatever you want with it. Now here is an app idea (warning: it might sound silly).

Happy Places
The idea is simple. Use Twitter Search and Streaming APIs to track the use of a smiley face ):. It is not hard if you try. The fun part: using the user_ids of those who used the smiley face, fetch their locations (if they have set their location on their profiles) and check them against a local list of your own. If any of them match, put a marker on a map. It should be evident that more markers within a small city might indicate that residents there are friendly or happier but that is up for debate. Either way, it sounds fun. ):

See you soon. If you have questions, please ask. Take care and thanks for stopping by!

What To Do After College and Without a Job

So you just graduated or even lost your job and you are looking for a new one. Everywhere you look, you see bad news. Everybody seems to be smarter than you, more experienced and yet willing to take less pay for the gig. You have spent so much money running around mailing your resume. It is a messy world you say.

job-interviews

The fact is, it doesn’t get any easier. What do we do now, you ask?. I am not an expert but I will give you my 2 cents. Here are some of my favorite tricks that could get you going. NOTE:  A previous study showed that only 2 percent of professionals actually use their degrees. This means that just because you have a degree in business doesn’t necessarily mean you must work in that field.

  1. NETWORKING – I list this as the first thing to do for a reason. You are more likely to get a job through referral than other means. If there is something students in college should be doing besides studying and partying, it is making connections. Save those contacts because you will need them later. If you didn’t do so, you can still catch up by using LinkedIn and other social networks. Attend local events where you will meet new people with similar interests. There is more to networking than this short description but you get the idea.
  2. VOLUNTEER – Volunteering is not easy especially when you have bills to pay. I say this because when I refer to being a volunteer, it simply means you are offering your services for FREE. The benefits sometimes outweigh the effort. How? One thing you can do while applying for a job is mention the fact that you volunteered at company A or B. Good Karma. It is better to volunteer than to sit on your couch watching reality television and eating chips. So, find a local charity or a company that could benefit from your skills. Heck, you might even get hired if they think you are worth it.
  3. JOB-SEARCH – Oh wait a minute, I am already doing this right? I totally agree with you here but I wanted to say something more specific. It is tempting to blame the economy for lack of jobs especially when you have no idea where to look. One advice I was given by someone was that when it comes to job hunting, you should make the search a full time job. The only difference is that you don’t get paid, in fact, you spend your own money running around from office to office. Warning: Do not do this: ‘You do so many interviews, when you reach your 40th interview, you ask your interviewer the name of his company! ‘ Got it? I must mention also that you can do networking and volunteering as you job search.
  4. START A BUSINESS – If you have been trying to find a job for too long without any luck, perhaps you can start your own business in your garage. Of course this move is tricky and sometimes expensive to take. Perhaps you have identified a market gab and you feel like you can help fill it. You might be a software developer and you have a great product that could revolutionize the way people do things. With today’s world, opportunities are vast but you have to work hard and smart for it. Depending on your area of expertise, I promise, there is something out there that you can do to make extra cash. Since starting a business requires some capital, you might consider looking for professional advice on how to get started.
  5. JOIN oDESK – This is just one place where you can keep your skills sharp by doing freelance work. There are thousands of people out there looking for people like you to help them get their jobs done. You might not be paid much but you will get to build connections that could lead to greater opportunities down the road. Did I mention creating a portfolio? That will come in handy when applying for a job. You want to have something to show when your interviewer asks “what projects have you worked on before?” 
  6. JOIN QUORA – This is my favorite website. You might be wondering why I even listed it here. Let me cut it to the chase: if you want professional advice, links to the best resources that you would otherwise pay a lot of hard-earned money for, help others by answering questions in areas of your expertise, and most of all, meet awesome people – Quora is your friend. It is totally FREE of charge. Warning: You might get addicted to it and that could make your girlfriend, boyfriend or spouse really mad at you – in that situation, you can tell them to blame me for it.
  7. START A BLOG – This is obviously not for everyone. Most often, maintaining a blog is a challenging task especially if you don’t have a specific idea or subject to write about. From a horse’s mouth – before I started this blog four months ago, I tried blogging and failed several times. I thought people didn’t really like what I was posting. It is easy to talk about everything and end up talking about nothing. I advise you to find something specific that you are good at and get started. Set a schedule and you will be amazed by the experience. In fact, you might be surprised by your interviewer by asking you whether you have a blog or not!
  8. WRITE A BOOK – One amazing thing about life is that when one door closes, more than one door opens. In this case, ebook publishing is a door that leads to potential success. Let us be honest here, you have a story you would like to tell. There is a book in you. If I was able to write a book and self-publish it, reach more than eleven thousand (11,000) downloads on Amazon Kindle alone, then why can’t you do it?  It is amazing how things work. Give it a shot, starting with a few hundred words every day or weekend. Talk to me if you need help.
  9. EXERCISE + FOOD – I am not a food and fitness expert but we all know that you are better equipped when you are eating healthy and exercising. Just because you don’t have a job doesn’t mean you should let your cholesterol get out of control. Take care of your body. It is easier to get tempted when you don’t have enough money to eat junk food and I totally understand it. That does not mean you should give up the fight. Just do your best to remain healthy.
  10. MORE – The list goes on and on. However, I am going to stop here because I know you have other things to do. Go out there, make a clear plan of what you really want to do. Hire a resume service and get down to work (job searching of course). Prepare to be turned down several times. Never give up. If you have other ideas, please share them through the comments section.

At the end of the day, if you are lucky to be interviewed, be honest because it is not morally upright to lie. It is easier to be caught lying. Do whatever it takes to be ready for that job because you never know when you will be meeting your next employer. With that in mind, happy April Fools Day! I am not fooling you at this point. Good luck and see you soon.

Programming With Google Maps APIs – Part V

Hello! I am back and I hope you are doing good today. At the end of my fourth Google Maps APIs  post, I mentioned in passing that I will be starting with Markers today and that is exactly where I will start. To make things fun, here is what a marker looks like – you have probably seen one if you have used a map before!

google-maps-api-marker

There you have it! So a marker is a small image that is positioned at a specific place on a map. Now we can figure out how to add it to our own map. We will start with a basic code for our map.

(function () {
    window.onload = function () {
        var mapDiv = document.getElementById('map');
        var latlng = new google.maps.LatLng(40.7257, -74.0047);

        var options = {
            zoom: 12,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(mapDiv, options);

    };
})();

Adding a Marker
You can choose to go with the default look of a marker or create your own. I will use the former in this example. A marker is of type google.maps.Marker object. This object takes one parameter which is of type google.maps.MarkerOptions . MarkerOptions has several properties that you can use to make the marker look and behave different but the basic two are: position and map.

position – this property defines the coordinates to place the marker and takes an argument of type google.maps.LatLng object.

map – the map property is a reference to the map to which you want to add the marker.

Example code for a marker

(function () {
    window.onload = function () {
        var mapDiv = document.getElementById('map');
        var latlng = new google.maps.LatLng(37.3700, -122.0400);

        var options = {
            zoom: 12,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(mapDiv, options);

        var marker = new google.maps.Marker({
            position : latlng,
            map : map
        });

    };
})();

There you have it. Oh wait, we have not seen it actually on a map yet. Here it is:

google-maps-api-markers

Adding a tooltip

We might both agree that adding a tooltip to our marker will make it much better. A tooltip is a yellow box with some text in it that appear when you hover your mouse over a marker. To add it to our marker, we simply use title property of the MarkerOptions object.

. //minimized code here from above
.
.
var map = new google.maps.Map(mapDiv, options);

var marker = new google.maps.Marker({
            position : latlng,
            map : map,
            title: 'Click Me Now'
});

One thing to note is that you are not limited to using the default marker icon. In fact, Google hosts a ton of other icons that you can freely use. In order to use a different icon, you provide a url location to it like this:

var marker = new google.maps.Marker({
             position: latlng,
             map: map,
             title: 'Click Me Please',
             icon : 'http://youricon-location.com'
});

Adding an InfoWindow

Normally when marking a place on a map, you might want to show more information related to that place. Google Maps APIs provides a way to do so using InfoWindow. It looks like a speech bubble and appears on top of a marker when you click it.

InfoWindow resides in the google.maps namespace. It takes one argument which is an object called InfoWindowOptions. Just like MarkerOptions object, InfoWindowOptions has several properties but the most important one is the content.  This property controls what will show inside the info window. It can be plain text, HTML or a reference to HTML node.

Code Example:

. //minimized code
. //save space
.
var map = new google.maps.Map(mapDiv, options);
var marker = new google.maps.Marker({
            position : latlng,
            map : map,
            title: 'Click Me Now'
});
//added a class for styling the window
var infowindow = new google.maps.InfoWindow({
      content : "<div class='infowindow'>You are awesome</div>"
});
.
.

Now that we have created our infowindow, running this code as is … well, won’t work yet. The reason is this: we have to connect the marker with our infowindow. How do we do that? Thanks to Google Maps APIs, we have google.maps.event.addListener() method to the rescue. This method takes three arguments ( the object it is attached to, the event it should listen for and the function (event handler) to call when the event is triggered.

Before I show you the code, it would be clear to mention that the InfoWindow object has a method called open() which takes two arguments – map: this is a reference to the map it will be added to(in case you have more than 1 map) and the second argument is the object that the   InfoWindow will attach itself to. In our case, we want to attach it to the marker being clicked!

Now code:

.
.
//added a class for styling the window
var infowindow = new google.maps.InfoWindow({
      content : "<div class='infowindow'>You are awesome</div>"
});

//add event listener
google.maps.event.addListener(marker, 'click', function(){
      infowindow.open(map, marker);
});
.
.

Here is how it looks in action:

google-maps-api-infowindow

That icon is called abduction. You can also see the shadow! Awesome.

More Markers – markersville

The question you might have asked yourself is this: how do I add more than one marker to my map without manually creating them? One thing I have assumed all along is that you are familiar with JavaScript and with that in mind, using a for loop and an array sounds like a good idea!

More United States Cities on the Map

I am going to show you the entire piece of code that does several things: (i) add markers (ii) add infowindows and (iii) eliminate duplicate windows. It will make much sense once I explain it.

(function () {
    window.onload = function () {
        var mapDiv = document.getElementById('map');

        var options = {
            zoom: 3,
            center: new google.maps.LatLng(37.09, -95.71),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(mapDiv, options);

        var cities = [];
        cities.push(new google.maps.LatLng(40.756, -73.986));
        cities.push(new google.maps.LatLng(37.775, -122.419));
        cities.push(new google.maps.LatLng(47.620, -122.347));

        var infowindow;
        for (var i = 0; i<cities.length; i++) {
            //create markers for each city
            var marker = new google.maps.Marker({
                position: cities[i],
                map: map,
                title: "City Number " + i
            });

            (function (i, marker) {
                //create even listeners (closures at work)
                google.maps.event.addListener(marker, 'click', function () {
                    if (!infowindow) {
                        var infowindow = new google.maps.InfoWindow();
                    }
                    //set content
                    infowindow.setContent('City number ' + i);
                    //open the window
                    infowindow.open(map, marker);
                });
            })(i, marker);
        }
    };
})();

Three markers:
google-maps-api-more
Clicking on any of the markers results in the following:

google-maps-apis-final

Everything up until line 11 should be second nature to you by now, I hope. Now, at line 12…15, I simply defined an array and added three cities to it.

On line 17 – I defined a variable infowindow which will come in handy when we want to avoid duplicating info windows by checking if one already exists.

On line 18…24 – I use a for loop to create markers and from

Line 26…37 – I used an anonymous function within the for loop to add event listeners to each of the markers. Everything within the anonymous function is much like what we have been doing all along – creating an info window, setting the content and finally opening it when a marker is clicked.

I am using closures here to avoid a situation where no matter which marker you click, the infowindow will open for the marker that was created last(always ‘infowindow number 3’). You can read more about closures by visiting Douglas Crockford’s Post .

I am going to stop here because I think this is long enough. I will do more fun stuff next time. If you notice any errors, please notify me and I will fix them as soon as possible. If you have any questions please let me know through the comments section. Hopefully this taught you something meaningful. Thank you for stopping by.

Programming With Google Maps APIs- part IV

Hello! If you have been here before, you might have noticed that I decided to change my blog theme and I hope you like this just like I do. I wanted to make reading easier and still maintain a cleaner look. That being said, let me start our 4th post on Google Maps APIs. My 3rd post had this code:

(function () {
    window.onload = function () {
        var mapDiv = document.getElementById('map');
        var latlng = new google.maps.LatLng(37.09, -95.71);

        var options = {
            center: latlng,
            zoom: 4,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            disableDefaultUI: true,
            navigationControl:true,
            keyboardShortcuts: false,
            disableDoubleClickZoom: true,
            draggable: false,
            streetViewControl: true,
            navigationControlOptions :{
                position: google.maps.ControlPosition.TOP_RIGHT,
                style: google.maps.NavigationControlStyle.ZOOM_PAN
            }
        };
        var map = new google.maps.Map(mapDiv, options);
    };
})();

Now let us move on to something new:

Controlling The Map Container

As I said yesterday(in post number 3), when I say ‘the map container’, I am referring to the html element(<div id=”map”>) that contains the map. The MapOptions object contains some properties that control the behavior of this map container.

noClear

Every time your map loads on the browser, it clears the map container (div element) of any content before inserting anything. Setting noClear to false will preserve the content of the map container. The opposite is true.

backgroundColor

This property sets the color of the container’s background. You will notice this when panning the map and before the map tiles are loaded. You can set its value using either hexadecimal value code starting with a ‘#’ symbol or using standard color keywords like ‘blue’, ‘white’ etc.

Code Example – noColor and backgroundColor

.
.
var options = {
        zoom: 3,
        center: new google.maps.LatLng(37.09, -95.71),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        noClear: true,
        backgroundColor: '#bbccff'
};
.
.

Controlling The Cursor

These set of properties control how the cursor will look like under certain circumstances.

draggableCursor

You can use this property to control what cursor to use when hovering over a draggable  object on the map – like the pegman! You can set it either by providing it with the name of the cursor like ‘crosshair’, ‘pointer’, or ‘move’, or using a url  to your own image. There are more names to explore.

draggingCursor

This is similar to draggableCursor except it controls the cursor being used while dragging an object in the map.

Combined Code Example:

var options = {
        zoom: 3,
        center: new google.maps.LatLng(37.09, -95.71),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        noClear: true,
        backgroundColor: '#bbccff',
        draggableCursor: 'move',
        //draggingCursor: 'move'
};

Controlling The Map Settings Using Methods

It has been fun changing properties of our map options. The question now remains: how do we change the same properties after the map is loaded? Don’t worry! There is a way out of this – the map object has methods.

There are two kinds of methods: the generic setOptions() method and specific methods for each of the properties.

setOptions

This is a method of the map object and it takes a mapOptions object as the only attribute. Using it simply entails creating an object literal and then passing it to this method.

var options = {
   zoom : 4
};

map.setOptions(options);

//or you can be cool and do this:

map.setOptions({
   zoom: 4,
   mapTypeId: google.maps.MapTypeId.SATELLITE
});

You can use the setOptions() method to change most of the map properties except a few:

  • backgroundColor
  • disableDefaultUI
  • noClear

That means that you should be careful to define these properties up front while initializing the map.

The Specific Methods

These types of methods are available for both setting and getting the values of the required properties of the mapOptions object: center, zoom and mapTypeId.

Getting and setting the zoom level

var zoomlevel = map.getZoom();
map.setZoom(18); //number

Getting and setting the center of the map

var center = map.getCenter();
map.setCenter(latlng: LatLng);

Getting and setting the mapTypeId

var maptype = map.getMapTypeId();
map.setMapTypeId(mapTypeId: MapTypeId)

Using the getter and setter methods for good!

Since we now know about the methods and the fact that we can use them to do some fun stuff to our map, like changing the map type and zoom, let us see how we can improve our map. Inside our index.html file, we add two buttons to get values and set values respectively.

<!DOCTYPE html>
<html lang="en">
    <head>
       <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
   	  <title>Google Maps Tutorial</title>
   	  <script src="http://maps.google.com/maps/api/js?sensor=false"></script>
   	  <script src="map.js"></script>
   	  <link rel="stylesheet" type="text/css" href="main.css" />
    </head>
    <body>
        <h1>Welcome To Google Maps</h1>
        <input type="button" id="getValues" value="GET-VALUES" />
        <input type="button" id="setValues" value="SET-VALUES" />
        <div id="map"></div>
    </body>
</html>

And now the main code that does the job:

(function () {
    window.onload = function () {
        var mapDiv = document.getElementById('map');
        var latlng = new google.maps.LatLng(37.09, -95.71);

        var options = {
               zoom: 3,
               center: new google.maps.LatLng(37.09, -95.71),
               mapTypeId: google.maps.MapTypeId.ROADMAP,
               noClear: true,
               backgroundColor: '#bbccff',
               draggableCursor: 'move'
        };
        var map = new google.maps.Map(mapDiv, options);

        document.getElementById('getValues').onclick = function(){
            alert(map.getZoom());
            alert(map.getCenter());
            alert(map.getMapTypeId());
        }
        document.getElementById('setValues').onclick = function(){
            map.setOptions({
                center: new google.maps.LatLng(36.1000, 112.1000),
                zoom: 16,
                mapTypeId: google.maps.MapTypeId.SATELLITE
            });
        }
    };
})();

If you end up running this code on your own, try guessing where the second map shows (it is somewhere in North America). If you don’t know, you can copy and paste the coordinates shown above to the Google search bar. You can get the values by simply clicking the GET-VALUES button on top of the map. Either way, this is how our map looks like:

google-maps-api-methods
Clicking the SET-VALUES button will change our map from the above type to the one below showing a specific location(try guessing it first).

google-maps-last
Try zooming out as you see if you can identify this secret location.
Thank you for reading through this post. I will stop here because I believe I have done enough for today. If you have any questions, please ask me and I will be more than glad to answer them. Next post will include concepts like markers and more fun features. See you soon!

Programming With Google Maps APIs – Part III

Hello! Thanks for stopping by. I didn’t post anything yesterday because I was asked to read and review an AngularJS Starter book which ended up taking all my time. It was a good experience because I learned some new stuff. That being said, today, I am going to continue with our Google Maps APIs series. My last post  ended with the code below and so let us pick up from there:

(function () {
    window.onload = function () {
        var mapDiv = document.getElementById('map');
        var latlng = new google.maps.LatLng(37.09, -95.71);

        var options = {
            center: latlng,
            zoom: 4,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            mapTypeControl: true,
            mapTypeControlOptions : {
                style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
                position : google.maps.ControlPosition.TOP,
                mapTypeIds :
                    [ google.maps.MapTypeId.ROADMAP,
                      google.maps.MapTypeId.SATELLITE ]
            }
        };
        var map = new google.maps.Map(mapDiv, options);
    };
})();

navigationControl

This property displays or hides the navigation control. That is the control that typically resides in the upper-left side of the map with which you can zoom and sometimes pan the map.

Code Example:

.
.
 var options = {
            center: latlng,
            zoom: 4,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            disableDefaultUI: true,
            navigationControl:true //here
        };
.
.

navigationControlOptions

With the navigationControlOptions property, you determine the look of the navigationControl. It pretty much works like mapTypeControlOptions by taking an object as its value. The object is of type: google.maps.NavigationControlOptions and it has two properties : position and style. It might sound familiar if you read my first two posts.

  1. position – this property is of type google.maps.ControlPosition.
  2. style – this property comes in several flavors and they all reside in google.maps.NavigationControlStyle. They are :
  • DEFAULT – if set to this value, the control will vary according to the map size and other factors. It displays either small or large.
  • SMALL – this is, well, the small control. Only allows you to zoom the map.
  • ANDROID – android anybody? This control is specifically tailored for android smartphones.
  • ZOOM_PAN – this is the large control that lets you to both zoom and pan the map.

Code Example:

.//using both position:TOP_RIGHT and style:ZOOM_PAN
.
var options = {
            center: latlng,
            zoom: 4,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            disableDefaultUI: true,
            navigationControl:true,
            navigationControlOptions :{
                position: google.maps.ControlPosition.TOP_RIGHT,
                style: google.maps.NavigationControlStyle.ZOOM_PAN
            }
        };
.
.

This is how the map will look like with the code above:

google-maps-api-3

As you can see, the position is top-right and the style is zoom_pan meaning you can do both zooming and panning of the map. In order to use the above property, you must set navigationControl to true.

scaleControl

This property determines whether the scale control will be displayed or hidden. The default value is false meaning it is not displayed. If you want to show it on your map, you must set it to true.

.
.
var options = {
    zoom: 8,
    .
    .
    scaleControl: true //this line
};

scaleControlOptions – Using this property, you control how scaleControl will be displayed. It takes an object of type google.maps.ScaleControlOptions. Just like NavigationControlOptions, it has two properties: guessed them yet? Position and Style. In order to use scaleControlOptions, you must also use and set scaleControl to true. (Sounds familiar right?).

keyboardShortcuts

This property enables or disables the ability to use the keyboard to navigate the map. It is true by default but you can change it to false to disable it.

disableDoubleClickZoom

Double-clicking on a map normally zooms in but if you want to disable that property, you set disableDoubleClickZoom to true.

draggable

You can pan the map by default by simply dragging it around. If for some personal reason you would like to disable it, set draggable to false.

scrollwheel

You can use this property to decide whether you want to use your mouse to zoom in and out by simply scrolling the wheel of your mouse. It is set to true by default. You can, for some alien reason, set it to false to disable it.

streetViewControl

This property shows or hides the Street View Control (wildly known as pegman). The default value of this property is false. You can set it to true to enable it. If you set the value to true, the map will display an orange pegman right above the zoom control.

Combined Code Example:

.
.
var options = {
            center: latlng,
            zoom: 4,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            disableDefaultUI: true,
            navigationControl:true,
            keyboardShortcuts: false,
            disableDoubleClickZoom: true,
            draggable: false,
            streetViewControl: true,
            navigationControlOptions :{
                position: google.maps.ControlPosition.TOP_RIGHT,
                style: google.maps.NavigationControlStyle.ZOOM_PAN
            }
        };
        var map = new google.maps.Map(mapDiv, options);
.
.

Before I finish this post for today, I would like to show you a snapshot of our final map with the above code:

google-maps-api-controls
I used squares and rectangles to indicate the controls and their positions. You might be curious to know what really happens when you drag the pegman around! This is what happened when I dragged it to some street in Kansas! It switched to Street View mode – Warning: you might see someone you know, seriously, you might!
google-maps-api-kansas
I told you it was pretty clear you might actually see your friend sneaking around. The good part, ‘we are not in Kansas anymore’.

Thanks again for stopping by and I hope you learned something from this post. Next time I will jump into Controlling the Map Container – the html div element that contains our map, then some more cool and fun stuff. If you spot an error, please let me know. Please share this post if you like it. ‘See you’ soon and take care of yourself!

How To Install Pik and Run Commands on Git Bash – Ruby

A few weeks or so ago, I was learning Ruby on Rails and I couldn’t avoid running into the version control issue with Ruby. Consider a situation where you are running Ruby 1.93 but you want to write code that works with a different version of Ruby like Ruby 2.00. The solution is to perhaps install more than one version right? Now after installing more than one version, you might be wondering how to switch from one version to another. That is why I am doing this tutorial.

This tutorial is meant for Windows computers! The idea is to install a ruby version manager for Windows. People using Macs might be familiar with something called rvm for … you guessed it … ruby version manager. People using windows however, have pik and it is totally free to download and use. So, without much ado, here is the video tutorial I created to make things easier. It is complete with examples.

So, there you have it. I hope it helped you and if you run into any problem, do not hesitate to ask because I will be more than happy to help.

Please remember to subscribe if you like what you see here. Thanks for stopping by and please leave me some comments.

Stay safe and see you soon!

Object-oriented Programming In PHP – Part II

Yesterday I created a post on OOP and had to split it in two to avoid making it too long. Today, I am going to finish up the remaining part before starting other stuff! So, let us get started here.

object-oriented-programming

Controlling Visibility Through Inheritance With private and protected

While writing code using OOP, you can use private and protected visibility modifiers to control what gets inherited. Attributes or methods declared as private will not be inherited. If an attribute or a method is marked as protected, it will not be visible outside the class (like private) but will be inherited. Example:

<?php
   class A
   {
     private function operation1(){
       echo 'operation1 was called';
     }
     protected function operation2(){
       echo 'operation2 was called';
     }
     public function operation3(){
       echo 'operation3 was called';
     }
   }

   class B extends A
   {
     function __construct(){
       $this->operation1();
       $this->operation2();
       $this->operation3();
     }
   }

   $b = new B();

   #----------------------------------------------------#
   |The above code creates a class A with three methods |
   |with private, protected and public accessibility    |
   |As I mentioned earlier, private attributes and      |
   |methods are not inherited - that means that operat- |
   |ion1() will result in an error when you call class B|
   |constructor                                         |

   |Fatal error: Call to private method A::operation1() |
   |from context 'B'                                    |
   #----------------------------------------------------#

   #The protected operation2() can only be used inside  #
   #the child class but not outside. That being said,   #

   $b->operation2();

   #will result in an error!
   #public operation3() however will not result in any  #
   #error
   $b->operation3();

?>

Overriding

We have shown that a subclass can declare new attributes and methods. It is also valid and sometimes useful to re-declare the same attributes and operations. You might do it to give an attribute in the subclass a different default value to the same attribute in its superclass or to give an operation in the subclass a different functionality to the same operation in its superclass. This is called overriding.

Consider:

<?php
   class A
   {
     public $attribute = "default value";
     function operation(){
       echo "Something <br />";
       echo "The value of \$attribute is ".$this->attribute."<br />";
     }
   }

   #Now if you want to alter the default value of $attribute
   #and provide new functionality to operation() you can create
   #the class B that inherits from A like this:

   class B extends A
   {
     public $attribute = "different value";
     function operation(){
       echo "Something else<br />";
       echo "The value of \$attribute is ".$this->attribute."<br />";
     }
   }

   #Declaring B does not affect the original declaration of A
   #Now see what happens here:

   $a = new A();
   $a->operation();
   #----------------------RESULT----------------------#
   #Something
   #The value of $attribute is default value
   #---------------------Now create one for B---------#

   $b = new B();
   $b->operation();
   #---------------------RESULT-----------------------#
   #Something else
   #The value of $attribute is different value

   #NOTE: overriding attributes and operations in a
   #subclass does not
   #affect the superclass

   #The parent keyword allows you to call the original version
   #of the operation in the parent class. To call A::operation()
   #in class B, you simply do this:
   parent::operation();
?>

Preventing Inheritance and Overriding with final

In PHP, using the keyword final in front of a function prevents it from being overridden in any subclasses. For instance, we could add it to our operation in our class A like this:

<?php
   class A
   {
     public $attribute = "default value";
     final function operation(){
       echo "Something <br />";
       echo "The value of \$attribute is ".$this->attribute."<br />";
     }
   }
   #-------------------------------------------------------#
   #using final prevents you from overriding operation in class
   #B and an attempt to do so will result in a fatal error!
   #Fatal error: Cannot override final method A::operation()

   #You can also use final to prevent a class from being
   #subclassed like so:

   final class A
   {
     //--------------
   }
   #Trying to inherit from A now will result in an error message:
   #Fatal error: Class B may not inherit from final class (A)
?>

Understanding Multiple Inheritance

PHP does not support multiple inheritance – that means each class can only inherit from one parent. There is however no restriction on how many children can share the same parent.

Implementing Interfaces

Since PHP does not support multiple inheritance, you use interfaces to solve problems that would otherwise require multiple inheritance. The idea of an interface is that it specifies a set of functions that must be implemented in classes that implement the particular interface.

Consider a situation where you have a set of classes that you want them to be able to display themselves. Instead of having a parent class with a display() method that they all inherit and override, you can simply implement an interface as follows:

<?php
   interface Displayable
   {
      function display();
   }

   class webPage implements Displayable
   {
     function display(){
       //do some display work here for web page
     }
   }

   #Failure to implement the display() function will result
   #in a fatal error. It is also worth mentioning that
   #a class can inherit from one class and implement more than
   #one interface!
?>

Designing Classes

When I was working on my simple shopping cart, I used some include() or require() to maintain consistency throughout the pages. Now that we know what classes and functions do, we should be able to generate our web pages dynamically!

That will be really fun and that is why I want to save it for tomorrow to avoid diluting it with what I have already done today! I hope you will join me for this fun adventure because it will be so much fun.

Thanks for stopping by and if you have any questions or have spotted any errors, let me know. Take care and see you!

Object-Oriented Programming In PHP – Part I

According to Wikipedia , Object-oriented programming(OOP) is a programming paradigm that represents concepts as objects that have data fields (attributes that describe the object) and associated procedures known as methods. An object  is an instance of a class – that is, you use a class to create an object. The easiest way to understand OOP is using a real-world example.

object-oriented-programming-cars

Looking at the above image makes our work really easier here. In real life, there is something called a car. But you can’t just walk to your friend’s house and say I own a car and assume that they will automatically know what type of car you have. So, in other words, our car is a class and from that car class, we can create different kinds of cars(objects) like Toyota, Ford, Chevy etc. Oh, don’t forget the VW Bug!

To make this a little understandable, we can break the car concept into data fields and methods. Every car has some color(attribute), and most importantly they move(method). What else can you think of? A car can either be on or off. The other fact is that different cars have different other properties. Think of them!

Another good example is a cookie-cutter. You can think of a cookie-cutter as a class and the cookies themselves as objects.  Using your cookie-cutter, you can create all shapes of cookies, using different recipes.

Encapsulation

One of the biggest advantage of OOP is its capability to support and encourage encapsulation – also known as data hiding. Essentially, access to the data within an object is available only via the object’s operations, known as the interface of the object.

Polymorphism

Polymorphism means different classes can have different behaviors for the same operation. Consider having a class Car and a class Bicycle. They can both have different move operations. Polymorphism is more a characteristics of behaviors than it is of objects. In PHP, only member functions of a class can be polymorphic.

Inheritance

Inheritance allows you to create a hierarchical relationship between classes using sub-classes.  If you are asking whether this works like a son inheriting a million dollars from his father or not, then you are thinking right! A subclass inherits attributes and operations from the superclass.  An example could work like this: we both know that a car and a bicycle have certain things in common. You could then use a class called vehicle that contain a color attribute and a move operation that all vehicles have. You can simply then have both car and bicycle classes inherit from vehicle class – how nice right?

Using inheritance might save you work if operations can be written once in a superclass rather than many times in separate subclasses. It might also allow you to more accurately model real-world relationships. If a sentence about two classes makes sense with “is a” between the classes, inheritance is probably appropriate.The sentence “a car is a vehicle” makes sense, but the sentence “a vehicle is a car” does not make sense because not all vehicles are cars.Therefore, car can inherit from vehicle.

Creating Classes, Attributes and Operations

Let us get our hands dirty here by …you guessed it, creating classes, attributes and operations in php. When creating a class, the keyword class must be used.


<?php
   #the structure of a class
   #opening and closing braces
   #---------------------------------------------------------#
   class classname
   {
     #do stuff here - attributes and operations
   }
   #---------------------------------------------------------#
   #Obviously, without attributes and operations, our class
   #is not that useful. So let us add some attributes
   #---------------------------------------------------------#
   class classname
   {
     public $attribute1;
     public $attribute2;
   }
   #---------------------------------------------------------#
   #the above code creates a class called classname and
   #two attributes $attribute1, $attribute2 with [public]
   #visibility. visibility options[public, private, protected]

   #We have added attributes but we have no way of operating
   #on them, so why not add some methods to our brand new class?
   #---------------------------------------------------------#
   class classname
   {
     public $attribute1;
     public $attribute2;

     #now add two methods here
     function operation1(){
        //do some cool math here
     }

     function operation2($param1, $param2){
        //do some other crazy rocket-propulsion.
     }
   }
   #--------------------------------------------------------#
   #As you can see, we created two functions inside our class
   #and we call such functions ... methods because they are in
   #the class!
?>

Constructors

Most classes have a special type of operation called a constructor. A constructor is called  when an object is created and also normally performs useful initialization tasks such as setting attributes to sensible starting values or creating other objects needed by the object.

A constructor is declared the same way as other operations inside a class but has the special name __construct() and although you can manually call a constructor, its purpose is to be called automatically when an object is created. Time for an example:

<?php
   #declaring a constructor for a class
   #----------------------------------------------#
   class classname
   {
     public __construct($param) #our constructor
     {
        //do some initialization or setup here
        echo "Constructor called with parameter: ".$param."<br />";
     }
   }

   #PHP supports function overloading - providing more than one
   #function with the same name with different numbers or types
   #of parameters!
?>

Destructors

Just like constructors, there exist destructors. They are special in the sense that they don’t take any parameters and declared as __destruct(). When all references to a class have been unset or fallen off a scope, it gets destroyed. If you then want to have some functionality executed before the class is destroyed, you use the destructor!

Instantiating A Class

After declaring your class, you need to create an object – a particular individual that is a member of the class. You can then do something with it. As I mentioned earlier, it is called instantiating or creating an instance of a class. You create an object by using the new keyword. When you do so, you need to specify which class your object will be an instance of and provide any parameters required by the constructor. Time for an example:

<?php
   #from our first class earlier;
   class classname
   {
     public __construct($param)
     {
        echo "Constructor called with parameter: ".$param."<br />";
     }
   }

   #--------------------NOW INSTANTIATE-------------------------#
   $a = new classname("first");  #param - first
   $b = new classname("second"); #param - second
   $c = new classname();         #param - none

   #Running the above code will result in: guessed it?
   #Constructor called with parameter: first
   #Constructor called with parameter: second
   #Constructor called with parameter:
?>

Using Class Attributes

Within a class, you have access to special pointer called $this. If an attribute of your current class is called  $attribute you refer to it as $this->attribute when either setting or accessing the variable from an operation within the class.

<?php
   #demonstrating how to use attributes inside a class
   class classname
   {
     public $attribute;

     function operation($param)
     {
       $this->attribute = $param;
       echo $this->attribute;
     }
   }
   #Access modifiers [public, private, protected] determine
   #whether you can access an attribute outside a class or not.

   #---------------------CONSIDER THIS--------------------#
   class classname{
     public $attribute;
   }
   $a = new classname();
   $a->attribute = "value";
   echo $a->attribute;
   #--------------------EXPLANATION-----------------------#
   #Since the $attribute variable is declared as [public],
   #we can access it outside and even change the value!
?>

Doing what we did above(accessing attributes and changing their values outside a class is obviously not a good idea.To avoid such a problem, we take advantage of OOP’s encapsulation. We enforce it by using __get and __set functions. These functions are commonly known as setters and getters or accessor functions. Example:

<?php
   class classname
   {
      public $attribute;

      function __get($name){
        return $this->$name;
      }
      function __set($name, $value){
        $this->$name = $value;
      }
   }
?>

Now our above code provides minimal functions to access our attributes. Basically, our __get function returns the value of the attribute with the same name as the one passed in ($name). __set() on the other hand takes a name of an attribute and a value, then sets the value of the attribute to the value passed in!

One thing to remember is that you do not call __get and __set functions directly. You may be asking, so how do we then call them? Here is the thing: when you instantiate an object like this:


<?php
   $a = new classname();
?>

You can then use __get() and __set() functions to check and set the value of any attributes: If you type:

<?php
   $a->$attribute = 5;
?>

The above statement implicitly calls __set() with the value of $name set to “attribute”  and the value of $value set to 5. You need to write __set() to do error handling.

The __get() function works in a similar way. If, in your code, you reference

<?php
   $a->attribute
?>

this expression implicitly calls the __get() function with the parameter $name set to “attribute”. It is up to you to write the __get() function to return the value.

Let us improve our __set() function to do some error checking!

<?php
   function __set($name, $value){
      if(($name == "attribute") && ($value >=0) && ($value <=100)){
         $this->attribute = $value;
      }
   }
?>

Access Modifiers Debunked

There are three main access modifiers and they are described below:

  1. public – this is the default option. That means that failure to declare an access modifier on an item makes it public. The particular item will be accessible both in and outside the class.
  2. private – this means that the marked item is only accessible within the class. You may also declare some methods as private – for example if they are utility functions used only inside the class. Items that are private will not be inherited.
  3. protected – this means the marked item can only be accessed within the class. It also exists in subclasses! Think of this as halfway between private and public.

Calling Class Operations

Let us quickly look at an example of calling operations(methods)!

<?php
   class classname
   {
      function operation1(){
         //---do something
      }

      function operation2($param1, $param2){
         //---do other stuff
      }
   }
   #create an instance now
   $a = new classname();

   #You then call the operations as you would call any
   #other function:
   $a->operation1();
   $a->operation2(12, 'test');

   #if our operation returns something, you can store it as:
   $x = $a->operation1();
   $y = $a->operation2(10, "sample");
?>

Implementing Inheritance In PHP

If a class is to subclass another class, you can use the extends keyword. Example here: Consider a class B that extends another class previously created by a friend A.

<?php
   class B extends A
   {
      public $attribute2;
      function operation2(){
         //do something here
      }
   }

   class A
   {
      public $attribute1;
      function operation1(){
         //do something here
      }
   }

   #Now you can do these:
   $b = new B();
   $b->operation1();
   $b->attribute1 = 10;
   $b->operation2();
   $b->attribute2 = 5;

   #Since class B extends class A, you can access both
   #operation1() and $attribute1
   #NOTE: inheritance works only in one direction - that is:
   #a subclass can only inherit from the superclass and not
   #the other way round.
   #-----------CONSIDER THIS NOW--------------------#
   $a = new A();
   $a->operation1();  #valid
   $a->attribute1 = 21; #valid
   $a->operation2(); #invalid
   $a->attribute2 =100; #invalid
?>

I am going to stop here then continue tomorrow. I hope you found this helpful. If you have any questions or errors you might have spotted, let me know. There are just a few more concepts that should fit into a single post bringing this OOP topic to an end. Stay safe and hope to see you soon! Please drop me a line in the comment section.

Writing Your Own Functions – PHP

Functions exist in most programming languages and they separate code that performs a single well-defined task. This makes it easier to read and reuse the code. A function is a self-contained module of code that prescribes a calling interface, performs some task and optionally returns a result.

There are several reasons to write your own functions in PHP; for instance if you want to perform a task that other built-in functions cannot help you do. Let us quickly look at an example of a function call before we do function definition.

<?php
  #call a function in php
  function_name();

  #this line calls a function named function_name that does not
  #require parameters. This line also ignores any possible values
  #that might be returned by the function.

  #You might have come across phpinfo() function used to test
  #php version, information about php, the web server setup etc
  #it takes no parameters:
  phpinfo();
?>

Most functions however do require a parameter or more – which are the inputs to the functions. If a function expects a parameter to be passed, you can either pass in the exact value or a variable containing the value. Let us see an example

<?php
   #this function expects 1 parameter (string):
   function_name('parameter');

   #this function expects a number:
   function_name(2);

   #we use a variable as a parameter here
   function_name($age);

   #Consider fopen() function's prototype here:
   resource fopen(string filename, string mode
                    [, bool use_include_path [, resource context]]);

   #The above prototype tells you several things: resource word tells
   #you that the function fopen() returns a resource(an open file
   #handle). The function parameters are inside the parentheses:
   #filename & mode are both strings and then bool use_include_path
   # and lastly
   #context which is of type resource!

?>

The square brackets around use_include_path and context indicate that these parameters are optional.That means you can choose to provide values for optional parameters or you can ignore them in which case the default values will be used. Note that for functions with more than one optional parameter, you can only leave out parameters from the right. In our example, you can leave out context or both use_include_path and context but you cannot leave out use_include_path and provide context.

Knowing the above prototype therefore makes it easier to understand the code below as valid:

<?php
   $name = 'myfile.txt';
   $openmode = 'r';
   $fp = fopen($name, $openmode);

  #the above line calls fopen() passing in $name and $openmode
  #whatever is returned is stored in $fp variable
?>

One common mistake among new php users is calling a function that is not defined. If you do that, you will get an error message! Always check to see if your functions are spelled correctly during definition and check to see if the function exists in the version of PHP you are using.

You might not always remember how the function names are spelled. For instance, some two-word functions have an underscore between the words and some don’t. The function stripslashes() runs the two words together while strip_tags() separates the two words with an underscore.

You will also get an error message if you try to call a function that is part of a PHP extension that is not loaded. It is a good thing to name your functions with lowercase for consistency.

The cool thing about programming languages is the ability to write your own functions. You are not limited to using built-in php functions!

Basic Function Structure in PHP

A function definition starts with the keyword function and then followed by a name, then the parameters required and contains the code to be executed each time this function is called:

<?php
   #define a function
   function my_function(){
      echo 'Hello, my function was called';
   }

   #we can now call our function as follows:
   my_function();   #you can guess the output!

   #built-in functions are available to all php scripts but
   #your declared functions are only available to the scripts
   #in which they were declared. It is a good idea to have a file
   #or set of files containing your commonly used functions. You
   #can then use require() to make them available to your scripts.
?>

Naming Functions In PHP

The main point to consider while naming your functions is; short but descriptive. Consider a page header function – pageheader() or page_header() sound pretty good! There are restrictions to follow:

  • Your function cannot have the same name as an existing function.
  • Your function name can only contain letters, digits and underscores.
  • Your function name cannot begin with a digit.

As opposed to other languages, function overloading – the feature that allows you to reuse function names, in PHP is not supported.

<?php
   //examples of valid function names
   name()
   name2()
   name_three()
   _namefour()

   //examples of invalid function names
   5name()
   name-six()
   fopen()   #this could be valid if it didn't already exist!

?>

Using Parameters In Functions

<?php
   function create_table($data) {
      echo "<table border=\"1\">";
      reset($data); // Remember this is used to point to the beginning
      $value = current($data);
      while ($value) {
         echo "<tr><td>".$value."</td></tr>\n";
         $value = next($data);
      }
      echo "</table>";
   }

   #You can call create_table($data) by passing in values like this:
   $my_array = array('This is Line one', 'This is Line two',
                     'This is Line three', 'This is Line four');
   create_table($my_array);

?>

If you run that simple code, you will get:
functions-testing

Just like built-in functions, your functions can have no parameters, one parameter or more than one parameter. Let us improve our above function to include some optional parameters:

<?php
   #allow the caller to set the border width, cellspacing and
   #cellpadding:
   function create_table2($data, $border=1,
                         $cellpadding=4, $cellspacing=4 ) {
      echo "<table border=\"".$border."\"
                        cellpadding=\"".$cellpadding."\"
                        cellspacing=\"".$cellspacing."\">";
      reset($data);
      $value = current($data);
      while ($value) {
         echo "<tr><td>".$value."</td></tr>\n";
         $value = next($data);
      }
   echo "</table>";
   }

   #Now let us call our function passing in the parameters
   $my_array = array('This is Line one.','This is Line two.',
                     'This is Line three', 'This is Line four.');
   create_table2($my_array, 3, 8, 8);
?>

If we run the above code, we get a much better table because we can adjust the parameter values as we wish. If we don’t supply them, the default values are used! This is what we get on the browser.
better-function

Understanding Scope

A variable scope controls where that variable is visible and usable. Below are the simple rules in PHP to follow:

  1. Variables declared inside a function are in scope from the statement in which they are declared to the closing brace at the end of the function. This is called function scope. These are called local variables.
  2. Variables declared outside functions are in scope from the statement in which they are declared to the end of the file but not inside functions. This is called global scope. These variables are called global variables.
  3. The special superglobal variables are visible both inside and outside functions.
  4. Using require() and include() statements does not affect scope. If the statement is used inside a function, the function scope applies. If it is not inside a function, the global scope applies.
  5. The keyword global can be used to manually specify that a variable defined or used inside a function will have a global scope.
  6. Variables can be manually deleted by calling unset($variable_name) .A variable is no longer in scope if it has been unset.

Example of scoping:

<?php
   #declare a function and a variable inside it
   function fn(){
      $var = "contents";
   }

   #the $var variable declared inside our fn() function has function
   #scope.
   fn();
   #Trying to refer to $var outside our fn() function will create a
   #new $var variable with global scope.It will be visible till the
   #end of the file. Using $var with just echo will return nothing
   #because it has no value at the moment.
   echo $var;

   #The inverse of the above example:
   function fn(){
      echo "inside the function, \$var = ".$var. "<br />";
      $var = 'contents 2';
      echo "inside the function, \$var = ".$var. "<br />";
   }
   $var = 'contents 1';
   fn();
   echo "outside the function, \$var = ".$var. "<br />";

   #-----------------OUTPUT-------------------------------#
   #inside the function, $var =
   #inside the function, $var = contents 2
   #outside the function, $var = contents 1

   #If you want to create a global variable inside a function,
   #you simply use the global keyword (global $my_variable)

?>

Pass By Reference vs. Pass by Value
Let us consider a simple function increment()

<?php
   function increment($value, $amount = 1) {
      $value = $value +$amount;
   }

   $value = 10;
   increment($value);
   echo $value    # 10 - no change

  #-----------------------------Solution-------------------------#

  function increment(&$value, $amount = 1) {
     $value = $value +$amount;
  }

  $a = 10;
  echo $a;   #10
  increment($a);
  echo $a;  #11

  #Explanation:
  #-------------by value -----------------------#
  #If you pass by value, a new variable is created containing the
  #value passed in. It is a copy of the original. Modifying this new
  #variable does not change the original value.

  #----by reference-----------------------------#
  #Instead of creating a new variable, the function receives a
  #reference to the original variable.This reference has a variable
  #name starting with a $ sign and can be used like any other
  #variable. Modifying this reference variable affects the original
  #variable.
  #You specify a pass by reference parameter by using an ampersand(&)
  #before the parameter name in the function definition.
?>

Using The return keyword:

The keyword return ends the execution of a function. Execution of a function ends either after all statements have been executed or the return keyword is used. Consider this example:

<?php
    function test_return() {
       echo "This statement will be executed";
       return;
       echo "This statement will never be executed";
    }
    #Calling the above function will cause the first echo
    #statement to be executed and not the second one!
?>

The above example is obviously not the best way to use return keyword. Normally, you want to use it while checking for some conditions being met or not. Let us see a simple example here:

<?php
    function larger( $x, $y ) {
       if ((!isset($x)) || (!isset($y))) {
            echo "This function requires two numbers.";
            return;
       }
       if ($x>=$y) {
           echo $x."<br/">;
       } else {
           echo $y."<br/">;
       }
   }
   #testing the function
   $a = 1;
   $b = 2.5;
   $c = 1.9;
   larger($a, $b);
   larger($c, $a);
   larger($d, $a);
   #The output is as follows:
   2.5
   1.9
   This function requires two numbers

?>

Returning values from functions
You can simply return values directly from functions as follows:

<?php
   #modified version of larger that use return
   #instead of echo to return the value
   function larger ($x, $y) {
      if ((!isset($x)) || {!isset($y))) {
         return false;
      } else if ($x>=$y) {
         return $x;
      } else {
         return $y;
      }
   }
   #--------------sample test code--------------#
   $a = 1; $b = 2.5; $c = 1.9;
   echo larger($a, $b).’<br />’;
   echo larger($c, $a).’<br />’;
   echo larger($d, $a).’<br />’;

   2.5
   1.9
   #--------------------------------------------#
?>

Implementing Recursion in PHP
Recursion is supported in PHP. A recursive function is a function that calls itself. They are more useful when navigating dynamic data structures such as linked lists and trees. Example:

<?php
   #----------recursive approach-------------#
   function reverse_r($str) {
      if (strlen($str)>0) {
         reverse_r(substr($str, 1));
      }
      echo substr($str, 0, 1);
      return;
   }

   #------------iterative approach-----------#
   function reverse_i($str) {
       for ($i=1; $i<=strlen($str); $i++) {
           echo substr($str, -$i, 1);
       }
       return;
   }

    reverse_r('Hello');
    reverse_i('Hello');

    #calling reverse_r('Hello') will call itself a number of times,
    #with the following parameters:

    reverse_r(‘ello’);
    reverse_r(‘llo’);
    reverse_r(‘lo’);
    reverse_r(‘o’);
    reverse_r(‘’);

?>

The above functions  do the same thing but using recursive and iterative approaches respectively.
With each iterative call in the first function, the length of the string is tested. When you reach the end where strlen($string) == 0, the test fails. One issue with recursion is the memory use. It is up to you to decide which approach fits your taste.

As I end this post, I would like to direct you to PHP documentations where you can find out more. Thanks for stopping by and I hope you found some useful information here. If you have any questions, please let me know through the comments section. If you spot any errors, please let me know as well.