Adding Custom Google Maps to Your Website

Adding Custom Google Maps to Your Website

Maps are often placed on a company website to help customers find their way there. For that, Google Maps is excellent. But wouldn’t it be nice to add your company logo, parking lots, train stations, etc. to the map, to help the customer even more? It is very simple, and in this article I am going to show you how.

Before we start, check out what we are going to create:

Now, here is an overview:

Overview

Google Maps API

The Google Maps API allows you to embed maps directly into your website. All it takes is a little JavaScript, and for beautifying—a little CSS. Version 3 of the Google Maps API has just been released, and of course, that is what we will be using here. You can read the entire documentation over at Google Labs, and while you are there, be sure to get an API key.

Getting the Coordinates

As I do not expect you to know the precise coordinates of your location, I will explain a very quick way Google has provided to do this. When you know the exact address, you can put it in an URL of this form:

http://maps.google.com/maps/geo?q=1+Infinite Liip,+Cupertino,+CA+95014,+USA&output=csv&oe=utf8&sensor=false&key=your_google_maps_api_key

When you enter this in your address bar, you will see this:

The coordinates of Apple's head quarter in Cupertino

The coordinates of Apple's head quarter in Cupertino

The first number is the status code, and 200 means that everything is okay. The second number shows how accurate the address is—in this case the number is 8, which is good. The last two numbers are latitudes and longitudes, which are the numbers we need.

Adding the Map to Your Website

There’s no need to hesitate – let’s add that map to your website! Open your favorite HTML editor and create a standard HTML file with UTF-8 encoding. First of all, we have to create the viewport and tell our HTML file to get the JavaScript file from Google Code. Add these lines between <head> and </head>:

1
2
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

After the URL, you will notice sensor=false. As we do not use any sensor, such as a GPS, to locate the location, this is set to false.

Just below what we have just inserted, write the following:

1
2
3
4
5
6
7
8
9
10
11
12
<script type="text/javascript">
function initialize() {
var latlng = new google.maps.LatLng(57.0442, 9.9116);
var settings = {
zoom: 15,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP
};

Let’s split this up to ensure that we understand it fully. In line 2 we create the function initialize(). Inside this function we are going to define the basic settings of the map. In line 3 we create a new variable, latlng. latlng stands for latitudes and longitudes. The variable contains the coordinates we’re going to use as the center of our map.
After that, we create the variable settings. You have a lot of options here.

zoom specifies—you guessed it—how far the map will be zoomed in. Play around with the number to get it to fit your location.

center specifies our center. By writing latlng, we refer to the variable we created earlier, and the coordinate inside that will be used.

The last code changes the layout of the map to a bit more minimalistic look in my opinion. The controls in the upper right corner (Map, Satellite, Terrain) are changed to a drop down menu, and the scaling/navigation controls in the left size are changed to small controls.

mapTypeId: google.maps.MapTypeId.ROADMAP defines that our map should be of the type ROADMAP – you can change this to either SATELLITE, HYBRID or TERRAIN.

Below the previous code, write this:

1
var map = new google.maps.Map(document.getElementById("map_canvas"), settings);

This code creates the variable map, and defines that the map should use the settings we just created.

Write

1
2
}
</script>

to end the function, and move to <body>, and write this:

1
2
3
<body onload="initialize()">
<div id="map_canvas" style="width:800px; height:500px"></div>
</body>

By doing this we are telling our site to execute the initialize() function when the site is loaded, and insert a <div> with the size we want our map to be.

Try to view your site now. Cool, isn’t it?

Adding Markers

Now we have to add some markers. Let’s start by creating a standard marker—we’ll customize it in a moment.

Right below

1
var map = new google.maps.Map(document.getElementById("map_canvas"), settings);

insert the following code:

1
2
3
4
5
6
  var companyPos = new google.maps.LatLng(57.0442, 9.9116);
var companyMarker = new google.maps.Marker({
position: companyPos,
map: map,
title:"Some title"
});

Try to update your page, and watch the magic. So, what have we done?

First, we create the variable companyPos, where we specify the position of the marker. Next, we create the marker itself using the variable companyMarker. You can add more settings than these, but we will get to that later. These settings are fairly logical, so I won’t go into more depth with them.

Customizing the Markers

Even though this could be enough to show your customer how to find you, we can still make it a lot nicer. Create an image in Photoshop with the size 100×50 pixels, and create something similar to this:

Create your logo

Create your logo

Next, create a shadow for your image:

The logo shadow

The logo shadow

To add these images as a marker instead of the standard marker, change the marker code to this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var companyLogo = new google.maps.MarkerImage('images/logo.png',
new google.maps.Size(100,50),
new google.maps.Point(0,0),
new google.maps.Point(50,50)
);
var companyShadow = new google.maps.MarkerImage('images/logo_shadow.png',
new google.maps.Size(130,50),
new google.maps.Point(0,0),
new google.maps.Point(65, 50)
);
var companyPos = new google.maps.LatLng(57.0442, 9.9116);
var companyMarker = new google.maps.Marker({
position: companyPos,
map: map,
icon: companyLogo,
shadow: companyShadow,
title:"Company Title"
});

What we have done here is also really simple. The variable companyImage points to the name of the logo image. Then it defines the size of the image, the origin of the image, and the tip of the image (where the image will be attached to the coordinate). Next, we do the exact same thing for the shadow in the variable companyShadow. In our companyMarker variable we add icon and shadow, and that is basically it.

Now, if you refresh your site, you will se that the marker has changed into your own logo with an added shadow to it as well. To add more markers, you just follow the same method (remember to change the names of the variables).

If you have two markers very close to each other, you might want to add some z-index. The marker with the highest z-index, is the one on top:

Adding zIndex allows you to choose which marker should be on top

Adding zIndex allows you to choose which marker should be on top

1
2
3
4
5
6
7
8
var companyMarker = new google.maps.Marker({
position: companyPos,
map: map,
icon: companyImage,
shadow: companyShadow,
title:"Høgenhaug",
zIndex: 4
});

Adding Infoboxes

To add a description of your company when the visitor clicks on the logo we can add a infobox. With the Google Maps API it’s peace of cake.

Clicking your company logo will bring up an infobox

Clicking your company logo will bring up an infobox

Paste this code right after you define the map variable:

1
2
3
4
5
6
7
8
9
10
11
12
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">Høgenhaug</h1>'+
'<div id="bodyContent">'+
'<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>'+
'</div>'+
'</div>';
 
var infowindow = new google.maps.InfoWindow({
content: contentString
});

The code here is fairly straight-forward, and you are of course not limited to headlines and paragraphs – there is room for images as well. To make the infobox appear when your logo is clicked, simply add this code right before the last } in the initialize() function:

1
2
3
google.maps.event.addListener(companyMarker, 'click', function() {
infowindow.open(map,companyMarker);
});

To make the infobox just a little more pretty, add some styles in your stylesheet file:

1
2
3
4
body {
font-family: Helvetica, Arial, sans-serif;
font-size:10pt;
}

And there you have it. One piece of fine-looking Google Map to include on your company website, your travel blog, etc.

Download

If you’d like to download the sample files, you can get ‘em right here. Be sure to leave a comment!

Share, share, share!

Did you like this article? Please share it with your friends:
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • Technorati
  • Twitter
  • email

Related posts:

  1. How to Use Directions with Google Maps API V3
  2. 5 Cool Ways to Add Graphs to Your Website
  3. Enhancing Your Site with WebKit

162 comments so far

Add one yourself

  1. Mike says:

    I like this project and I’m attempting to use it. I’ve got things working OK, but I have a large area with lots of buildings. I wanted to do multiple markers with multiple info windows. I made copies of the necessary code, changed the variables and it works, only the info windows won’t go away when someone clicks on the map or another marker. Can someone explain what I should be doing to make that happen?

  2. David says:

    I can not figure out how to make this popup window contentString displayed on load not on click…. any tips?

    BTW. Great article man.

  3. that was wonderfully explained. thanks for the walk-through, you discussed it in every single detail.

  4. Ubisan says:

    Great post and really easy to follow.

    I reckon I’ll design some nice markers and replace the standard Google Maps feed with my own one in the very near future!

  5. kissmo says:

    Thanx for sharing….Really awesome..I ll try in my site..

  6. marius says:

    !!! There is an error message in IE6 and IE7 because of the trailing coma in this code bellow:

    var companyMarker = new google.maps.Marker({
    position: companyPos,
    map: map,
    icon: companyLogo,
    shadow: companyShadow,
    title:”Company Title”,
    });

  7. MattDunlap says:

    Love the blurred map… Makes it look deep.

  8. Vikram says:

    Thanks, nice new concept.

  9. Tam Nguyen says:

    Thanks man – great post… ^_^

  10. UpTrending says:

    Great post and a useful resource for web developers working with Google Maps. I’ve added the link to my blog here: http://www.andybrewer.com

  11. Nicely explained, Peter…and there are some valuable comments too. Thanks.

  12. Saudinium says:

    This is awesome man! Thanks for sharing it with the rest of us!! God bless..

  13. Hos Robert says:

    Thanks a lot! Very usefull …

  14. Steffen says:

    Here’s a nice webtool for googlemaps coordinates: http://www.vivid-planet.com/sandkiste/google_maps_koordinaten/

  15. freddo says:

    thanks… its so usefull….

  16. Barton says:

    Nice and simple, good starter read…

  17. Well done. Easy to implement, very informative. I will add it to my aerial photography site. Thx.

  18. fastmanu says:

    Really nice… thanks a lot :)

  19. Matthias says:

    Nice and detailed! Thanks.

  20. Harsha M V says:

    wow. nice article. thanx a lot.

  21. anon says:

    Does it validate?

  22. Nice feature, good post. I’m sure I’ll use this on my pages. Thanks!

  23. For a long,long time I´ve been searching an clear and direct explanation for embebing this code and to get an personal custom map without lossing quality. Al last I found your web through STUMBLE UPON and Eureka . This is it.

    THANKS. FOR SHARE YOUR SKILLS WITH US, WITH THIS ACTION WE ARE GETTING AN INTERNET MORE FRIENDLY FOR ALL !

  24. ticacho says:

    Great explanation man ;)

    It’s very usefull

    Regards

  25. Baris says:

    I have added some code so I can map any address dynamically (for instance when I have more addresses in a database). Maybe it’s not the best coding, but it works for me.

    $gresult = file(‘http://maps.google.com/maps/geo?q=ADDRESS&output=csv&oe=utf8&sensor=false&key=GOOGLEKEY’);
    list($gm_status,$gm_soort,$gm_lat,$gm_long) = split(“,”,$gresult[0]);

    ADDRESS = the address how google wants it in the URL, just like “1+Infinite Liip,+Cupertino,+CA+95014,+USA”. This address will come from your database.

    $gm_status is the status code, so you should check if this is 200.
    $gm_soort is the the accuracy, so you can decide when to show and not (I have mine set at > 4).
    $gm_lat and $gm_long are the lattitude/longitude which you can then use everywhere you need those.

    I hope it’s clear what I mean.

    • foco says:

      I am interested but is not clear enough for me.
      You mean that having an ADDRESS on the DB, request to google geocode in order to obtain de status, accuracy, latitude n longitude ($gm_soort,$gm_lat,$gm_long) and then probably Insert them into DB?

  26. Coogan says:

    Hey man, great article. I’ve already knicked and implemented it on my own site. ;)

    Just one thing, for our less adept coders.
    You state the variable
    var companyLogo = new google.maps.MarkerImage(‘images/logo.png’…

    But then call on “icon: companyImage,” which would explain why some people might have some trouble getting their custom icons to display.

    Simply change “icon: companyImage,” to “icon: companyLogo,” and you’re all set. :)

  27. Viona says:

    This is fantastic! Just what I needed!

    I’ve implemented and tested with Firefox and Chrome, they work perfectly. However with IE6 (shitty browser, I know) it comes up with the following error:
    “Line: 21
    Char: 5
    Error: ‘google’ is undefined”
    when using your sample pages.

    Any idea how to fix that?

  28. WittWicky says:

    Everything worked except I’m having trouble displaying custom markers. Standard marker appears okay—custom marker doesn’t show at all. Try 174.132.190.8/~valcom99/map_code.txt to see the code.

    Thanks,
    WittWicky

  29. Chris says:

    You could try OpenStreetMap.org. The maps are often better than Google and are truly free to use. The underlying data is available too.

  30. This stuff is getting easier and easier. I still like Google Maps the best though.

  31. 摇光 says:

    what’s the Google Maps API use for?

  32. Tess Ledesma says:

    Educational. Nice to visit sites like yours. I have learned enough today. I will visit you again.

  33. Digital Dojo says:

    awesome! very informative.

  34. Tek3D says:

    awesome. Thanks very much

  35. Thank you! This is exactly what we were trying to figure out how to do with one of our applications. Then this morning I looked in Google Reader and there was this little RSS feed from the programming Gods.

    All kidding aside, this is kick ass and is exactly what we needed to make one of our apps for our clients more user friendly.

  36. Freddy says:

    Great post. I’ve been looking for a way to spice up and customize my clients’ maps.

  37. ozzysong says:

    Nice work!

    Very informative.

  38. Gajendra says:

    Great work !

  39. Web Designer says:

    very very useful and a well written tutorial.

    thanks for this.

  40. Oleg says:

    Yeah! Thanks a Lot! I used G maps API in past but not with teh custom logo.

  41. FoO Iskandar says:

    Great Article … thank’s

  42. markgt says:

    very nice tut!
    straight to the point and easy to follow, with no fluff
    thanks! :-)

  43. d13t says:

    I’ve succesfully implemented a directions to here option in the info balloon via this method: http://bit.ly/4DkHm
    There are some coding flaw in that script, but it’s not hard to figure out and get it to work AND style it.

  44. Ricardo Zea says:

    Very nice article.

    You should have a “Send article to friend” link or something to send articles from your site to an e-mail address.

    Thanks.

  45. URK says:

    Great post..

    Is there a way to instead of popping up the information box, make a “directions to here” link like in google maps? That would be a great feature –

    URK

    • Peter says:

      Hi URK,

      I am actually not sure about how to do that – it is possible, I just don’t know how to do it, but I’ll definitely look into it – it’s a very exciting idea!
      UPDATE: I found this post at the Google Maps API v3 Group, and it states that directions are not yet supported in version 3, but that they will be in a short period on time – and when that happens, I’ll post a tutorial on Stiern.com on how to implement it in our map!

  46. JT says:

    Great Tutorial!
    Is there a way to replace the map and add your own image to the viewport?

    Thanks

    JT

  47. Robert says:

    Hi, excellent post, very useful thanks.

    I have a question for you: How can show track in map? or add a kml file?

    Regards.

    • Peter says:

      Hi Robert, and thanks for your comment!

      With ‘track’ I assume you mean a ‘route’ – so you’re able to show your customers which way to go, right? I will return with another tutorial on this very soon!

      Regarding KML files from Google Earth – I’ll have to look into that, but I’ll let you know!

  48. cypherbox says:

    Useful post. thanks!

Trackbacks & Pingbacks

  1. Personalizar mapas de Google | Mailing Factory
  2. links for 2009-11-20 | HiRes Squad
  3. Customized Google Maps on Your Website
  4. Agregando Google Maps a tu sitio web | ubiraci.com
  5. Chris Robson Design.co.uk » Custom google maps
  6. Блог-шоу - выпуск 30 - Продвижение сайтов, веб-дизайн и креатив
  7. Google Maps API - Personaliza tu mapa - Añade tu negocio a GOOGLE MAPS | Smultron POTENCIA !!
  8. Twitted by n0unours
  9. Insertar y personalizar Google Maps en tu sitio web - elWebmaster.com
  10. PixMedial — Design & Geek » Personaliza el Mapa de GoogleMaps
  11. Implementacija Google maps | T&R splet - internetne storitve
  12. Friday Fix Oct 12 – 16 | Programming Blog
  13. Daily Digest for October 21st | Mike Hayes
  14. Teknologeek.com » Cómo Agregar Mapas Personalizados a tu Sitio Web o Blog
  15. Resource Roundup | Andy Brewer
  16. Heti események | I build websites
  17. Embed Customised Google Maps into Your Website | Programming Blog
  18. Персонализирана Google Maps във Web 2.0 Приложение | Web 2.0 Blog
  19. Tutorial per inserire una mappa personalizzata di Google nel nostro sito web
  20. Notable Tech Posts – 2009.10.18 | The Life of Lew Ayotte
  21. Adding Google Maps to Your Website | blogfreakz.com
  22. Google Maps API mini ceļvedis | onkulis.com
  23. Daily Digest for October 18th | More Than Scratch The Surface
  24. Embed Customised Google Maps into Your Website | trackteq.com
  25. AMB Album » Embed Customised Google Maps into Your Website
  26. Friday Fix Oct 12 – 16 | Master Design
  27. links for 2009-10-17 « Giri’s Blogmarks
  28. Adding Custom Google Maps to Your Website | Stiern.com
  29. Embed Customised Google Maps into Your Website | Internet, Marketing, Enterprenuership
  30. Cum pun în situl meu o hartă Google | CNET.ro
  31. Aggiungere una google maps personalizzata nel proprio sito web - Caputo’s blog - Informatica, tecnologia, programmazione, fai da te, papercraft e papertoy
  32. Friday Fix Oct 12 - 16
  33. links for 2009-10-16
  34. links for 2009-10-15 « Boskabout
  35. The Barcus Family » links for 2009-10-15
  36. links for 2009-10-15 | Glorified Monkey
  37. polaris14551 | 摇光 » 在Google地图上标记地点
  38. links for 2009-10-15 « Uncle Joe's House of Crazy
  39. Adding Custom Google Maps to Your Website | Stiern.com « gregsmithsays…
  40. links for 2009-10-14 « Donghai Ma
  41. TwittLink - Your headlines on Twitter
  42. Del.icio.us op 14 oktober 2009 | Michel Vuijlsteke's weblog
  43. Seta Digital Blog » Blog Archive » links for 2009-10-14
  44. CSS Brigit | Adding Custom Google Maps to Your Website
  45. Mittwoch, 14.10.09 – Web Tweets | abtwittern
  46. Bookmarks for October 3rd through October 14th |
  47. 28 top trending topics in webdesign, technology, development and seach engine optimization « Adrian Zyzik's Weblog
  48. Adding Custom Google Maps to Your Website | Stiern.com « Netcrema – creme de la social news via digg + delicious + stumpleupon + reddit
  49. Adding Custom Google Maps to Your Website | Stiern.com » Web Design
  50. Tweets that mention Adding Custom Google Maps to Your Website | Stiern.com -- Topsy.com