Tag Archives: scripts

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 !

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!

The Big Questions That I ask Myself

Hello! I have decided to step a side today and post something outside programming. I have always fought the urges to act robotic by reminding myself that after all is said and done, I am indeed, a human being who has questions. I laugh really hard when tickled. I cry when hurt. I bleed when pricked. Most often, my questions never get answered.

life-big-questions

Today some people are celebrating Easter – and so “Happy Easter”. I say ‘some’ because there are those who don’t do it.

One of the biggest questions I have started asking myself is “what really happen to us when we die” and immediately after that question comes? “where do we really come from?”. Believe it or not, every time I hear people talk about the absence of a higher power, I don’t give them a dead ear – instead, I listen to what they have to say and then ask them “but how did everything happen to be?” I know some Physics and I obviously won’t start an endless discussion here on how there had to be a force that started the process of life.

What if we were not named “human beings?” I don’t really know. You might say that I could use some serious scientific reading and whatnot and I agree. However, every day I step outside my house and look around me, I see things that I can’t even explain. I see trees and rocks. I hear birds of prey singing. I am not blind to the fact that there is more to life than just what I can and cannot see.

Consider a rich guy who has worked so hard to be where he is today. The fact is that he has a right to drive the most expensive car as he pleases. He can live the best lifestyle(best here means he can buy whatever he wants). You can also look across the oceans or anywhere around the world and see poor children dying of hunger. The question is: can you really say the rich guy should take some of his money and help those poor kids? It would be a humane gesture but quite complicated. The reason is simple: you can argue for and against it. Most obviously he has a right to say no.

The other aspect of life is that perhaps if we worked a little harder, just an extra mile, we might feel satisfied with our lives. Make some extra dollars, live in a bigger house, make the best friends and have a perfect family. Most of us believe that we have to do all that in order to be happy. I don’t know about you but I would like to have a nice house and a car. Do I sound greedy? Perhaps but am not. Aren’t we advised to work really hard and earn stuff? What about those who have worked hard and yet they still cannot see success? Is it their fault? Are they lazy? Or maybe they don’t know how to define success!

I believe that most of us have focused so much on making a living, forgetting to make a life. Maybe we could have a fresh start by asking ourselves what we really want and need. We might be looking too far away instead of looking closer. Inside. The day we start to understand what we can do with what we already have, we will be happier than ever. It is not about having a lot of friends. It is about appreciating what I already have. Showing them that I care. Being human. It is not really hard. Start small.

I am going to stop here. Thank you for reading. I hope you have a good day. See you soon and you are welcome to leave a comment below this post. Always remember that it is not much to do with where we have come from, rather, it is where we are headed in this life. Stay safe and strong.

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 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!

Programming With Google Maps APIs – Part II

Hi! First of all, thank you for stopping by. It gives me strength to keep sharing what I like because I know it is all worth the effort. That being said, today, I am going to expand on what I did on Google Maps API part I by adding more features to our map. Last time, our map.js file has the following 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
        };
        var map = new google.maps.Map(mapDiv, options);
    };
})();

Controlling The User Interface

  • disableDefaultUI – setting this property to true disables the default user interface. This further means the default zoom control and the map type chooser will not be displayed. Even if you disable the default user interface, you can still enable these controls individually. The default value is false. Example:
.
.
var options = {
   center: new google.maps.LatLng(37.09, -95.71),
   zoom : 8,
   mapTypeId : google.maps.MapTypeId.ROADMAP,
   disableDefaultUI : true
   //Alternatively, you can seperately enable or disable:
   //mapTypeControl: true
   //zoom
};
.
.

Before disabling the default user interface, the map looked like this:
google-maps-api-roadmap
After disabling it, you will see something like this:

google-maps-api-disableui
As you can see, the rectangles represent the original position of our default user interfaces.

mapTypeControlOption

In a case where you decide to have mapTypeControl visible, then mapTypeControlOption controls how it will be displayed. It can look different depending on circumstances or your own decisions to place it where you want. One good thing also is that you can define what map types you would like the user to choose from. This property takes an object of type google.maps.MapTypeControlOptions as its value. It has three properties:

  1. style
  2. position
  3. mapTypeIds

As you might have guessed, while using mapTypeControlOptions, you must always remember to set mapTypeControl to true. 

Style

This property determines the appearance of the control. The values you can choose from reside in the google.maps.MapTypeControlStyle object. The choices are:

  1. DEFAULT – the look will vary depending on the window size and maybe other factors. If the map is big enough, you get a horizontal bar displayed, otherwise, a drop-down menu will be shown.
  2. HORIZONTAL_BAR – this displays the horizontal bar!
  3. DROPDOWN_MENU – displays a drop-down list to either save space or some other reason!

Code Example:

(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
           }
        };
        var map = new google.maps.Map(mapDiv, options);
    };
})();

Position

As you might have noticed, the default position of this control is in the upper-right corner. You can easily define it to appear somewhere beside the upper-right corner. To do that, you will need to use the google.maps.ControlPosition class. This class has several predefined positions you can choose from: BOTTOM, BOTTOM_LEFT, BOTTOM_RIGHTLEFT, RIGHT, TOP, TOP_LEFT, TOP_RIGHT.

Code Example: Style: DROPDOWN_MENU, Position: TOP

(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
            }
        };
        var map = new google.maps.Map(mapDiv, options);
    };
})();

The outcome is:

google-maps-api-position

mapTypeIds

You use this property to control which map type to display. It takes an array of available MapType controls you want to use. The code below shows how to add it to our map example:

(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);
    };
})();

The final map now has a drop-down menu with a list of two MapTypeIds: ROADMAP and SATELLITE. Let us finish this post with a look!

final-google-map-api
I am going to stop here for today because I don’t want to make this post too long. So, I want to wrap up by saying congratulations for keeping up with me. Next time I will do some work on navigationControl and more! Thanks for stopping by and if you liked this post, please drop me a line and share it online! See you soon. If you have questions, please ask me!

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.

Regular Expressions – Data Validation In PHP

Hi! I am back from a serious headache and today am going to talk about regular expressions. The idea is to validate data submitted by the users of our online store. This will help us stop taking in invalid emails, or stuff like that. Also, using a new page created for feedback submission, we would like to send the message to respective departments depending on which  words our customers mention in their messages. Let us get started.

Here is my feedback page:

feedbackone

Basically, we don’t want crazy people submitting fake data just to annoy us and to avoid that, we use regular expression. This is a huge subject and I will not exhaust it, instead, I will touch on the basics so that you can go out there for more details.

postfeedback.php file:

<?php
 #Here I define some variables and then check to make sure
 #that they are set in the _POST array.
 $name = '';
 $email = '';
 $feedback = '';

 if(isset($_POST['name'])){
   $name = trim($_POST['name']); //use addslashes
 }
 if(isset($_POST['email'])){
   $email = trim($_POST['email']); //use addslashes
 }
 if(isset($_POST['feedback'])){
   $feedback = trim($_POST['feedback']); //use addslashes
 }

 #This will return an array of two items (an email is separated
 #by an '@' symbol and so the two sides are stored in our array
 $email_array = explode('@', $email);
?>

From the above code, you might have noticed certain new things: trim, addslashes and explode. When trying to store data in a database, you want to do some clean-up to remove any dangerous characters which might be interpreted by the database as commands. To eliminate such uncertainties, you use trim() and addslashes(). explode breaks the string given using the delimiter (‘@’) given and stores the results in an array.

<?php
  #my intention here was to put together some feedback and then email
  #them to the respective departments. So, let us get some variables
  #ready here:
  $toaddress = 'feedback@crazystore.com'; //default
  if(strstr($feedback, 'shop')){    //if 'shop' is in $feedback
      $toaddress = 'retails@crazystore.com';
  }else if(strstr($feedback, 'delivery')){ //if 'delivery' is in..
      $toaddress = 'fulfilment@crazystore.com';
  }else if(strstr($feedback, 'bill')){
      $toaddress = 'accounts@crazystore.com';
  }
  #
  #Even more variables here.
  if(strlen($email) < 6){    //strlen() returns length of string
     echo 'That email address is invalid';
     exit;
  }

  $subject = 'feedback from website';

  $mailcontent = 'Customer name: '.$name .'\n'.
                 'Customer email: '.$email. '\n'.
                 'Customer comments:\n '.$feedback.'\n';

  $fromaddress = 'From: webserver@crazystore.com';

  //invoke mail() function to send the email
   mail($toaddress, $subject, $mailcontent, $fromaddress); //use mail()

?>

As shown above, you might have thought to yourself that there might be better ways to doing the validation! You are right and it is always good to try out different approaches before settling on one.

Other String Manipulation functions:

<?php
   #-------------------------------------------------#
   strstr(haystack, needle); #case sensitive
   strchr();                 #find character match
   strrchr(haystack, needle);#from the end
   stristr(haystack, needle); #not case sensitive

   strpos(haystack, needle)  #returns position (numerical)
   strrpos(haystack, needle) #returns position of
                             #the last occurrence of the needle

   $sample = 'Hello world';
   strpos($sample, 'o');    #returns 4
   strpos($sample, 'o', 5); #returns 7 (3rd param is the starting point)

   #Alternatively:
   $result = strpos($sample, 'H');
   if($result === false){
     echo 'Not found';
   }else{
     echo 'Found at position: '.$result;
   }
?>

Let us assume your customers were really outraged by your service and they just unleashed really mean feedback. To protect your employees, you want to replace every cuss word with some other word. Let us do that!

 <?php
  #--------------------string replacing ---------------------------#
  $offcolor = array('fr***', 'nkdhs', 'k*-^', 'cuss');

  #Now we have our array of cuss words to replace; ($offcolor)
  #So, let us use str_replace() function to achieve this goal
  $feedback = str_replace($offcolor, '%!&@', $feedback);

  #What about substrings? Here is how to replace substrings
  #we have a $test string, we then replace whatever is at position
  # indicated by the 3rd parameter (-1) with 'X'
  substr_replace(string, replacement, start) #replaces a substring
  $test = substr_replace($test, 'X', -1);

  #More string manipulation functions and examples:
  $test = 'Your customers are the best in the world';
  substr($test, 1); //our customers are the best in the world
  substr($test, -10); // the world
  substr($test, 0, 4); // Your
  substr($test, -13); //returns between 4th
                      // character and 13th character-to-last

  #----------------------------------------------------#
  strcmp(str1, str2);     #compare strings
  strcasecmp(str1, str2); #not case sensitive
  strnatcmp(str1, str2);  #case-sensitive
  strncasecmp(str1, str2, len); #not case-sensitive

  #------------------------------------------------------#
 ?>

So far, we have not really used any regular expression functions yet!
I am going to make this as simple as possible to avoid confusion because Regular Expressions are not very easy to understand yet they are so useful!

<?php
   #Regular Expressions - Smart Form
   [a-zA-Z] #both lower and uppercase letters of alphabets
   [a-z]    #only lower-case alphabetical letters
   [aeiou]  #only vowels
   [^a-z]   #cannot be a member of a set

   [[:alnum:]] #------ Alphanumeric characters
   [[:alpha:]] #------ Alphabetic characters
   [[:lower:]] #------ Lowercase letters
   [[:upper:]] #------ Uppercase letters
   [[:digit:]] #------ Decimal digits
   [[:xdigit:]]#------ Hexadecimal digits
   [[:punct:]] #------ Punctuation
   [[:blank:]] #------ Tabs and spaces
   [[:space:]] #------ Whitespace characters
   [[:cntrl:]] #------ Control characters
   [[:print:]] #------ All printable characters
   [[:graph:]] #------ All printable characters except for space

   #repetitions
   [[:alnum:]]+ #------ means --> at least one alphanumeric character

   #subexpressions
   (very)*large ------ matches: 'large', 'very large',son on

   #counted subexpressions
   (very){1, 3} ------ matches -> 'very', 'very very', 'very very very';

   ^crazy #----- matches 'crazy' at the start of a string
   com$   #----- matches 'com' at the end of a string
   ^[a-b]$ #---- matches a single character from a and z

    com|edu|net #----- matches com, edu and net
?>

Let us take a quick look at what characters mean when used outside and inside the brackets:

<?php
#-----------------Outside brackets------------------------|
 # Character | Meaning                      |
 #     \     | Escape character             |
 #     ^     | Match at start of string     |
 #     $     | Match at the end of string   |
 #     .     | Match any character except \n|
 #     |     | Start of branching (OR)      |
 #     (     | Start subpattern             |
 #     )     | End of subpattern            |
 #     *     | Repeat 0 or more times       |
 #     +     | Repeat 1 or more times       |
 #     {     | Start min/max quantifier     |
 #     }     | End min/max quantifier       |
 #     ?     | Mark a subpatter as optional |
 #----------------Inside brackets -------------------------|
 #     \     | Escape character             |
 #     ^     | NOT - if used in initial pos |
 #     -     | Specify character ranging    |
 #---------------------------------------------------------|

?>

We are almost done here. Now that we know some regular expressions, we should be able to use them to validate our data: particularly the email and the message- searching for keywords then determining where to send the message!

<?php
#we check if the $email passes the test here.This will probably
#not work for all kinds of emails.
if(preg_match('~^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]{2,4}$~i', $email)){
   echo '<p>That is not a valid email address!</p>'.
        '<p>Please try again by visiting the previous page.</p>';
   exit;
 }

 $toaddress = 'feedback@crazystore.com'; //default value
 #we are using the $feedback variable from the start of our post above

 if (preg_match(“shop|service|retail”, $feedback)){ #use | (OR)
    $toaddress = 'retail@crazystore.com';
 }else if(preg_match("deliver|fulfil", $feedback)){ #use | (OR)
    $toaddress = 'fulfilment@crazystore.com';
 }
 else if(preg_match(“bill|account”, $feedback)){    #use | (OR)
    $toaddress = 'accounts@crazystore.com';
 }

 #Always use string functions instead of regex here. This is
 #just an example to demonstrate that you can also use regex
 if(preg_match('bigcustomer\.com', $feedback)){
    $toaddress = 'owner@crazystore.com';
 }
  ?>

Finally, we will look at splitting strings using Regular Exp.

  <?php

    #Splitting strings using Regular expressions
    $address = “username@crazystore.com”;
    $arr = split (“\.|@”, $address);
    while (list($key, $value) = each ($arr)) {
       echo “<br />”.$value;
    }
    #Results ---------------------------------------
    #username
    #@
    #crazystore
    #.
    #com
    #-----------------------------------------------
  ?>

That is it for today. I hope you found this helpful in a way. If you have any questions, please let me know so that I can answer them. Next time we will tackle functions and code reuse. If you  have spotted any errors, please let me know through the comments section and I will really appreciate.

Storing Data Using Files in PHP – Shopping Cart

Hi! After adding some functionality to our shopping cart, I am going to do something different today: storage. Assuming we want to collect all the orders from customers and store them in a file somewhere for later use, we can easily create a file and write and read to and from it. I have altered the original look of our simple cart by adding a new input area for shipping address: Let us look at it now.

snapshot1

Adding that single input area is obviously not a big deal but if you have done any online shopping before, there is a good chance you were prompted to enter your shipping address! Now let us take a quick look at the results of submitting your order!

snapshot2

Simple enough, the Address information is now included in the summary! Everything looks great. Now, we both know that just displaying the summary of orders might not be the best way to get the job done – assuming you have a million orders or something. So, to solve this problem, we need to save the orders in a file. We can then retrieve the orders and process them before fulfilling them. So, using a new file, vieworders.php here is what I have done already:

snapshot3

Now we are not worried about anything getting lost because we can look into our file and fetch the orders. That is good. I know you might be asking, but is that the best way to do this kind of job? The answer is NO. Using plain text files is not the most efficient way and the reason why am using it here is to demonstrate why we will need to use a database management system for anything important! Let us look at how to write data into a file.


#from within store.php we add some new lines of code here
#writing data into files stored in my machine

<? php
  $fp = '';
  //create a folder in your directory (orders)
  $fp = fopen("C:\\orders\orders.txt", 'ab');
  flock($fp, LOCK_EX)       #lock the file - file cannot be shared
  if(!$fp){
    echo "<p><strong>Your order could not be completed at this time."
          ."Please try again later</strong></p></body></html>";
    exit;
  }
  else{
    //that means there is no error and we therefore
    //can write to a file

    $outputstring = $date." \t". $tiresqty." tires \t". $oilqty." oil\t"
                  .$sparksqty." spark plugs\t\$".$totalamount
                  ."\t". $address."<br />";

    fwrite($fp, $outputstring);  //write data to file
    flock($fp, LOCK_UN);         //release existing lock
    fclose($fp);                 //close the file!
  }
?>

That is all you need to write to a file. So what did we do here? A few things: first, create a variable $fp (file pointer) and then use PHP’s file open function (fopen()) which takes several parameters. First, the file path and then others. As you can see, I added ‘ab’ as the second param (a – (writing only) for appending to the end of existing content if any. If the file doesn’t exist, try to create it. b – (binary) differentiates between binary and text files – recommended for portability.

I then applied a lock to the file to disable sharing it. I then check to see if the file pointer exists, if not, then inform the customers politely that their order was not processed. Otherwise, go ahead and write their order to our file using fwrite() function. Then remove the lock and finally close the file.

Let us finally take a look at our vieworders.php file which we use to read data from our file as we process them in our parents’ garage!

<?php
    $fp = fopen("C:\\orders\\orders.txt", 'rb');
?>

<html>
   <head>
   <title>Crazy Auto Orders</title>
   <link rel="stylesheet" type="text/css" href="index.css" />
   </head>
   <body>
      <div class="container">
         <h1>Crazy Auto Store Inc </h1>
         <h2>Customer Orders: </h2>
         <?php
            if(!$fp){
              echo '<p><strong>No orders pending.'
              .'Please try again later</strong></p>';
             exit;
            }
            flock($fp, LOCK_SH);
            while (!feof($fp)){
               $order = fgets($fp, 999);
               echo $order. "<br />";
            }
           flock($fp, LOCK_UN);
           fclose($fp);
         ?>
       <p>Copyright 2013 &copy; Crazy Auto Store Inc </P>
     </div>
   </body>
</html>

Description:

Once again, on top of our file we create a file pointer variable $fp and use file open function fopen() passing in the path and a second param (‘rb’ – r (opens the file for reading from the beginning) and b – for binary differentiation – recommended by PHP developers!).

Just like before, we check to see if the pointer exists and if not, give the user a friendly message to try again later. If it exists, we use LOCK_SH to enable reading lock. The file can be shared with other readers. Using a while loop, we check to make sure that we have not reached the end of the file (feof – file end of file) and output the data one line at a time using fgets() function.

Last but not least, we release the lock and lastly close the file. That is all.

There are so many reasons why this is not the best approach and that is why database management systems were created. I will briefly mention a few:  The speed is affected if our files grow and so reading the data becomes a big challenge. Secondly, searching for a particular group of records is difficult. Another one could be a situation where more than one user is trying to access our file at once – concurrent access. This can become problematic even while using locking. It is hard to enforce different levels of access to data. Those are just a few and if you are interested in finding out more, I would recommend checking out the php documentations .

NOTE: This example does not include everything that file writing and reading entails. With that being said, there are a lot of information online on how to read and write files (functions and such) – this is just a small piece of it. I just touched on the tip of the iceberg here.

If you have any questions, spotted any errors or comments, please leave them below this post using the comments section. Thank you for stopping by and I hope you enjoyed building this shopping cart with me. See you soon!

Building A Shopping Cart – Part 2

Please Visit The Post’s New Location Simple Developer

Hi! I had promised to improve our simple shopping cart by adding some functionality to it. Today therefore, I have added a drop-down list to our web store so that customers can select an option describing where they found our store. It could be through television ads, phone directory, word of mouth or other sources. So, without much ado, am going to show you how our page will look like then share the php and html code.

crazy-php-html-code

As you can see above, you get a list of different sources. Now, in the next snapshot, I am going to show you another feature that I added to dynamically display a table which you can use to determine your shipping cost. I used a for loop to generate it. Cool!

store-image-php

You might have noticed something new in the above snapshot: the total costs and taxes inclusion. There is also the table shown by the arrow. Now, if you select an option from the drop-down, it will be displayed just below the total amount! Now let us take a look at the code.

php-code-image

Simply click on the above image for a closer view of the entire code. This code contains some pieces from the first Shopping Cart Part I and then the calculations and constants definition and usage.

Now let us take a quick look at how selections are used in html markup. It is easier than you might think:

referral-code-selection

What I did here was to simply add a <div> tag just below what I had in my first post. I added to the same file! Again, please click on the image to see the code clearly. Now let us take a look at the switch statement that utilizes the values returned by the above selection:

switch-statement-code

As you can see, using a switch statement is much better than using a lot of if else statements. I went a head and added the code to dynamically generate the table that shows the distance ::: shipping information. I used a for loop! Please click on the image to see a clear version of the image. I apologize for that!

That should do it for today! I know it is not that complicated but I thought it was good for me to start small and then move on to intermediate levels. I really liked reading through the PHP documentations and I think everyone trying to learn how to do scripting using PHP should give it a substantial amount of time. Thanks for visiting and if you have any questions or see any errors, please don’t hesitate to drop me a line using the comments! I will really like to connect with you!

Take care and see you soon!