Nov13

Google Maps Tutorial, Part 1: A Simple Map

at 7.40pm

Google Maps provides an excellent and powerful mapping solution with some complex features whilst maintaining high usability and a fast user interface. Through the JavaScript API Google have exposed a large portion of the functionality of their maps and data for use in websites and web applications (all of which must comply with their Terms of Use). It may sound difficult but it doesn’t have to be. In fact it is quite easy to produce some quite sophisticated behaviour with relatively little code.

In this series I hope to demonstrate how to build several increasingly complex mapping applications that could have practical uses in a website or application. At the end of each part I will give some ideas for how I think the example could be adapted to a real-life situation. As the examples get more advanced the number of possible applications will increase but so also will the amount of work required to change my code to achieve a specific purpose. I hope to demonstrate to tools and techniques you might need in making these changes. So, of we go!

In the first example I will show how to create a very simple map that can be displayed on a web page with a pin marking a particular point.

Prerequisites

For this part of the tutorial you will need a basic knowledge of HTML, CSS and JavaScript and some web space but not a lot else. You won’t even need any server-side scripting!

Step 1 - Getting a Google API Key

The first step is to obtain a Google API key. This will be required for any Google Maps application that you create and is tied to the domain from which the requests to the API are made. This may mean that you need separate API keys if your development domain is different to your live domain. This is not really a problem however as it is really simple to obtain a key.

Simply go to the sign-up page, read the Terms of Use (or more likely the summary as the full document is rather dull), check the box confirming you understand the blurb, enter your site URL and generate the key.

The next page will give you your key (a really long string of letters and numbers) as well as a snippet of code to get you started. Ignore this for now as we will be recreating something similar in a moment but with more explanation along the way. If you forget your key, don’t worry as following this procedure again should result in exactly the same key as long as domain is the same.

Step 2 - Displaying a Map

Okay, that’s the boring bit over. Now for something more interesting - let’s get a map on the screen. Firstly create a simple (X)HTML file (I’ll assume you know how to do this) and add an empty div element to the body as below.

<body>
   <div id="map"></div>
</body>

Make sure you don’t forget the id attribute as we’ll be using it in a moment.

Next, you’ll need to load in the API file. Add the following code to the HTML head tag replacing the key for this site with the key for yours.

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAv5cMnGZ5zeb1SlRlW91GkBStkTdrHPl7LrMl77V0klQxRUcDRBSy-WJLTWS8O7_n3a6dBXQ0xp7Jqg" type="text/javascript"></script>

Now that’s the preparation done so we can add the map itself. Create a new JavaScript file called map.js in a directory called js and add the lines

function load() {
   if (GBrowserIsCompatible()) {
      var map = new GMap2(document.getElementById("map"));
      map.setCenter(new GLatLng(0, 0), 1);
   }
}
 
window.onload = load;
window.onunload = GUnload;

So what’s going on here? Well the load() function is the bit doing all the magic and is creating a new Google Map object (if the browser can display it) and attaching it to our map div. The centre point of the map is set to longitude 0 and latitude 0 which is the point on the equator on the Prime Meridian (which runs through Greenwich). The last argument sets the zoom level of the map which is set to the minimum value to display a world map. We will change this centre point and zoom level later. We attach this function to execute when the page is loaded so the map gets displayed as soon as the user visits the page.

The GUnload() call destroys any Google JavaScript objects left around when the user navigates away from the page. This is important as in some browsers those objects would stay in memory until the whole browser is closed unless explicitly destroyed.

Okay, just a few more bits left to get the map on the screen. Firstly you will need to load in your newly created JavaScript file into the HTML page.

<script src="js/map.js" type="text/javascript"></script>

You may be wondering why I’ve separated the JavaScript into another file whereas the Google example has it all in the one HTML file. It is good practice to separate markup (HTML), behaviour (JavaScript) and presentation (CSS) into different ‘layers’ or groups of files as it helps separate your code into more maintainable and readable chunks. It also means that browsers can cache your JavaScript and CSS files independently and therefore decrease loading times. For a further discussion into these techniques see Understanding Progressive Enhancement from A List Apart or the Wikipedia article on progressive enhancement.

We need to set the size of the map on the page otherwise it will not display properly. To do this, create a CSS file called styles.css in a new directory called css. Insert the following code.

#map {
   width: 500px;
   height: 300px;
}

Now link the style to your HTML page by adding

<link href="css/styles.css" type="text/css" rel="stylesheet" media="screen, projection" />

to the head of the document.

If you now open your HTML page in a web browser you should see a lovely world map displayed on the page.

Step 3 - Centering the Map

That’s the hard work done now lets change where the map is focused. Google Maps requires location information to be passed to it in terms of its longitude and latitude. Unless you think in these terms you will need to convert an address, location or postcode into this format in order to use it in a Google Maps application. The process of converting an address or other human readable location into its longitude and latitude is called geocoding. We will discuss this topic in a later tutorial but for now we will use the Google’s own Maps application to do the work for us.

Go to Google Maps and search for the location you want to be at the centre of your map. Check that the map is centred around the correct point and that the marker is pointing to the right place. Now, right click on the marker and select the option ‘Clear search results’. The marker will disappear but the map should stay centered on the same place. Now go to the top right and click ‘Send’. A box will pop up containing a link. The longitude and latitude are in the ‘ll’ fragment of the url. This is the data you will need.

For example, I searched for Downing Street, London and the URL I have is

http://maps.google.co.uk/maps?hl=en&ie=UTF8&ll=51.503093,-0.128124
&spn=0.010205,0.027895&z=16

I have highlighted the relevent fragment. In this case the longitude is 51.503093 and the latitude is -0.128124.

With these values we need to add a few lines to the beginning of the map.js file.

var latitude = -0.128124.;
var longitude = 51.503093;
var zoom = 13;

Now alter the script that sets the centre location to the following.

var location = new GLatLng(latitude, longitude);
map.setCenter(location, zoom);

Now when you load the map it should be centred around the point you specified.

Step 4 - Adding a Marker

Adding a marker is very simple. Just add the following code to your JavaScript file at the end of the load() function. This will add a marker at the same location as the map is centered.

var marker = new GMarker(location);
map.addOverlay(marker);

Load up your map in your browser and you should see you map focused on and marking the location you specified. Magic.

As you can see the amount of code involved in this is quite small considering the visual complexity of the effect. The Google Maps API allows you to tell it what you want it to do in simple terms while it does all the hard work in the background.

This example map would be perfect on a company website to show the location of an office or shop or simply to point out a landmark or a place you have visited. A picture (or map) is worth a thousand words! In future tutorials we will look at more advanced techniques like information bubbles, multiple points, interacting with the server and geocoding.

Nov05

Upgrading to Ubuntu Intrepid Ibex

at 6.53pm

The latest version of Ubuntu, 8.10 (also known as Intrepid Ibex), has been out for a few days now and I was waiting for the update manager to tell me the upgrade was available. When this didn’t happen I tried to find out why.

It turns out that version 8.04 (Hardy Heron) was what Ubuntu call a Long Term Support release which is why you often see 8.04 followed by the acronym LTS. For this reason, by default, Hardy Heron will not by default offer the new version as an upgrade in the update manager. This can be fixed of course and here’s how:

  1. Go to the Software Sources item in the menus:
    System -> Administration -> Software Sources
    
  2. Now select the Updates tab and change the option at the bottom called ‘Release upgrade’ from ‘Long term support releases only’ to ‘Normal releases’ and then accept the changes.
  3. Now go back to the Update Manager in
    System -> Administration -> Update Manager

    and the option to upgrade will be present and you can upgrade as normal. Simple.

Nov02

.local Domains on Ubuntu Desktop

at 7.43pm

My web development environment usually consists of an Ubuntu machine set up with a LAMP stack using Apache virtual hosts and a simple DNS setup. I tend to use a .local extension to the domains to make them easy to access and to compare to their online counterparts. For example I use oneangrydwarf.local for the testing environment for this site.

The problem comes when I set this up on an Ubuntu Desktop installation (as opposed to an Ubuntu Server installation) which I prefer simply for ease of use. Unfortunately a program called Avahi stands in my way by hijacking the top-level domain and overriding the DNS records. Apparently Avahi is used for “service discovery on a local network” and is an integral part of Ubuntu Desktop (attempting to remove it also removes the desktop environment) but personally I don’t need it and it gets in my way. For anybody else having this problem here’s how to fix it, firstly temporarily (if you need Avahi normally but just want a quick fix) and secondly a more permanent solution.

  1. Stop the Avahi daemon by typing
    sudo /etc/init.d/avahi-daemon stop

    This will only solve the problem until the server is rebooted as the process is integral to Ubuntu Desktop. Attempting to uninstall Avahi will also uninstall the Ubuntu Desktop.

  2. Tell Ubuntu to check the DNS server first by editing /etc/nsswitch.conf and changing the line that reads
    hosts:  files mdns4_minimal [NOTFOUND=return] dns mdns4

    to

    hosts: files dns mdns4_minimal [NOTFOUND=return] mdns4

    Now restart Avahi with the command

    sudo /etc/init.d/avahi-daemon restart

    See Avahi and dot-local addresses on Ubuntu Gutsy from The Fifth Wheel of andrewg for more details.

Posted in Ubuntu, Web | 1 Comment »
Oct20

Syntax Highlighting with Wordpress

at 7.43pm

No programming blog is complete without decent syntax highlighting so it seemed reasonable to expect there to already be a good plug-in available to provide the functionality I need. Sure enough, a quick search resulted in finding WP-Syntax. The plug-in is based on GeSHi which started as the syntax highlighter for phpBB and is now a fully independent project with support for most major languages.

As a demonstration (and a test) here’s some PHP:

public class Foo {
   public function __construct($bar) {
      echo 'Hello World!';
   {
}

and some CSS (with line numbers):

1
2
3
4
   .foo {
      color: #FFFFFF;
      height: 100px;
   }

I think that’s enough of a demonstration and promotion of the previously mentioned projects but expect to see some code related posts in the not-to-distant future.

Oct17

New Site Design

at 5.08pm

You may have noticed that I have just launched a new, improved site design. I decided on a new look in order to accomodate the changing direction of the site and my future plans for its content.

Before

Before

After

After

The first thing you might notice is the wider layout (see the before and after screenshots) which allows for both a wider reading area and more content in the sidebars (more on that in another post). The shorter header section is more streamlined too which also gives over more space to content. The emphasis on content is also echoed by the new location of the sidebars on the right. Content is king!

So, what will all this space be used for? Well I am hoping to keep the content updated much more frequently and with much more of a technical emphasis. I have been working as a professional web developer for over a year now and it’s time I started documenting some of my experiences. Maybe somebody somewhere might find it useful as well as it being a good record for me in the future.

Any feedback or bug reports on the new design are more than welcome. I know its far from perfect but I hope to iron out all the major problems over the next few weeks.

Jun06

In Response to ‘Where did all the PHP developers go?’

at 7.55am

In response to this post by Leonid Mamchenkov about the lack of good PHP developers in Cyprus I thought I would share my thoughts about the experience that the company I work for has had in recruiting a PHP developer to work on our web applications in the UK. We have had great difficulty targeting the quality of developer that we need for our large scale business applications and have come to the conclusion that it’s partly due to the lack of good web developers in the market. We have had a wide variety of applicants but very few have been anywhere near the quality we have been looking for (so far).

There are a lot of ’script kiddies’ around who claim to be advanced developers just because they have made a few websites that use a scripting language and a database. Very few seem to have any knowledge of MVC, frameworks, design patterns, version control or even fundamental concepts like OO and basic commenting and documentation techniques. Like Leonid we would settle for even a few of these skills.

I don’t believe that these problems are necessarily specific to PHP (I may be wrong) but probably the web development industry in general. One of the main problems is the lack of respect for web development by computer scientists and academics. Coming from a university that teaches what I would call pure computer science (by that I mean concepts, thought processes, theory and techniques rather than any particular technologies or programming in a specific language) I was staggered to find, at the end of my degree, that out of my hundred or so fellow students I was one of the only ones going into the web development industry as a career. There were some who had an interest but it was always considered a secondary skill which would be a bonus feature on their CV rather than their main selling point. Web development, particularly with scripting languages (including PHP, Ruby and Python), is not considered to be a ‘proper’ profession for someone with that level of qualification. Java is the exception to the rule as it seems to be the language of choice for many universities to teach the principles of programming and is therefore accepted by its students as an appropriate tool on which to base their career path.

There are quite a few universities that teach the more practical aspects of computer science and some even specifically web development but our experience is that many of their graduates have learnt either .Net or Java but nothing else. The former often do not seem to even be aware of programming tools outside of the safe and cosy Microsoft ecosystem. I am not criticising these universities or the languages that they teach but I do feel that other languages and tools are under-represented in academia.

In response to Leonid’s criticisms of PHP I do agree that one of its problems is its ease of use and the fact that it is newbie safe. There is no doubt that this does attract a lot of beginners to the community. However with the right training and experience there is no reason why these beginners can’t become great programmers, even if they do stick to PHP.

I also think it is unfair to say that it is an ‘ugly language’ although it most certainly can be if not used well. It certainly can’t be criticised for not being ‘convenient’ especially when used with PEAR or a good framework. In my opinion Java is more of an ugly language to read and certainly some of it’s libraries have been forced into its ‘everything is an object’ approach even where it is not appropriate. I admit that PHP is somewhat inconsistent in its function naming and the combination of native functions, procedural code and objects in its documentation but this is becoming easier to ignore with projects such as PEAR and the Zend Framework. PHP is a rapidly maturing language which in the last few years has become a very realistic candidate for developing large scale applications. Yes, it has its weaknesses and can be used to write horrible code but any language can, if put in the wrong hands. The problem here is not PHP itself but the type of people who claim to be good at it.

I think as a community there needs to be more work done to raise the profile of PHP, and web scripting in general, within academia. There are a lot of misconceptions about web scripting and its applicability to large projects and computer science theory. The industry is very young and its power only just being demonstrated. In order to keep moving forward we need more benchmarks and qualifications for developers so we can really separate the excellent and the good from the truly awful. Less time spent searching for the people our projects need is more time creating new and innovative applications.

Posted in Web | 3 Comments »
Mar31

IE7 Fixes and Other Progress

at 11.40am

Although it looks like I haven’t done anything for a while, I have in fact been quite busy. I’ve fixed a few CSS bugs I found in Internet Explorer 7, particularly on the photos pages. It seems that IE7 really isn’t that much more standards compliant than IE6 (a discussion point for another time) - surprise surprise Microsoft! Behind the scenes I’ve also been working on the commenting system for photos. It’s taking longer than I’d hoped, probably because I’m a perfectionist! I want the comment system to work in a similar way to the Wordpress system as that just makes sense to me. The Gallery comments module on the other hand has different ideas so I’m going to have to rewrite it somewhat to bend it to my will.

In other news, I’ve got a job! From September (after I’ve graduated and been slumming it around Europe for a bit) I’ll be working for a small company called Protec Innovations Ltd as a Web Application Developer. Currently lots of the details are still in discussion but I’ll post more info when I get it.

Posted in Web | No Comments »
Mar21

Photo Downloads

at 11.51pm

It’s time to celebrate! You can now download the full-size versions of photos. This feature is useful for anyone that wants to print the photos at any decent quality. One problem with Facebook (which a lot of my friends use to share photos) is that although you can save the photos on it, if you try and print them, they look crap. If you’re really interested then go and try it for yourself. Everyone else just take my word for it!

Posted in Web | No Comments »
Mar21

Photos (and Stuff)

at 4.28pm

Time for an update I think. I’ve been working hard on getting things a bit more how I want them and particularly on the photos section. I’ve uploaded and partially set up my theme for Wordpress, it is not finished yet but I think the site is pretty much still usable and the bits that do not work properly will be fixed soon.

The photos section is now looking pretty good and has basic functionality, you still can’t comment on photos or download the full-size versions but I’ll do that soon. To celebrate I’ve added an album of photos from New Year. Don’t worry I’ll be adding some more soon. In fact that’s the next thing on my todo list.

Just a few other points. You may notice that the menu at the top looks a bit odd. That’s because it’s not finished yet and as I add the other sections of the site it’ll start to look a bit more normal. Also there’s the ‘Weekly Artists’ section on the front page sidebar, which is thanks to another plug-in for Wordpress called Scrobbler. This uses a clever bit of AJAX to pull the information from a feed on my Last.fm page and stick on my site. Lovely!

Posted in Web | 2 Comments »
Mar19

First Steps

at 10.44pm

So, where to begin? Well the first thing to do is obviously to get Wordpress and Gallery 2 all set up and installed. Clearly the Wordpress installation went OK otherwise you wouldn’t be reading this. I will be integrating Gallery 2 into Wordpress to make the whole thing look like one site with the help of the rather useful and aptly named WPG2 (Wordpress Gallery 2) plug-in.

WPG2 in action!After installing Gallery 2 and downloading the required plug-ins for WPG2 to work (really easy to do with Gallery’s awesome plug-in manager) and some mod-rewrite magic, the path /photos now points to my embedded galleries. Time for another coffee…

Posted in Web | No Comments »

Web

PHP, MySQL, Apache, Linux, JavaScript, CSS and other web technologies.