Stiern

via Ad Packs

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!

346 comments

Leave one yourself

  1. Thanks! I like how your details are straight to the point, my A.D.D thanks you lol

  2. It would be perfect if this tutorial would be extended with a function for Jquery mouseovers for each marker as shown in http://marcgrabanski.com/articles/jquery-google-maps-tutorial-basics

  3. I have used that code but interent does not accept it I dont know why it is happening

  4. Thanks for the informative tutorial on creating custom google maps, I am working on a rabbit breeders directory and have been considering adding maps to the site but really didn’t know where to begin. I still will have to work out a few obstacles due to the way I have my directory setup however I wanted to thank you for taking the time to add this tutorial to your site.

  5. This is my second go to to your blog. We are starting a brand new initiative in the same category as this blog. Your blog provided us with valuable information to operate on. You’ve done a great job.

  6. @Palomo Graphics: Yes, I am suffering from the same problems. The iPhone seems to have difficulties with the zooming issue.

    Also, I cannot insert two different maps on one single page. Does anyone know how to do that? See comment-9222

    Thanks a lot!

  7. Great tutorial, congratulation!
    But I can’t seem to make it work on Firefox v3.6.8. Could you please tell me what I’m doing wrong or any tips on it?

    Thank you!

  8. Hi Stiern,

    I am making a map with diretions, and therefore I need the map to center at some coordinates. The code “center: latlng,” is centering at our marker, which you have pointed out. How do I center it at these coordinates?:

    56.24335, 10.59082

    I have tried center: 56.24335, 10.59082 and center: (56.24335, 10.59082);

    None of these have worked so far. I just get a blank page.

    You can answer in danish, if you want to. ;-)

  9. Great tutorial and it worked! I found though when I viewed the website with this embedded google map on my iPhone it locks zooming out capabilities of the entire webpage. Zooming in and out of the map itself is fine but I can’t seem to zoom out of the web page…Am wondering if anyone roses site that uses this code has the same issues?

  10. Thank you so much for your article. It’s really well explained and 100% useful. Congrats mate!

  11. I seen your blog using google and I must say, this is without doubt one of the best well written articles I have noticed in a long time. I have bookmarked your site for further posts.

  12. Great stuff! I am working on adding some php to print out markers from a mysql. I print out the markers with a while loop and rename the vars with $n ($n++ for every while). Q: How can I handle the infowindows, so that with clicking on one it closes all other that are open? (except for my dumb solution when closing all infowindows$n(other) but not infowindows$n(this n)

  13. i guess this is the ultimate page. i have searched a number of sites for google maps. some are lacking knowledge and some r too technical. yours is the perfect.

  14. What an useful tool! Thank you so much for this article! It’s so simple and effective with great options to customize!

    Oh powerful Javascript!

  15. Is there a better method for calling the script than body onload? The Google documentation suggests using window.onload in the script itself:

    http://code.google.com/apis/maps/documentation/javascript/basics.html#Async

    Is there a reason to use body onload instead?

  16. Great tutorial. Thank you so much!

    I tried to insert a second map on the same page. In the HTML source code I wrote:

    I added the following to the JavaScript file:

    function initialize() {
    var latlng = new google.ma…

    });

    var latlng2 = new google.maps.LatLng(57.0442,9.9116);
    var settings2 = {
    zoom:16,
    center:latlng,
    mapTypeControl:true,
    mapTypeControlOptions:{style:google.maps.MapTypeControlStyle.DROPDOWN_MENU},
    navigationControl:true,
    navigationControlOptions:{style:google.maps.NavigationControlStyle.SMALL},
    mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map2 = new google.maps.Map(document.getElementById(“map_canvas2″), settings);
    var companyLogo2 = new google.maps.MarkerImage(‘/images/googlemaps.png’,
    new google.maps.Size(100,50),
    new google.maps.Point(0,0),
    new google.maps.Point(50,50)
    );
    var companyPos2 = new google.maps.LatLng(57.0442,9.9116);
    var companyMarker2 = new google.maps.Marker({
    position: companyPos2,
    map: map2,
    icon: companyLogo2,
    title:”My Home”
    });
    }
    The first map works great. But the second map does not work. First, there is no pointer. Second, I see the first map a second time.

    How to add two maps on the same page?

  17. Thanks so much! This is exactly what I was looking for. You’ve made everything very clear and easy to follow.

  18. Thanks so much! This is exactly what I was looking for. You’ve made everything very clear and easy to follow.

  19. Google maps is getting hotter every day. Thanks for sharing how to implement it into my work.

  20. Very useful tutorial, thanks! I have one question: how do you display texts in a different language (e.g. Chinese or mixed texts) inside the info window?

  21. Really nice tutorial. I just replaced about a half dozen of my clients’ old iframe-based maps (the ones simply generated by the “embed this map” link) with spanking new ones with custom map pins.
    Thanks a lot for this.

  22. Thx for the thorough and easy to understand tutorial. I was able to make my own custom Google Map using the API tutorial. There’s one thing I can’t figure out.. it works fine in every browser except Google Chrome?! IE8, Firefox, and Safari on my PC. Chrome just shows an empty white space as if the API doesn’t load at all. What am I missing?

  23. Wow!! thanks for this wonderful tutorial, just what i’ve been looking for

  24. Hey, great tutorial. Thank you.

    But: I didn’t enter the Google API key anywhere. Which means this solution is not legal.

    To insert the API key I think I need to enter this in the header:

    But is this enough to use Google maps legally? Why does it work without the API key?

    1. There’s nothing illegal in this solution. What happened is that you don’t need an API key to use Google Maps anymore, cf. the Google Maps website.

  25. i’m write link for my location like this …
    http://maps.google.com/maps?q=Sekeloa,+Bandung,+Indonesia
    try it :) i hope that used :)

  26. Andreas Pilavakis

    September 14, 2010 at 1:19 pm

    I tested the script and it works fine apart from the first time it loads where the custon points are not shown on the map…the second time and thereafter it is fine…any idea why? It worths mentioning that the map is inside a jquery tab…Please advice me how to resolve this issue

  27. Pretty useful post. Thanks.

  28. Thanks alot for this tut i really like it ….
    i like to here from you guys more on google maps

  29. Great tut. I RSS the site as soon as I read through this tutorial. I am having one problem. My custom marker does not show up. It is there I can click on it and the info window opens up but I cannot see it. Here is the page it the map is displayed on: http://winonafaith.com/index.php/location/

    Any advice would be great.

    1. Hi Aaron,

      It seems the path for your images is wrong. When looking for the image “orangebrown/winona_faith_marker.png” on your server, I simply can’t find it. Are you sure it is uploaded, or that the path is correct?

      Let me know how it goes.

      1. Peter
        Thanks. I feel a little foolish for not checking that. I was so consumed in analyzing the code I was skipping over the basics. Thanks for your quick help and response. I love the site and have become a follower via RSS and twitter.

        thanks for taking the time to put together a great tutorial.

  30. Thank you a lot about very beneficial to my work was very useful thank you

  31. Brilliant! Just what I was looking for, thanks so much!

  32. I don’t think my last comment made it through since I came with stumbleupon. I just wanted to say great tutorial! I didn’t know it was that easy to implement using Google Maps APIs. Keep it going!

  33. Great tutorial!
    I didn’t know it was that easy to implement the Google Maps into your site with the Google Maps API. Learned a lot. Thanks!

  34. Hello, This is a really useful tutorial, I’ve been searching on how to customize ugly looking Google maps to be integrated into a project I’m working on. and that just did the trick.. Thanks :)

  35. Thanks for such easy way to Put an attractive Google Map in the website. Nice Job

  36. Has anyone else had a problem with custom Markers not showing up in Firefox or IE, but okay in Chrome and Safari?

    Great tutorial by the way, this was my only problem.

  37. i use google maps in my in one of my client website. It works great! ;)

  38. Hi Peter,
    I was so excited to see your nice article with custom bookmarks and great looks i should say, I was just doing a map search for one of my sites, and found this, just trying to get this work on wordpress platform, can you suggest how to insert the head and body tags to a wordpress page,
    Thanks for the info, Keep the posts coming,
    Bino.

  39. Great tutorial, thank you so much, if possible can you please tell me how to manipulate the code to add a second map with different points to the same page.

  40. Thanks For Great Tips. Its Really Helpful for me.

  41. this great help u r doing to me as i always had problem with google map.
    thanks a lot guys

  42. Thanks a lot! this will be very useful for future projects!

  43. Wow!!!.. impressive way to go.. i was up and running in less than an hour.. now i’m gonna push it to the max :-)

  44. you can just google it for lat / long.

  45. I found your tutorial simple enough for me and after working through got it done on my site. Now to do the same for a client. Great work and thanks.
    Martin

  46. By far the best tutorial on google maps. Trust me

  47. Hi!

    Very nice tutorial about Google Maps! I knew a lot more now! But I’m still looking for simple code how to display several markers and info windows?

  48. Hi Peter,
    I’ve incorporated all of this into a clients site, including the route mapping. Is there a way to add the directions like google does so visitor could print them? Such as ‘Start here at xxxx location, go 1.2 mi, turn rt on Rt xxx.’

    Here’s a link to clients directions page http://lathamauto.com/direction.php

    Don

    1. Hi Don,

      You can have a look at my article How to Use Directions with Google Maps API V3. Hope this helps.

      1. Thanks Peter,

        I’ve got this part working 4.0 already. I just wanted to know if possible to have a ‘Print Directions’ tab that would pull in the route with road directions.
        I’m using Iframe on site to pull in map page and have found that IE8 allows to print page with Iframe great. Site has black background so don’t want BG to waste peoples ink. IE8 does this fine however FF won’t print map if don’t print BG is turned on. ????

        1. Hi Don,

          Most printers don’t even print backgrounds, so you might just want to add that. Otherwise, you can add background: transparent;, and check if FF then can print it.

  49. Hi,
    We use a cms and I don’t want to have on every page of the site.

    Any suggestions?

    Thanks!

    1. It depends pretty much on which CMS you are using? If you are able to insert HTML code in your CMS’ editor that’s the way to go.

Trackbacks

Leave a comment

Required

Required (will not be published)

or Twitter URL

Some HTML allowed. Spam is not.