Google Maps – Multiple Custom Markers

Recently I have been building a system that required some interaction with Google Maps in terms of creating multiple custom markers to a map. There are many different approaches to solving this problem but I thought I would share my particular twist on this in this post.

The first thing we want to do is ensure that we have the Google Maps API included in our page, using the following code:

 

Now we have the ability to use all the GoogleMaps functionality within our page we can start by creating our basic map.

Just as a quick note – the sensor=false bit on the end of our URL does pretty much what you would expect – tells GoogleMaps that we will not be using the built in sensor (that is present in almost all modern smart phones) to decide the maps location, as its not needed in this example.

The first thing we will do is define an array to hold all of our coordinates and also some types that can be used for markers – like this:

<script type="text/javascript">// <![CDATA[
//Initialise our coordinates array
var coords = new Array();
 
//Initialise our markers definitions - in this example we are just using an image for a custom icon	
var marker_types = new Array();
marker_types['marker_1'] = 'marker_1.png';
marker_types['marker_2'] = 'marker_2.png';
// ]]></script>

For this example I will just be generating a random selection of coordinates to populate our array, obviously in an actual solution you would want to populate this either by hand (if they will never change) or pulled from a database (possibly using Ajax) to get your own data in there:

//Initialise our coordinates array
var coords = new Array();
 
//Initialise our markers definitions - in this example we are just using an image for a custom icon
var marker_types = new Array();
marker_types['marker_1'] = 'marker_1.png';
marker_types['marker_2'] = 'marker_2.png';
 
function gen_data(amount) {
		for(var i = 0; i0.5) {
				coords[i].type = 'marker_1';
			} else {
				coords[i].type = 'marker_2';
			}
		}
}

The principal job of this function as discussed before is to populate our coordinates array with data. Given a number of markers to generate the function generates a random latitude and longitude (making sure that they are roughly around the same location so that they are visible together) and then assigns a “type” to the marker for deciding what image should be used.

So now we have the ability to generate some data, and also the definitions we will use for the different markers, now we can create our code to populate the map:

//Declare our map object
var map;
 
window.onload = function () {
 
	gen_data(100);
 
    	var latlng = new google.maps.LatLng(51.451408,-0.847959);
    	var myOptions = {
      		zoom: 12,
      		center: latlng,
      		mapTypeId: google.maps.MapTypeId.ROADMAP
    	};
    	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
 
 }

We have declared our map and then added a function to run once the page has loaded, essentially this function generates our random data to be used, sets up the map using the options provided and then asks GoogleMaps to draw it within the element on our page with the id “map_canvas” which we also need to add to our page:

 

So now we have some data and a map and we need to add them together, which we can do by looping over our array of coordinates and adding the markers to our map, we add this at the bottom of our onload function:

for(var i in coords) {
 
			var marker = new google.maps.Marker({
		        map:map,
		        draggable:false,
		        position: new google.maps.LatLng(coords[i].lat,coords[i].lng),
		        icon: tree_types[coords[i].type],
		        title: coords[i].type,
		        zindex: i
	      	});	
 
}

This code loops over our array to be added to the map and then for each marker adds it to our “map” we have declared.

The most import point to notice here is that for every element in our coords array we are looking at a corrds object we have defined, each contains the latitude (obj.lat), longitude (obj.lng) and type (obj.type). In the code above our coords[i] gives us the i’th element within our coords array (all of which are coords objects.

As coords[i] is a coords object then we can simply use coords.property (where property is lat,lng or type).

The main advantage of this approach for me is that its easy to add new maker declarations (by adding to the marker_types array), and that we can populate the coords array however we want (as evidenced here – because we are using a function to generate test data).

The main downside is that if your system had a lot of markers spread over the whole world – we wont want to add them all at once – we would also probably like to hold references to the markers in order to alter them later on, but its a good start for the problem I had to overcome for my project.

The final code:

<script type="text/javascript">// <![CDATA[
//Initialise our coordinates array
var coords = new Array();
 
//Initialise our markers definitions - in this example we are just using an image for a custom icon	
var marker_types = new Array();
marker_types['marker_1'] = 'marker_1.png';
marker_types['marker_2'] = 'marker_2.png';
 
function gen_data(amount) {
		for(var i = 0; i<amount; i++) {
			var mx = 51.451408 + (Math.random()/20) - 0.0225;
			var my = -0.837959 + (Math.random()/20) - 0.0225;
			coords[i] = new Object();
			coords[i].lat = mx;
			coords[i].lng = my;
			if(Math.random()>0.5) {
				coords[i].type = 'marker_1';
			} else {
				coords[i].type = 'marker_2';
			}
		}
}
 
//Declare our map object
var map;
 
window.onload = function () {
 
	gen_data(100);
 
    	var latlng = new google.maps.LatLng(51.451408,-0.847959);
    	var myOptions = {
      		zoom: 12,
      		center: latlng,
      		mapTypeId: google.maps.MapTypeId.ROADMAP
    	};
    	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
 
for(var i in coords) {
 
			var marker = new google.maps.Marker({
		        map:map,
		        draggable:false,
		        position: new google.maps.LatLng(coords[i].lat,coords[i].lng),
		        icon: tree_types[coords[i].type],
		        title: coords[i].type,
		        zindex: i
	      	});	
 
} 
 
}
// ]]></script>

And for our div:

 

Any questions or problems (or suggestions for other similar blogs you would like to see) – please add them to the comments!

Rob Basden

Rob founded a web design company company which was acquired by Linear Blue in 2009 in order to bring web development to bring professional web development services in-house. After graduating from Warwick University with a bachelors degree in Computer Systems Engineering, Rob entered the world of web development. He began by supporting a development team then moved on to running his own team as development director. His skills include extensive knowledge of PHP / HTML / Javascript / CSS / Ajax methodologies and Flash / Actionscript.

More Posts

1 thought on “Google Maps – Multiple Custom Markers”

Leave a Reply