google-maps-api-tutorial

Google Maps API v3 tutorial – how to make a simple custom map

I’ve grown a little tired recently of seeing the same old Google Maps embedded onto the contact webpage of small businesses. In this tutorial I’m going to walk through some of the basic features of the Google Maps API (V3) and create a custom map for a local business.

I first tried out the Google Maps API when creating a mini map embed for our contact page. Dissatisfied with the clutter of the default Google Places embed, I managed to achieve a much more usable map whilst maintaining it’s mini size.

The types of Map Embeds Available

At present, there are three different ways to add Google Maps to your website. Classic Google Maps (below left), New Google Maps (centre) and by using the Google Maps API 3.0 (below right).

google-maps-embeds

As you can see, particularly when used small, the classic map embed is barely usable. Whilst the new standard Maps embeds are better, the Maps API gives you full control with zooming and using your own custom marker graphics.

In this tutorial I’m going to explain the basics of creating your own local business Google Map embed using the API.

This is not a complete tutorial to show you all of the possible features of the API, however I am going to cover the basics of creating your own map with a custom marker and controls.

Getting Started by loading the Google Maps API

To begin work on your map, you must first load the Google Maps API by adding the following code within the HEAD tag of your web page(s) that will be displaying maps via the API:

<script type="text/javascript"
      src="https://maps.googleapis.com/maps/api/js?key=API_KEY&amp;sensor=SET_TO_true_OR_false">
    </script>

Simply replace API_KEY with your API key (see below) then set ‘sensor=’ to either TRUE or FALSE. If you’re intending on using the HTML5 Geolocation tools built in the API, set this to TRUE, or if you’re just making a simple map like in this tutorial, set it to FALSE.

API Keys

Although not compulsory, Google recommend that you log into their API console to create and use a free API key. By using an API key you can monitor your API usage and access some simple statistics within your Developer console.

How to find a location’s coordinates on Google Maps

So now that we’re running the API, we need to start by acquiring the coordinates for the location we wish to focus on in our map. The simplest way to do this, is to literally find the point on Google Maps, then Right Click as shown below:

co-ords

By clicking on ‘What’s Here?’ the location’s latitude and Longitude coordinates are presented in the search box. Save these for later.

Defining and creating your Google Map

So now that we have our coordinates, we can begin to put together our map. To do this, we’ll need a blank Div placeholder and also some initial inline JavaScript to get our Map off the ground:

<div id="map-canvas" style="height:400px; width:600px;"></div>
<script>
	function initialise() {	
		/* All of our map settings are going here */	
	}
	google.maps.event.addDomListener(window, 'load', initialise); // Execute our 'initialise' function once the page has loaded. 
</script>

Essentially, the inline JavaScript is going to render our custom Google Map inside the empty div. In order to load our map into the div after the page has fully loaded, I’ve started by creating an empty ‘initialise’ function. Everything within our ‘initialise’ function will therefore be triggered once the page has fully loaded. Now let’s focus on the settings that fall within our initialise function:

function initialise() {
		
	var myLatlng = new google.maps.LatLng(53.068165,-4.076803); // Add the coordinates
	var mapOptions = {
		zoom: 8, // The initial zoom level when your map loads (0-20)
		center: myLatlng, // Centre the Map to our coordinates variable
		mapTypeId: google.maps.MapTypeId.ROADMAP, // Set the type of Map
	  }
	var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); // Render our map within the empty div
		
}
google.maps.event.addDomListener(window, 'load', initialise); // Execute our 'initialise' function once the page has loaded. 

Customising this initial code is very straight forward. Start by adding your co-ordinates for your location and experimenting with the zoom parameter. If you view this code in your browser, you should get your initial Google Map centred on your coordinates.

How to add a custom (Retina compatible) Marker icon

Now that our Map is centralised on our coordinates, we need to add a marker for our local business. It’s also worth noting that you can add a hi-dpi/retina compatible images as your marker. To do this, we create a variable for our marker and set it as follows:

var image = new google.maps.MarkerImage(&quot;marker.png&quot;, null, null, null, new google.maps.Size(40,52)); // Create a variable for our marker image.
			
var marker = new google.maps.Marker({ // Set the marker
	position: myLatlng, // Position marker to coordinates
	icon:image, //use our image as the marker
	map: map, // assign the market to our map variable
	title: 'Click to visit our company on Google Places' // Marker ALT Text
});
		

On line 1 above, you’ll notice the marker’s width and height dimensions in the last parameter. When you create your PNG marker, simply ensure that you make it at twice the resolution and it will be displayed correctly for those with a Hi-DPI/Retina display.

How link our marker

If you wish to link your marker to a different URL, like your Google Places listing, you can do so by adding a Listener to your map:

google.maps.event.addListener(marker, 'click', function() { // Add a Click Listener to our marker 
	window.location='http://www.snowdonrailway.co.uk/shop_and_cafe.php'; // URL to Link Marker to (i.e Google Places Listing)
});

Or add an InfoWindow

Instead of linking your marker to an external URL, you might want to add a little ‘Speech Bubble’ style InfoWindow that appears once the marker is clicked. Within this InfoWindow you can also include and style HTML content:

var infowindow = new google.maps.InfoWindow({ // Create a new InfoWindow
  	content:&quot;&lt;h3&gt;Snowdown Summit Cafe&lt;/h3&gt;&lt;p&gt;Railway Drive-through available.&lt;/p&gt;&quot; // HTML contents of the InfoWindow
});

google.maps.event.addListener(marker, 'click', function() { // Add a Click Listener to our marker
  	infowindow.open(map,marker); // Open our InfoWindow
});

Adjusting the Controls

Finally, the last features that I wanted to share were the controls. By using the Maps API, you have the ability to even customise the controls of the map from how far users can zoom in, to disabling Street View. Here’s a full list of the common ones I often adjust or disable:

minZoom: 6, // Minimum zoom level allowed (0-20)
maxZoom: 17, // Maximum soom level allowed (0-20)
zoomControl:true, // Set to true if using zoomControlOptions below, or false to remove all zoom controls.
zoomControlOptions: {
  	style:google.maps.ZoomControlStyle.DEFAULT // Change to SMALL to force just the + and - buttons.
},

// All of the below are set to true by default, so simply remove if set to true:
panControl:false, // Set to false to disable
mapTypeControl:false, // Disable Map/Satellite switch
scaleControl:false, // Set to false to hide scale
streetViewControl:false, // Set to disable to hide street view
overviewMapControl:false, // Set to false to remove overview control
rotateControl:false // Set to false to disable rotate control

If you’re pasting the code as you go, make sure that all of these control features are added within the mapOptions variable alongside the initial zoom control we added earlier.

Putting it Altogether

Here’s my complete code from the tutorial, that I’ve also added as a Gist on GitHub.

Additional Reading

We’re only scratching the surface in this tutorial, with what’s possible in V3 of the Google Maps API. To further develop your map and to see what else is possible, i’d recommend following this tutorial on W3 Schools, and also the code samples on the Google Maps API site.

If you have any tips or recommendations for utilising the Google Maps API, please leave them in the comments below. Thank you for checking out my Google Maps API tutorial.

  • Alex

    Great Outline,
    I was wondering if you knew how to pull through the places information or do you need to rebuild it using the API ?

    Also, i found a lot of users clicked the marker to close it again, so it might be worth having an if statement to make it close on second click.

  • Aaron

    I’ve been through many other Google Maps tutorials online, and most of the tutorials out there do not even work. Not only does this one work, but your example shows the different options we can adjust and provides good explanations along the way. Thank you!! I appreciate your effort.

    • http://www.creare.co.uk/ James Bavington

      Aaron, wow thanks for the amazing feedback. Glad it worked for you.

  • whirrefhirre

    Outstanding tutorial James! Thanks alot!

    1 question: is it possible to add more markers to the map, and how do I do that in that case?

    Thanks in advance!

    • Mile

      the already existing scripts add code: var myMarker2 = new google.maps.Marker({position: new google.maps.LatLng(43.610119, 21.009461), map: map, icon: ‘path/to/your/image2.png’ });

  • gbrowne

    Very helpful. Thankyou so much.

  • pixelBender67

    Nice, I’m trying to write an application that uses the type-ahead feature to locate businesses

  • http://www.yum-my.com.au Yummy2013

    hi guys,
    I need this kind of application:
    – an app that gets my location and shows it with a marker on Google map.
    – this app should have a button and when I click on it:
    It select from my database nearest restaurants (within any range, maybe 1 miles) and show them with markers on the map.
    =>of course restaurants are stored in the database with their names and coordinates (latitude & longitude).

    If anyone ever seen any tutorial to do such an app, please tell me.
    Thx

  • http://yasak.tumblr.com/ Yasin aktimur

    Google disabled shadows new version but i wanna using shadow how can i make ? please help.

    • http://www.creare.co.uk/ James Bavington

      Hey Yasin, Marker Shadows were removed in 3.14 of Google Maps. The immediate way I can think of would be to include the shadow within the custom marker graphic itself. Shame, as if you have different custom markers, you could previously use the same shadow for all, and save on load time.

  • Terry Mardi

    Great tutorial James! How would one change the colours in the map? It would be great if this was included as maps can really stand out then and not look like evry other GMap. Thanks, Terry

    • http://www.creare.co.uk/ James Bavington

      Thanks Terry. You can style the colours of the map using the style array. I’m working on a blog post for this, but I’d recommend checking out Google own Style Wizard: http://gmaps-samples-v3.googlecode.com/svn/trunk/styledmaps/wizard/index.html?utm_medium=twitter and also Snazzy Maps http://snazzymaps.com/

      • Terry Mardi

        Thanks squire, I have it styled rather well now.

        • Mile

          Regards Terry, are you succeeded to add code to change the style of Google Maps if you did send the whole code, thanks in advance

          • Terry Mardi

            Hello Mile, I used the links that James provided above, most notably snazzy maps.

            James, any reason the logo fails to show if I change it from the default one in your example? Even if I use the same file name for the logo it will not show.

  • Ari

    Can I add more places? If there are two areas of my webpage, left side is list of some places. Then If I click a place name, right side will show up the map. Anyone can help me?

    • Mile

      var myMarker2 = new google.maps.Marker({position: new google.maps.LatLng(43.610119, 21.009461), map: map, icon: ‘path/to/your/image2.png’ });

  • Mile

    excellent tutorial, just one more detail: how to add tyled Maps JSON to function initialise, I tried everything but the code supplied does not work after adding the script. A big thank you for your reply

  • NotApplicable

    This doesn’t work. I keep getting a reference error saying google is not defined. Please, update this with the correct code.

    • http://www.creare.co.uk/ James Bavington

      Hi, the code works perfectly fine for me, do you have an online example of your integration so that I can help you to get it working?

  • Conor

    Great tutorial, would you know how to change the latitude and longitude if I wanted to call the map from a different part of the code without having to create a new map object. In other words can I reuse the map created but change the latitude and longitude .?

  • bhushan

    Good tutorial. thank you :-)

  • Rupesh Singh

    you’re using

    google.maps.event.addListener(marker, ‘click’, function() { // Add a Click Listener to our marker

    infowindow.open(map,marker); // Open our InfoWindow

    });
    similarly
    google.maps.event.addListener(infowindow, ‘closeclick’, function() { // Add a Click Listener to our marker

    openinfowindow.open(map,marker); // Open our InfoWindow

    });
    suppose while loading the map we are showing the window i.e. openinfowindow and after performing ‘click’ event i want to close openinfowindow and show infowindow and then after performing ‘closeclick’ event, wanna show openinfowindow.
    Above code works for one marker but if we have multiple marker then it fails to load it….. what would be the solution?

  • Rupesh Singh

    you’re using

    google.maps.event.addListener(marker, ‘click’, function() { // Add a Click Listener to our marker

    infowindow.open(map,marker); // Open our InfoWindow

    });
    similarly
    google.maps.event.addListener(infowindow, ‘closeclick’, function() { // Add a closeclick Listener to our marker

    openinfowindow.open(map,marker); // Open our InfoWindow

    });
    suppose while loading the map we are showing the window i.e. openinfowindow and after performing ‘click’ event i want to close openinfowindow and show infowindow and then after performing ‘closeclick’ event, wanna show openinfowindow.
    Above code works for one marker but if we have multiple marker then it fails to load it….. what would be the solution?

    • Rupesh Singh

      var infowindow = new google.maps.InfoWindow({
      content: content,
      marker:marker,
      maxWidth: 300,
      image:image,
      id:vehicleNo
      });
      var openinfowindow = new google.maps.InfoWindow({
      content: contentone,
      marker:marker,
      maxWidth: 300,
      image:image,
      id:vehicleNo
      });
      google.maps.event.addListener(marker,’click’, (function(marker,content,infowindow){
      return function() {
      openinfowindow.close();
      infowindow.setContent(content);
      infowindow.open(map,marker);
      };
      })(marker,content,infowindow));

      google.maps.event.addListener(infowindow,’closeclick’,function(){
      openinfowindow.setContent(contentone);
      openinfowindow.open(map,marker);
      });

  • JF Picard

    I noticed that the controlers are broken in you example (the map in the Putting It All Together section). That’s because of the img { max-width: 100%; } in the style of your site. I just had the same problem on my side. You need to remove this in the map, add: #map-canvas img ( max-width: initial; } to cancel the max-width for the images in the map.
    I think Google is using a sprite for the images of the controlers. The max-width breaks it.

    • http://www.creare.co.uk/ James Bavington

      Thanks JF Picard, I’ve also noticed this too in the past and added the same CSS.

  • andy

    This is the best tutorial I have found. I am not a programmer but I managed to make a map with markers work on my site. Great, but now the navigation for the site on the map page doesn’t work and I get an error message when uploading using dreamweaver
    public_html:css:my.css – same – not transferred
    – error occurred – Access denied. The file may not exist locally, may be open in another program, or there could be a local permission problem.

    Any help would be fantastic.
    Thanks

    • http://www.creare.co.uk/ James Bavington

      Hey Andy, glad you found the tutorial helpful and managed to get this working for your website. I’m unsure on the issues you’re having with your server in Dreamweaver, as I do not use this application.

      • andy

        Thanks James. The navigation problem turned out to be a fault with the layout CSS. All hunky dory now

  • Rachel

    This helped so much. Thanks

  • Hoàng Trọng Hùng

    hi,please help me add a button on marker
    I mine,if i click to marker, it display a small button on there
    thank you very much

  • Bruno Vaz

    Hi! I’m looking for a widget that makes it possible for users to create routes (by right clicking, setting a start and end point, and putting waypoints). I’m developing an application and the users should be able to create the route, and then my system would retrieve the informations of the route. But I can’t seem to find it it’s actually possible for the users to create routes via a frame