Add a Custom Google Map to your Website using the Google Maps Javascript API

By Andrew Gehman google maps api

If you’ve built a website, there’s a pretty good chance that you’ve used a Google Map, as they’re simple enough to use and beneficial to the end user. It’s as easy as apple pie to copy the Google Map embed code and paste it into your website in order to add a custom Google map.  If you’re using WordPress, you can also include a Google Map with a plugin.

But what if you’d like a little more customization? Here’s how you can include a map yourself using the Google Maps API.

First, a little clarification. There isn’t a single Google Maps API, but rather a collection of Google Maps APIs. We’re talking about adding a map to a website, so we are going to be using the Google Maps Javascript API.

Ok, let’s get started.

Let’s say you are working on a basic HTML or php file. We’ll create an empty div element in that file to hold the map and give it an ID, like ‘map.’

<div id="map"></div>

In your CSS, you will need to give the div a height. For example, if you gave your div an ID of ‘map,’ you’d write:

#map {height: 600px;}

Of course, you’ll want to substitute the 600px for whatever height best suits your needs.You may also want to do the same for the width, again, depending on your needs and your layout.

The Google Maps API documentation suggests also adding a height to the HTML and body tags to ensure that any inherited divs are not sized at 0 x 0 pixels. You may or may not not need to do this depending on your website’s style or theme, but it’s good to keep in mind just in case.

html, body { height: 100%; margin: 0; padding: 0; }

Before we do anything else, we’ll need to connect to the Google Maps Javascript API. To do this we’ll drop this script just before our closing body tag of our document.

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>

Note: While the Google Maps Javascript API will currently work without an API key, the documentation recommends it. You can acquire a key by visiting the Google Maps Javascript API documentation and following the instructions to get a key. It’s free, and just takes a few minutes.  

Of course, if you are using an API key, you’ll want to replace  YOUR_API_KEY with your actual API key. If you choose not to use one, you can remove the key=YOUR_API_KEY section from the script, so it’ll read:

<script src="https://maps.googleapis.com/maps/api/js?&callback=initMap" async defer></script>

Take notice of the ‘callback=initMap’ at the end of the url. This callback function will trigger the initMap function in our Javascript code, which we will write shortly.

For the purposes of this example, we’ll place our custom Google Map code in a separate Javascript file called map.js.  Just above the Google Maps API script in your HTML file, add a link to your Javascript file. Be sure to replace the src attribute value with the location of your own file.

<script type='text/javascript' src='js/map.js'></script>

Now, we’ll code a very basic map in Javascript. First, create a variable for the map, and a function called initMap() to run when we initialize the map (remember that callback=initMap from our Google API script? This is that initMap function it will run).

Note: Saving the new map object in a variable is not strictly necessary at this point, but we will use it later for some advanced features, so we’ll just create it now.

When the initMap function runs, we create a new map object. You can see we use the getElementById method to reference our previously created div with the ID of ‘map’. If you chose to name your ID something other than ‘map,’ you’ll want to replace ‘map’ with whatever ID you used.

var map;
function initMap(){
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 40.0519752, lng: -76.314270999999},
    zoom: 15 // typical is usually 8 or 9
  });
}// end initMap function

The Google Maps API has a lot of options, but only center and zoom are required.

Zoom levels range between 0 (which is the full view of the earth) and 20 (which is building level). A typical zoom on a Google Map is usually around 8 or 9. I’ve chosen a zoom of 15 for this example to show a map with a little more detail.

For the center, you’ll want to set latitude and longitude. So, how do you find that info? Go to Google Maps, right click on a location on the map that you wish to be the center of your map, and select “What’s here?”

wheres-here

A small card will appear at the bottom of the map and you’ll see the latitude and longitude listed there at the bottom. You can use those settings for your center.

google-maps-card

Now, if we’ve included our Javascript file, added the necessary CSS, connected to the Google Maps API, placed a div tag with an id=”map” and have done everything correctly, we should see our Google Map displayed on our site.

Pretty cool, but what we have is pretty basic. What if we want to add some more customization? Let’s look at some additional options.

scrollwheel – One thing I find annoying is scrolling down a page on a website, coming across a Google Map, and suddenly the map starts zooming and the page stops scrolling. You can prevent this behavior by setting scrollwheel: false on your map object. (True is the default) And don’t worry, you’ll still be able to zoom in and out using the zoom control.

zoomControl – These are the (+) and (-) buttons, enabled by default, that allow you to zoom in and out. Set the zoomControl to false to remove them.

zoomControlOptions – By default, the zoom controls appear at the bottom right corner of the map. You can change the position to any of the other corners, or have it centered along any of the sides. For example, adding this code will vertically center the controls along the left side of the map.

zoomControlOptions: {
  position: google.maps.ControlPosition.LEFT_CENTER
}

For all of the position controls see the documentation:

https://developers.google.com/maps/documentation/javascript/controls#ControlPositioning

streetViewControl – enabled by default at the bottom right of the map, this control is the “Pegman icon” (as Google calls it) that users can drag and drop onto the map to see a street view. To remove it, set the option to false.

Similar to the zoom control, the position of this control can be moved using the same control positioning. The code below would place it at the top left.

streetViewControlOptions: {
  position: google.maps.ControlPosition.LEFT_TOP
}

fullscreenControl – this is a feature that is disabled by default. Use fullscreenControl: true to enable it. As you might expect, it gives you a control to allow the user to put the map in fullscreen mode.

Now, if you put it all together, this is what our Javascript file with our initMap function will look like.

var map;

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 40.0519752, lng: -76.314270999999}, // lat/long of center of map
    zoom: 15, // 8 or 9 is typical zoom
    scrollwheel:  false, // prevent mouse scroll from zooming map.
    mapTypeControl: true, //default
    mapTypeControlOptions: {
      style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
      position: google.maps.ControlPosition.BOTTOM_CENTER
    },
    zoomControl: true, //default
    zoomControlOptions: {
      position: google.maps.ControlPosition.LEFT_CENTER
    },
    streetViewControl: true, //default
    streetViewControlOptions: {
      position: google.maps.ControlPosition.LEFT_TOP
    },
    fullscreenControl: true
  });
}

If all is right, we should have a Google Map, with position controls customized with the Google Maps Javascript API, displayed on our website. We have map controls as a horizontal bar displayed at the bottom center, zoom control moved to the left center, street view control moved to the top left, and full screen control enabled (shown at the top right).

Adding the Custom Google Map to Your WordPress Theme

The major difference here, is how we are going to load our Javascript files, and where we put our <div id=”map”></div> code. You can put the #map div tag in a template file, code it into sidebar.php, or even in the content editor of a page or post.

As for the script files, rather than sticking them in the header or footer of our theme, we’ll load them using the wp_enqueue_script function in our functions.php file.

The other issue we’ll address along the way is loading those Javascript files only on the page or pages with a map.

We’ll again use a file called map.js and the code from the previous example to create our map.

var map;

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 40.0519752, lng: -76.314270999999}, // lat/long of center of map
    zoom: 15, // 8 or 9 is typical zoom
    scrollwheel:  false, // prevent mouse scroll from zooming map.
    mapTypeControl: true, //default
    mapTypeControlOptions: {
      style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
      position: google.maps.ControlPosition.BOTTOM_CENTER
    },
    zoomControl: true, //default
    zoomControlOptions: {
      position: google.maps.ControlPosition.LEFT_CENTER
    },
    streetViewControl: true, //default
    streetViewControlOptions: {
      position: google.maps.ControlPosition.LEFT_TOP
    },
    fullscreenControl: true
  });
}

Now, let’s enqueue our files. we’ll need to load our map.js file, as well as the Google Maps API file. The Google Maps API file shown below does not include an API key. If you are using one, it will be in this format:

https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap

And again, you’ll want to replace YOUR_API_Key with the API key you get from Google.

Your theme’s functions.php file will likely already include a wp_enqueue_scripts hook that loads any scripts and styles. If so, you can enqueue you scripts at the bottom of that function. If not, you can create your own function and ‘add_action’ hook.

function my_theme_load_scripts() {
  wp_enqueue_script('map', get_template_directory_uri() . '/js/map.js');
  wp_enqueue_script('googlemapsapi', 'https://maps.googleapis.com/maps/api/js?&callback=initMap');
}
add_action('wp_enqueue_scripts', 'my_theme_load_scripts');

Now, let’s say we only want to load these files on one page on your WordPress site. We’ll use a simple conditional to prevent these scripts from loading on every page.  Let’s assume our map is on a page called “contact.”  We’ll use the WordPress is_page() conditional and pass in the name of the page.

function my_theme_load_scripts() {
  if ( is_page(‘contact’) ) {
    wp_enqueue_script('map', get_template_directory_uri() . '/js/map.js');
    wp_enqueue_script('googlemapsapi', 'https://maps.googleapis.com/maps/api/js?&callback=initMap');
  }
}
add_action('wp_enqueue_scripts', 'my_theme_load_scripts');

We should now have our map loading on our contact page, and the Javascript files should only load on the contact page and not every page on your WordPress site.

Add a Custom Animated Marker to your Google Map

In the previous two sections we showed you how to create a custom map for your website using the Google Maps Javascript API, and how to add it to your WordPress theme using your theme templates and functions.php. Now, we’re going to add a sweet custom animated marker to the map.

You may have seen this effect before on other Google Maps. A ‘pin’ drops down and lands on the desired location of the map. We’ll do the same, but with the added twist of our own custom image.

So, if you’ve been following along, you may recognize this Javascript code we created:

var map;
function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 40.0519752, lng: -76.314270999999}, // lat/long of center of map
    zoom: 15, // 8 or 9 is typical zoom
    scrollwheel:  false, // prevent mouse scroll from zooming map.
    mapTypeControl: true, //default
    mapTypeControlOptions: {
      style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
      position: google.maps.ControlPosition.BOTTOM_CENTER
    },
    zoomControl: true, //default
    zoomControlOptions: {
      position: google.maps.ControlPosition.LEFT_CENTER
    },
    streetViewControl: true, //default
    streetViewControlOptions: {
      position: google.maps.ControlPosition.LEFT_TOP
    },
    fullscreenControl: true
  });
}

This initMap function creates our map object and adds a bit of simple customization to the the controls. It displays on the page in the element with the id attribute set to “map.”

At the bottom of our initMap function we’ll create a marker object and add our custom options.

var marker = new google.maps.Marker({
  position: {lat: 40.0519752, lng: -76.314270999999}, // lat/long of marker
  map: map,
  animation: google.maps.Animation.DROP, // drops marker in from top
  title: 'MIND Deveopment and Design', // title on hover over marker
  icon: {
    url: 'http://YOURWEBSITE/wp-content/themes/YOURTHEME/img/mind-map-marker.png',
    scaledSize: new google.maps.Size(75, 120)
  }
});

So, what’s going on here? First, we are creating our map marker object and saving it as a variable called ‘marker’.  Just like when we created the map object, we don’t strictly need to save it to a variable at this point to make it work, but we’ll do so now as it may come in handy later.

For the position, we’re using the same latitude and longitude that we used for the center of the map object.

For the map option, we want to refer to the map we’ve just created, so we’ll set it to that ‘map’ variable we created when creating the map object.

Now for the fun stuff…the animation.  If we stop now we’ll have a nice marker on our map, but there won’t be any cool movement.  So, we’ll set the animation option to google.maps.Animation.DROP.  This ‘drops’ the marker in from the top of the map when it’s loaded.

Currently, the only other supported animation option is BOUNCE, which makes the marker repeatedly ‘hop’ like a pogo stick.

We’ve also added a title option. This allows you to specify text that will be displayed when you hover over the marker, such as the name of your company.

Finally, we add the custom marker icon. This is where you can really get creative and choose your own custom image as a marker. Here you set the url to the location of the image file you wish to use. If you need to scale the image, use the scaledSize option and pass it the scaled width and height of the image in pixels. If the image size is fine, simply omit this option.

So, when it’s all finish, our code will look like this:

var map;
function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 40.0519752, lng: -76.314270999999}, // lat/long of center of map
    zoom: 15, // 8 or 9 is typical zoom 
    scrollwheel:  false, // prevent mouse scroll from zooming map. 
    mapTypeControl: true, //default
    mapTypeControlOptions: {
        style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
        position: google.maps.ControlPosition.BOTTOM_CENTER
    },
    zoomControl: true, //default
    zoomControlOptions: {
        position: google.maps.ControlPosition.LEFT_CENTER
    },
    streetViewControl: true, //default
    streetViewControlOptions: {
        position: google.maps.ControlPosition.LEFT_TOP
    }, 
    fullscreenControl: true
  });

  var marker = new google.maps.Marker({
  position: {lat: 40.0519752, lng: -76.314270999999}, // lat/long of marker
  map: map,
  animation: google.maps.Animation.DROP, // drops marker in from top
  title: 'MIND Deveopment and Design', // title on hover over marker
  icon: {
    url: 'http://YOURWEBSITE/wp-content/themes/YOURTHEME/img/mind-map-marker.png',
    scaledSize: new google.maps.Size(75, 120)
  }
});
}

Now, we should have a map with a custom marker that drops in from the top when the map is loaded.

See the Pen mVaMEE by Andrew Gehman (@AndrewGehman) on CodePen.

View Comments

One response to “Add a Custom Google Map to your Website using the Google Maps Javascript API”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Are You Ready To Do More with Mind?

Click the link below to get started!

Work With Mind