Category Archives: Twitter API Programming

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!

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!

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!

FREE Book Download From Amazon (True Story)

Hello! I apologize for taking a little too long to post something! I have been doing certain things (other side projects) and following the progress of my country’s election [Kenya]. I hope everything is going good for you.

Today(starting Wednesday 3/6/2013), I am going to give my book away for FREE on Amazon. I have been waiting for this for a while now and I figured I should do it now and then extend my reach to other platforms like smashwords and Barnes and Noble. So here is what I am going to do:

If you own a kindle tablet, an android tablet, a smart phone, or any other type of gadget that accepts applications, then you are all set. Oh, wait, I have to also mention the fact that you need an appetite for true stories (like the nearly 10,000 others who have read the book already). I normally tell people to read the reviews first: like these two I grabbed from Amazon:

my-free-book-giveaway

You can also read more reviews by visiting my Amazon page before making your decision.

When you are done reading the reviews, you can grab your copy by downloading it to your device (including your computer if you don’t own the above mentioned tablets). Here is the snapshot of the book:

my-life-sentences-free-book

You can download the book by clicking on the above image or using this download link:

Download My Life Sentences – A True Story for Free Today

If you run into problems while trying to do this, please notify me and I will be more than happy to help you. If you would like to share a link on Facebook or any other social media that you use, please know that I will truly appreciate. That is all am going to say for today. I hope you find this book inspiring.

Thank you!

A simple python script to find bloggers on twitter

Hi! I know you are probably asking what the heck is he doing? I will be honest here, this is not a tutorial but a simple quick fix to a problem I faced last night. I was invited by an author to take part in the so called blog hopping. One of the requirements was to find at least five other authors with blogs to join the adventure. So, I asked myself, how could I make this as much fun as possible and learn something at the same time?

So today, I packed my gear and headed to a nearby coffee shop to create something. In a few lines later (I had to wait for one hour after I exceeded 150 rate limit on Twitter), I had put together a simple script that helped me reduce the pain of searching for potential bloggers(who are authors).

Assumptions:

  1. I assumed that Twitter users who mentioned the word ‘authors’ were likely to be authors themselves or review books through their blogs.
  2. Secondly, I made a partial assumption that most twitter users who talk about authors had their ‘website’ part of their profiles filled. So, I could easily get their blog addresses. If they didn’t have anything listed, I just moved on.

Now let us take a closer look at the code: part 1

#Let us get our first part out of the way here.
#I am using python, so let us import the needed libraries
import json
import urllib2
url = 'http://search.twitter.com/search.json?q=authors' #link
user_ids = []                            #list to store user_ids
#define our first of the two functions to be used
def get_user_ids():
    data = urllib2.urlopen(url)   #make the call to twitter
    js   = json.load(data)        #parse using json.load() method
    i = 0
    while i < len(js['results']): #you need to know what is returned
        user_ids.append(js['results'][i]['from_user_id_str'].encode('utf-8'))
        i += 1
    return user_ids
#Explanation:
#after getting data from twitter, I iterate through the 'results'
#and grab the from_user_id_str - whoever mentioned the word 'authors'
#I find this more convenient than using a screen name.
#I then add that value to the user_ids list for later use.
#finally, I return the list
print 'Move to the next level now!'

In the second part of this post, I want us to look at the second function definition that will complete our script. Yeah, it is really short!

#Within the same file, we will continue our script!

def get_blogs():
    i = 0
    user_urls = []            #define a list to store the urls
    user_ids = get_user_ids() #get the user_ids and store for use
    while i < len(user_ids):
        url = 'http://api.twitter.com/1/statuses/user_timeline/'+
               user_ids[i] + '.json'
        data = urllib2.urlopen(url) #make the call
        js = json.load(data)
        if js[0]['user']['url'] is not None:
            user_urls.append(js[0]['user']['url'])
        i += 1
    return user_urls

Can you believe we have finished the script? Well, we have reached the end. I know you are saying: show me! And to that question, an answer is worth it – in a snapshot! Let us run this code by doing the following:

#Call the function and store the links in a list.
user_links = get_blogs()
for link in user_links:
    print link

#That is all we need to get everything from the list!!

And ….. here is what I got when I executed that code!

finalbloglinks
As you can see, you get easy to read urls that you can open using your browser of choice! One thing you might notice is that not all of the links are either wordpress or blogspot. You can go ahead and improve the script to grab only those links that have either wordpress or blogspot in them. You can view the image clearly by clicking on it!

So why is this a better idea than searching on Google for individual bloggers? Simple; you get a ton of links that you can scan through using your browser, sending requests to their owners and saving yourself some time!

As far as time is concerned, this script makes several API calls during the execution and you will notice a slight delay in completion. Also, you might hit the required rate limit (150) without knowing because you are making several requests per execution. That being said, I still had fun doing this and I have sent numerous requests for blog hops within a short time!

Summary:

I make an API call to Twitter servers to search for the word ‘authors’. Then saved the user_ids of the people who mentioned that word. We then use their user_ids to make another API call to their timelines. While doing that, we grab their url (the property that is part of the Twitter profile). If the url is missing, we ignore, otherwise, we store it in a new list. We finally iterate through the list and print the links out in a clean manner then visit them individually! That is it! I hope you had fun reading through this post. Got questions? Ask them! Thank you.

Free Software Developer Training – 90 Days

Please visit the new location of this post at Simple Developer Site. Thank You!

Hi! Today, I have decided to take a brief detour from my regular posts and share something so good with you. I think it does not hurt to take a breather from all the code and documentations(this is not to say that you should stop reading your docs).

So what do I have in store for you today? Sit back and relax, oh wait, am not going to keep you waiting for long. I will jump right in and give you the information you will need to grab a FREE 90 Day Software Training . This is not a typical training course, it is kick-ass (did I just say that?) and every developer would do anything to get access to it. You get a huge library of step by step training videos (very high quality and corporate level) that you would otherwise pay lots of money for. To make everything easier, I have put together a YouTube video for you. It is easy to follow and it takes just 5 minutes of your time. I think it is totally worth it especially if you can get 90 days of free cutting edge training.

I should stop and let you watch the video already,  right? I hope you find this helpful and share it with others who are interested.

On a serious note, I hope you find this helpful and if you are already using these resources, please pass this video on to those who might need it and cannot afford to pay monthly fees. The only thing one needs is an email address from their college. You don’t need to enter your credit card information or anything that might look fishy. So, without much ado, please enjoy and see you soon.

Remember, if you have any questions, do not hesitate to ask through the comments section.

You can get some ground work done by clicking here and reading through my first tutorial on PHP scripting before we get to build a shopping cart!! I look forward to seeing you around!

Thank you for stopping by. Take care!

Victory is Yours – Going Public (github)

This happens to be my last post on this Programming With Twitter API journey. I do not feel sad because this is actually just the beginning! I will not stop here, I will keep making something better out of it. This has been a great adventure, very informing and fun. So, without much a do, I want to show you(if you have not done this before), how to make our code publicly accessible to interested people who want to read it and even use it for their own learning or applications. I am going straight to github – by the way this is not the only one, look for bitbucket or something that makes you happy.

github

So, once we are over at Github.com , we can grab a free account for now and then do some cosmetic setups and off we go. It is a simple process that should take you less than 5 minutes or ten at most. For easier commits, you should download github onto your machine then perform these two actions to set it up for usage:

#After installing github on your machine, you set up
#first the username, then the email by entering these
#commands onto your terminal

$ git config --global user.name "your user name here"
#sets the default name for use by git when you commit

$ git config --global user.email "your email"
#sets the default email for use by git when you commit

That will make your work so much easier because you will just publish new code without having to visit github website. Take a look at what I did here:

lastgithub

If you look keenly at the snapshot above, you will see how a typical page looks like once you have logged into your repository. Just below the page is a list of files that include an optional README. Finally, I would like to show you how opened files will look like on Github. It is a good skill to comment your code because you never know who will be reading it and most importantly, you yourself will be reading it a few years from now. It will be shameful not to understand your own code!

githubpage

So, there you have it. Every time you want to review your code, or improve it, you can do so without any worries of losing it. Github is your friend, always there for you when you need it. I hope you found this post useful and you will have your awesome scripts available on Github for others to read and even use.

You can easily access my repository on Github by visiting simpledeveloper .

Thanks and please subscribe for updates if you like what I do here.