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. sasan says:

    thanks you very much for your information

  2. Pat Hults says:

    Is there a way to link the content of an infobox to wikipedia?

  3. Spot on! Thanks for helping to spread how easy this is to do, Im sure tons of people have benefitted from this.

    • Irishman says:

      I THANK you so much for this great tutorial, straight forward, easy to understand and amazing outcome on a webpage!

      I digg it!

  4. shilpee says:

    Hi Peter,
    I am definitely asking my webdesigner to use this for my site. I really enjoyed trying it myself even though my knowledge is extremely limited.
    I would like to add ‘text’ directions besides the visual directions. How can I make that work?
    Thanks again.

  5. Artisani says:

    Thanks man,

    I’m gone give this a try on of my websites.

  6. Stefan says:

    Great tutorial! Thanks!

  7. Murty BVNS says:

    Good tutorial. I had to rely on widgets to do this until now which made my blogs and websites slow to load.

  8. rey says:

    hi peter sorry to trouble you. i managed to display the info window thanks to ur tutorial :)

    but i still have a problem. how can i trigger the infowindow to close on mouseout event?

    thanks a lot

  9. rey says:

    nice tutorial.

    but i still have trouble with my code displaying the info window.

    var singapore = new google.maps.LatLng(1.283333,103.833333);
    var map;
    var marker;
    var infoWindow;
    var contentString = ”+
    ”+
    ”+
    ‘Location’+
    ”+
    ‘Latitude: Longtitude’+
    ”+
    ”;
    ;

    function initialize() {
    var myOptions = {
    zoom: 16,
    center:singapore,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById(“map_canvas”), myOptions);

    google.maps.event.addListener(map, ‘click’, function(event) {
    placeMarker(event.latLng);
    });
    }

    function placeMarker(location) {
    var clickedLocation = new google.maps.LatLng(location);

    infowindow = new google.maps.InfoWindow({
    content: contentString
    });

    marker = new google.maps.Marker({
    position: location,
    map: map,
    icon: ‘image/blue-dot.png’,
    title: contentString,
    clickable: false
    });

    map.setCenter(location);

    google.maps.event.addListener(marker, ‘mouseover’, function() {

    infowindow.open(map,marker);

    google.maps.event.addListener(marker, ‘mouseout’, function() {
    infoWindow.close();
    });
    });
    }

    i cannot get the info window out on mouseover event.. i hope to display the location name and its lat and long but how?

    please advise me thanks a lot

  10. Kishore says:

    Really GOOD Post Dude:

  11. Easy to use and implement.

  12. Jennifer says:

    Great Tutorial. Thank you!

    Question though, is it possible to have the map show up on only one page of the site? I have the map working only problem is it’s on every page of my site. Thanks in advance.

  13. Angela says:

    Great, great tutorial! Thanks so much!

  14. Bronson says:

    Awesome and seeminly simple, just the solution I was looking for to pimp out a location map for a client who has a few guest houses near each other – this will rock their socks off!

  15. Sarah says:

    Great Tutorial! Finally one that made sense and walks you through the process.

    I am wondering though, is there a way to link it to excel or have it auto update? Or is the easiest way to add more locations to the map to do it manually in the editor? My map is going to be updating frequently and manually won’t be efficient.

  16. Jim says:

    Many thanks! Much easier to comprehend than Google’s own site! Cheers…

  17. RDB says:

    I could not get this bit to work:

    Any suggestions are appreciated.

  18. Chris says:

    Hi been messing around with map tutorials for days now. Wish I had found this one first!

    Two questions though…

    How do I add an info window to each marker (I have 27 markers on my map)

    and

    Is there a way to get the marker to show from a link click at the side of the map (ie I list 27 venues in an UL each with a link, when the user clicks one I want the appropriate infowindow to appear)

    Any help would be great thanks

    Chris

    • Peter says:

      Hi Chris,

      First, to add another (or 26) info windows, all you have to do is to duplicate the contentString and infowindow varialbes – you just name them something else, like contentString1 and infowindow1 or whatever you’d like to. Create these two variables for each of your infowindows.

      Also, you have to insert this code, replacing infowindow and companyMarker with the variables for the current infowindow.

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

      Secondly, to open an info window by clicking on a link in the side, you could add the following as onclick to your link, replacing infowindow and companyMarker with the names of your variables.

      infowindow.open(map,companyMarker)

      That is, for instance:

      <a onclick="infowindow.open(map,companyMarker)"></a>

      I’m not actually sure this works, but try it out and let me know.

      Cheers!

  19. Hadith says:

    Thank you for this, really helps, i’ll bookmark it for now, but ill def be using this.

  20. We use Google map as addons to increase efficacy of our clients site. We have experienced that it is very important for e-commerce site. For e-commerce site most important is conversion rate and credibility and simplicity are two most important factor for a website. In general buyers are not much technically aware and want simple purchase process and a pic of owner along with Google map is the best way to make a e-commerce site well accepted by customers.

    these are my 2cent. Hope help full other visitors.

    Thanks

  21. Sean says:

    This tut is great… Just what I all need at this time… Really thanks…

  22. dale says:

    Great tutorial, thanks for taking the time to set it up.

    My only issue is that I’m unable to add more than one map to the same page. I’ve got a contact page with multiple locations and I wanted to add a map for each.

    Anyway this is possible?

  23. Hrvoje says:

    Hello dear Peter, great tutorial, but i’m having some difficulties, could You please drop an eye on my code here:

    this is in

    function initialize() {
    var latlng = new google.maps.LatLng(45.893866,16.11282);
    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
    };
    var map = new google.maps.Map(document.getElementById(“map_canvas”), settings);
    var companyLogo = new google.maps.MarkerImage(‘images/google_ikona.png’,
    new google.maps.Size(100,167),
    new google.maps.Point(0,0),
    new google.maps.Point(100,100)
    );
    var companyPos = new google.maps.LatLng(45.893866,16.11282);
    var companyMarker = new google.maps.Marker({
    position: companyPos,
    map: map,
    icon: companyLogo,
    title:”Igraonica Medvjedić Winnie”
    });
    }

    .
    .

    .
    .

    Where did i go wrong?
    The map should be seen on the page:
    http://www.igraonica-medvjedic-winnie.hr/gdje_smo.html

    Thank You very much!

    • Hrvoje says:

      Sorry I’ve put some marks in so they are invisible, lets go again, this is my code:

      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
      script type=”text/javascript”
      function initialize() {
      var latlng = new google.maps.LatLng(45.893866,16.11282);
      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
      };
      var map = new google.maps.Map(document.getElementById(“map_canvas”), settings);
      var companyLogo = new google.maps.MarkerImage(‘images/google_ikona.png’,
      new google.maps.Size(100,167),
      new google.maps.Point(0,0),
      new google.maps.Point(100,100)
      );
      var companyPos = new google.maps.LatLng(45.893866,16.11282);
      var companyMarker = new google.maps.Marker({
      position: companyPos,
      map: map,
      icon: companyLogo,
      title:”Igraonica Medvjedić Winnie”
      });
      }
      /script

      /head

      body onload=”initialize()”

      div id=”map_canvas” style=”width:800px; height:600px” /div

      • Hrvoje says:

        Ok, i’ve found out what was the problem! Thank You and sorry for the trouble. It seems that a script i have on my webpage is in conflict with google’s map script. as soon as i deleted the previous script, the map appeared. now i only have to manage to get them both to work at the same time! ciao

  24. Hrvoje says:

    great tutorial!!!!

  25. Naganjan says:

    Execellent ! Earlier I didn’t know how to place the API code, but after reading the tutorial I am sure I can do it.
    Thanks a lot for sharing
    Naganjan

  26. Mick says:

    Nice tutorial.. thx a lot

  27. Fabio says:

    Awsome tutorial. Very helpful, thanks!

  28. Brian says:

    Hi,

    First, thanks for the tutorial.

    I’m following your instructions except for changing the coordinates, which are working fine, but I can’t get a marker. I can’t get Google’s marker, I can’t get a custom marker.

    I uploaded your custom markers for testing, so they should be showing up on the map.

    I also put a fake map image under the real map so you can see where the marker should be.

    Can you look at my page and tell me what’s wrong?

    http://www.eccatoysfortots.org/maptest/maptest.html

    Thanks,

    Brian

  29. Hi!

    Thanks for the awesome tutorial, great job!

    But as this is my first work using Google API, i can’t seem to understand the need of that key that i signed up for. You are not using it on your tutorial and it works flawlessly both on localhost and the site where i am using the API, but now, when i the first script line inserting there the Googles given link+key = it simpy doesn’t even show the map.

    I even got a key for “http://localhost” but still the map was not showing, then i changed back to your code, where you are not using any keys – so where is the catch? Why with the my own key map is not showing up? Is that because your code differs from Google’s functions and they don’t work together?

    And by the way – what is the difference if i am using that key and if i am not using the key – like you here on this tutorial?

    Thanks!

  30. Hey, just wanted to say this is one of the finest map tutes on the web. Very nice work.

  31. nathan says:

    I tried using this method, and I’m getting a syntax error in the 3rd line in DWCS4:

    var latlng = new google.maps.LatLng(29.5497903, -98.4789687);

    I’m a framework user—more designer than developer or programmer. I’m not sure what’s going on here. Any ideas? (coordinates have been customized for the business I’m building this site for.)

    • Peter says:

      That’s weird. Do you get the syntax error when using the code directly copied from this site?

      And also, does the map work when you open your site in a browser? It might just be Dreamweaver messing with you…

  32. Tamara says:

    I made a completely customized google maps v3 last week, including customized control buttons. Someone wrote a few functions for it, you can download it here: http://google-maps-js-api-v3.googlegroups.com/web/custom-controllers.zip

    I used this for basics, and extended it a bit, too.

    I got it from this site: http://groups.google.com/group/google-maps-js-api-v3/browse_thread/thread/671858685b8b6c1b/e9642fb0ecc5cab1?lnk=gst&q=button+custom#e9642fb0ecc5cab1

  33. John says:

    Great tut! Great result, almost perfect :-)

    I am having trouble inserting :
    google.maps.event.addListener(companyMarker, ‘click’, function() {
    infowindow.open(map,companyMarker);
    });

    After inserting this literarly the map stops working.

    I have :


    mapTypeId: google.maps.MapTypeId.ROADMAP,
    google.maps.event.addListener(companyMarker, ‘click’, function() {
    infowindow.open(map,companyMarker);
    });
    };

  34. Macoi says:

    Hello, what if i want to get the data from an xml file? how can i do that? thanks.

    • Peter says:

      As I understand it, the API doesn’t give an option for retrieving data from an XML file the way it is now. I guess you have to use some PHP or something in order to get what you want. You can try asking the question in the Google Group.

  35. Emmie says:

    Brilliant, thank you so much, clear and easy to use. Even for someone who doesn’t know java. Thanks.

  36. John says:

    this tutorial is insane! can’t wait to propose it to my customers! thank u very much for this very good work you did!

  37. Sava says:

    Really really great tutorial. I didn’t know you could customize google maps this way :D

  38. Neil Quadros says:

    Great! Thanks so much for this. Been looking around about how to work the API. Will get back in a few days.

  39. artViper says:

    That’s really a nifty function, I guess most of our customers would love to see it on their page(s).

  40. Mark says:

    I was zooming in and out on my map and the icons were moving to the left.. anyone know why?

  41. Adriano says:

    very nice tutorial!

  42. in-sanity says:

    Very nice tutorial. Thanks.

  43. Shweta says:

    Its nice,
    it will be very helpful for us in our project at student level.

  44. Biju Subhash says:

    Hey,
    Nice job….
    Thank you for sharing :D

  45. Thanks for the great information, we hope to use this google map on our website http://www.studentbrands.co.za to show people how to get to our offfffffffffices

  46. Jim says:

    Great tute – thanks – exactly what I needed. Great stuff :-)

  47. Catalin says:

    Nice work man!!
    Just one thing: for example if for a certain location i want to use a png and for others i want to use the standard marker for google map how do i do that?

  48. u have really shown it in an easy way… it is crystal clear to me now… thank u very much…

  49. JM says:

    Just a quick note,
    If anyone is having trouble with the markers (taken from the example), you can change the second line “new google.maps.Point(XX,XX)” for the itemImage, so the first number is half the width of your png image and then add 10 for the itemShadow.
    I was zooming in and out on my map and the icons were moving to the left. I don’t know JavaScript so it took me a little bit to figure out why.
    Btw, I love the tut.

    var itemImage = new google.maps.MarkerImage(‘images/item.png’,
    new google.maps.Size(90,50),
    new google.maps.Point(0,0),
    new google.maps.Point(45,50)
    );

    var itemShadow = new google.maps.MarkerImage(‘images/item_shadow.png’,
    new google.maps.Size(90,50),
    new google.maps.Point(0,0),
    new google.maps.Point(55,50)
    );

    • Peter says:

      Nice, JM!
      That’s really useful, and also probably a better way to do it than I did!

      • apo says:

        Dear Peter i have already read the problem of a friend with the movement of the figures while zooming or unzooming. The trick to set the parameters half of the width at the third line works a bit but it does not work with big detail. If you see my page you will see some figures in Greece and if u unzoom alot of times u will be able to see them in another country. It is the same with ur example upper. If you unzoom alot u will see the figure in another country. Please HELP!!

Trackbacks & Pingbacks