Location is becoming a very popular topic day by day, and Google is one of the main game changers in this area. Most websites have a contact page with Google Maps showing the location of the business. This is the simplest usage of the Google Maps JavaScript API. There are also other advanced usages of it to show different information on maps. This whole book contains multiple usage recipes on the Google Maps JavaScript API, from beginner to advanced topics. There are different parts that make up the Google Maps JavaScript API such as the raster/vector layers, controls, events, and services, which are all covered in the following chapters.
There are both open source and commercial alternatives to the Google Maps JavaScript API, such as OpenLayers, Leaflet, Bing Maps, MapQuest, and Here Maps (formerly, Nokia Maps), but the Google Maps JavaScript API has great support in base maps, satellite images, and the API itself. For example, the API can be used to show only one location or all the data of a government agency on a map.
The Google Maps JavaScript API is not a free tool to show maps, but its free usage limit is enough for most developers. There is a limit of 25,000 map loads per day per site, which is counted when a map is initialized on a web page.
When you work with mapping applications, creating a map is the most important task you can do. The map is the main part of the application with which the users interact and where all the visualization occurs. This part may seem trivial, but all of the following chapters rely on this part of the application.
This recipe will guide you through the process of creating a simple map view on a web page.
Note
As described in the preface, we need a web server to host our HTML, JavaScript, and CSS files and a web browser to interpret them on the client side.
As already stated, the Google Maps JavaScript API works with HTML, CSS, and JavaScript code. So a text editor with HTML, JavaScript, and CSS handling capabilities would be a good friend to have on hand while exploring this book.
For Mac users, there are lots of commercial or free text editors such as TextWrangler, BBEdit, Sublime Text, or WebStorm. They all handle HTML, JavaScript, and CSS beautifully.
For Windows users as well, there are different text editors, but Notepad++ is the most used and recommended one.
Choosing an editor depends on your computer usage habits, so there is no exact solution or recommendation to users to select a particular type of editor. Everyone has different perceptions that affect these choices.
You can find the source code at Chapter 1/ch01_simple_map.html
.
Tip
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Here are the steps we will use to create our first map using the Google Maps JavaScript API.
Create a new empty file named
map.html
and insert the following code block into it. This block is required for every app that uses the Google Maps JavaScript API. You must insert your Google Maps JavaScript API key into the URL in the following code.<!DOCTYPE html> <html> <head> <!-- Include Google Maps JS API --> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=INSERT_YOUR_MAP_API_KEY_HERE&sensor=false"></script>
Tip
Please ensure that you have your Google Maps JavaScript API key from the Google APIs Console (http://code.google.com/apis/console) and replace it with
YOUR_API_KEY
. If you do not change that part of the code, your map cannot be seen due to Google's API rules. Also make sure to change the API key before publishing your map's document on another location or production environment.The following part is required in order to place the map where needed. In the
<head>
section, add the HTML styling code to create a map that is 800 px in width and 500 px in height with the<style>
element as follows:<style type="text/css"> #mapDiv { width: 800px; height: 500px; } </style>
Add the following JavaScript lines to the code to run with the Google Maps JavaScript API. Do not forget to define the
map
object outside the function in order to access it from every part of the code.<!-- Map creation is here --> <script type="text/javascript"> //Defining map as a global variable to access from //other functions var map; function initMap() { //Enabling new cartography and themes google.maps.visualRefresh = true; //Setting starting options of map var mapOptions = { center: new google.maps.LatLng(39.9078, 32.8252), zoom: 10, mapTypeId: google.maps.MapTypeId.ROADMAP }; //Getting map DOM element var mapElement = document.getElementById('mapDiv'); //Creating a map with DOM element which is just //obtained map = new google.maps.Map(mapElement, mapOptions); }
Add the following lines to finish the code. This part defines the
<html>
tags where the map will be added and when to initialize the map.google.maps.event.addDomListener(window, 'load', initMap); </script> </head> <body> <b>My First Map </b> <div id="mapDiv"></div> </body> </html>
Enter the URL of your local server, where your
map.html
file is stored, in your favorite browser and take a look at the result. You will see a map with navigation controls at the top-left corner and the base map control at the top-right corner.
As evident from the preceding screenshot, we have created our simple map with the Google Maps JavaScript API.
Let's start examining the code step by step. First, the HTML5 document is defined with the code <!DOCTYPE html>
. Then the <html>
and <head>
tags are added.
Before the <style>
element, the Google Maps JavaScript API is included as a reference using the <script>
element as follows:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key= INSERT_YOUR_MAP_API_KEY_HERE&sensor=false"> </script>
Then a new <script>
tag is added to the code. After the <head>
section, the <body>
section starts.
<body>
The following line of code listens to the load of the document. This event triggers the initMap
function when the page is fully loaded. This prevents unpredictable behaviors that would arise from DOM and its related elements.
google.maps.event.addDomListener(window, 'load', initMap);
Finally, we have the HTML tags to create our page. The <div>
element with id="mapDiv"
is the place where our map will be shown. This element gets its style from the CSS tags defined previously, which has a width of 800 px and a height of 500 px.
Note
The styling of the mapDiv
element is directly related to CSS rules that can be found on the W3Schools website (http://www.w3schools.com/css) in detail.
As stated previously, the main JavaScript code that initializes the map will be explained in detail. First, the map
object is defined as a global object to access the map from every function that is added later.
var map;
Then the initMap
function is defined as follows:
function initMap() { }
Before creating a map, the following code is called to change the map's theme to the latest one that was announced at Google IO 2013 in May 2013. This theme is the new look used in the new Google Maps. Both the cartography and styles of components are fresh and up to date; however, using this new feature is optional. If you don't use the following line of code, you'd use the old theme.
google.maps.visualRefresh = true;
Then, the map options would be defined as follows:
var mapOptions = { center: new google.maps.LatLng(39.9078, 32.8252), zoom: 10, mapTypeId: google.maps.MapTypeId.ROADMAP };
There are three important parameters for the map options.
center
: This is the center of the map in latitudes and longitudes. The previously defined parameters are the coordinates of Ankara, Turkey. If you don't know how to get the coordinates of a place, refer to the recipes given in Chapter 5, Understanding Google Maps JavaScript API Events.zoom
: This parameter is an integer that defines the level in which the map is shown. Google Maps have zoom levels from 0 (world level) to 21+ (street level). Users see more details but less area when the zoom level increases.mapTypeId
: This parameter defines the types of base maps shown on the map. The details of this parameter are given in the later recipes of this chapter.
Before creating the map object, it is necessary to get the div
element to where the map will be shown. This is done via the classic DOM method, getElementById
, as follows:
var mapElement = document.getElementById('mapDiv');
Finally, we have everything in place to create a map object:
map = new google.maps.Map(mapElement, mapOptions);
This code gets the mapElement
and mapOptions
objects to create the map. The first parameter is the div
element where the map will be placed and the other is the mapOptions
object that holds the starting parameters of the map. The preceding line of code creates the map with the given options at the given div
element and returns the map object to interact with the map later.
Note
This recipe is the simplest one in the book but also the most important one to get started with the Google Maps JavaScript API. There are lots of parameters or options of the map, which will be discussed in the later chapters and recipes.
Also remember that in the following recipes, the basic code will not be included in the book in order to provide you with more recipes. Only those lines of code that are changed or required are given in the following chapters and recipes, but you will have access to the complete code with all the omitted lines from the Packt Publishing website (http://www.packtpub.com/support)
Applications can be mapped in different formats. Some of them show a map after a mouse click or an event, and some of them are shown directly in fullscreen mode.
This recipe will show you how to create a fullscreen map that will be used both in web or mobile applications.
As stated before, some recipes will show only the changed lines in the code in order to make way for more recipes. This recipe is the modified version of the previous recipe, Creating a simple map in a custom DIV element.
You can find the source code at Chapter 1/ch01_full_screen_map.html
.
You can easily create a simple fullscreen map by following the given steps:
Let's start by creating a new empty file named
full_screen_map.html
. Then, copy all of the code in the previous HTML file (map.html
) and paste it into this file.Find the following lines of code in the new file:
<style type="text/css"> #mapDiv { width: 800px; height: 500px; } </style>
Add the following lines and change them according to the new values stated. The
width
andheight
values are changed to100%
in order to make the map full screen in the browser viewport. Also, the margin value of thebody
element is changed to0
to remove all the spaces around the map.<style type="text/css"> html { height: 100% } body { height: 100%; margin: 0; } #mapDiv { width: 100%; height: 100%; } </style>
Enter the URL of your local server, where your
full_screen_map.html
file is stored, in your favorite browser and take a look at the result. You will see the map with navigation controls at the top-left corner and the base map control at the top-right corner that fills the entire browser area.
Thus we have successfully created a simple fullscreen map.
The Google Maps JavaScript API uses the div
component of the HTML standard to show the map. The div
component gets its style and properties from CSS rules, which are defined at the top, in the <head>
element. The width
and height
attributes of #mapdiv
show that the div
component will fill the entire browser space. You can easily modify these width
and height
properties to change the map dimensions according to your needs.
The size of the map is directly related to CSS styles, and there is no direct relation between the map size and the Google Maps JavaScript API. The DIV
element that holds the Google Maps JavaScript API's base maps and overlays is just a blank container, and as the DIV
elements get larger, so does your map.
Mobile devices are getting more popular nowadays; all the popular websites are preparing their mobile apps or sites in order for people to access them anywhere. Mapping applications have also become more popular since accessing the location of a device with proper APIs was introduced in HTML5.
In this recipe, we will prepare a mapping application that will run on mobile browsers in full screen, and it will zoom to the location of a device with the help of the W3C Geolocation API. This API is also accessible from desktop browsers to get your location.
This code will be run on a mobile device or simulator, so make sure that your code will be accessible from your mobile device or simulator. In this recipe, I suggest you upload the code to a hosting server or website so that it could be accessed easily from your mobile device or simulator.
You can find the source code at Chapter 1/ch01_mobile_map.html
.
If you want to create a map that is optimum for mobile devices, you should follow the given steps:
Let's start by creating a new empty file named
mobile_map.html
. Then, copy all of the code in the HTML file (map.html
) that was introduced in the Creating a simple map in a custom DIV element recipe, and paste it into the new file.Find the following lines of code in the new file:
<!-- Include Google Maps JS API --> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=INSERT_YOUR_MAP_API_KEY_HERE&sensor=false"> </script>
Insert the following line before the previous code block. This line tells mobile browsers that the current web application is designed for mobile devices:
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
Add the following
CSS
styles in order to make the map fullscreen.<style type="text/css"> html { height: 100% } body { height: 100%; margin: 0; } #mapDiv { width: 100%; height: 100%; } </style>
Then, add the following code block after creating the
map
object. This code block will check whether your browser supports the Geolocation API and sets the center of the map according to the coordinates of the device.if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var lat = position.coords.latitude; var lng = position.coords.longitude; //Creating LatLng object with latitude and //longitude. var devCenter = new google.maps.LatLng(lat, lng); map.setCenter(devCenter); map.setZoom(15); }); }
Upload your file to a proper hosting site and check this URL on your mobile device or simulator. You will be asked whether to allow the reading of your location or not. If you allow it, you will see the map of your location.
This is how we achieve the goal of creating a simple map for mobile devices.
The <meta>
tags are used by browsers and search engines, and they are not visible to the users. They help browsers know how to behave. In our case, the following <meta>
tag is used to tell browsers that the current website is optimized for mobile browsers:
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
This <meta>
tag solves zooming problems when the user pinches in or out, because pinching in or out should zoom the map in or out respectively and not the document itself.
In order to get the device location, the W3C Geolocation API implemented by browsers is used. There is a navigator namespace in the HTML5 standard, and the Geolocation subnamespace is checked first if the browser has support for the Geolocation API. If navigator.geolocation
returns an object, we can get the coordinates with the help of the getCurrentPosition
function. The callback function gets the latitude and longitude of the device and creates the google.maps.LatLng
object. Then, the setCenter
method of the map
object is triggered with the devCenter
object that was created before. This will change the center of the map according to the device location.
The last line of the callback function is used to set the zoom level of the map. This can be changed according to your needs.
The HTML5 standard is still in progress, and there can be changes in the W3 Geolocation API. If you want to get more information about geolocation, refer to the W3C documentation site (http://dev.w3.org/geo/api/spec-source.html).
Until this recipe, the map has been interactive within itself. Users can zoom in/out, drag the map, change the user interface, or enable/disable mouse interactivity. If you want to play with the map outside of it, you should access the map and change the properties you want, or you can change the properties programmatically in different cases. Changing map properties programmatically is one of the important parts of the Google Maps JavaScript API. In most mapping applications, a user searches for a place, and the application should focus on that point on the map. This is possible with the map
object's functions. There are lots of map functions, but we will cover only the most used ones.
In this recipe, we will create a mapping application that a user can interact with outside the map. Buttons are used in order to interact with the map.
Before you continue, a map object must be created in order to interact with it. If a map object is not defined, you will get an error. These kinds of problems occur due to JavaScript's asynchronous behavior in most cases.
You can find the source code at Chapter 1/ch01_interaction_map.html
.
Changing the map properties is quite easy if you follow the given steps:
Let's start by creating a new empty file named
interaction_map.html
. Then, copy all of the code in the HTML file (map.html
) that was introduced in the Creating a simple map in a custom DIV element recipe and paste it into the new file.Add the following functions after the
initmap()
function. These functions are called by the buttons defined in HTML, which are used to interact with the map. Functions are explained later in this recipe.function zoomToIstanbul () { var istanbul = new google.maps.LatLng(41.0579,29.0340); map.setCenter(istanbul); } function zoomToStreet () { map.setZoom(18); } function disableDrag () { map.setOptions ({ draggable: false }); } function setMaxZoom () { map.setOptions ({ maxZoom: 12 }); } function setMinZoom () { map.setOptions ({ minZoom: 5 }); } function changeUI () { map.setOptions ({ disableDefaultUI: true }); } function disableScroll () { map.setOptions ({ scrollwheel: false }); }
Next, add the following function to listen to the click events of the buttons defined in the HTML code in step 5.
function startButtonEvents () { document.getElementById('btnZoomToIst' ).addEventListener('click', function(){ zoomToIstanbul(); }); document.getElementById('btnZoomToStr' ).addEventListener('click', function(){ zoomToStreet(); }); document.getElementById('btnDisableDrag' ).addEventListener('click', function(){ disableDrag(); }); document.getElementById('btnMaxZoom' ).addEventListener('click', function(){ setMaxZoom(); }); document.getElementById('btnMinZoom' ).addEventListener('click', function(){ setMinZoom(); }); document.getElementById('btnChangeUI' ).addEventListener('click', function(){ changeUI(); }); document.getElementById('btnDisableScroll' ).addEventListener('click', function(){ disableScroll(); }); }
The
startButtonEvents
function must be called on initializing the map, so the following line of code is added:startButtonEvents();
Then, add the following HTML lines of code inside the
<body>
tag. These are the<button>
tags to be shown on the web page. Eachbutton
element listens for the click event to fire the related function.<input id="btnZoomToIst" type="button" value="Zoom To Istanbul"> <input id="btnZoomToStr" type="button" value="Zoom To Street Level"> <input id="btnDisableDrag" type="button" value="Disable Drag"> <input id="btnMaxZoom" type="button" value="Set Max Zoom to 12"> <input id="btnMinZoom" type="button" value="Set Min Zoom to 5"> <input id="btnChangeUI" type="button" value="Change UI"> <input id="btnDisableScroll" type="button" value="Disable Scroll Zoom">
Enter the URL of your local server, where your
interaction_map.html
file is stored, in your favorite browser and take a look at the result. You will see the map with buttons at the top. Each button triggers a different function to interact with the map.
As a result of the recipe, we can change map properties programmatically.
Each JavaScript function defined previously is used to change the different sides of the map. The ones most used are to change the center and zoom level of the map. Most of the time, people just move from one location to another on a map. For example, if you are showing the locations of a coffee chain, the map should focus on each of the locations of the coffee shops. The following code creates a google.maps.LatLng
object that will be the input of the setCenter()
function. The 41.0579
and 29.0340
values are the latitude and longitude of Istanbul, Turkey respectively. You will replace these coordinate values with your own coordinate values to change the center of the map. This function will only change the center of the map, not the zoom level.
var istanbul = new google.maps.LatLng(41.0579,29.0340); map.setCenter(istanbul);
If you want to zoom in or out of the map in order to cover/show an area, you should also play with the zoom value. For example, your coffee shop location at zoom level 6 cannot provide effective guidance to your customers. It should at least be at level 15 or more to see the street names and the exact location. This can be done with the following code:
map.setZoom(18);
In some cases, you don't want users to interact with the map, such as fixing the map location, by disabling mouse drags or wheel scrolls. These are some examples of the google.maps.MapOptions
object's properties. These properties are directly related to the properties of the map. If you want to change one or more properties of the map, you should create a JSON object and call the following map function:
map.setOptions ({ draggable: false, maxZoom: 12 });
With the setOptions()
function, you can also enable or disable the default controls, but this will be reviewed in Chapter 4, Working with Controls. You can set one or more properties with the setOptions()
function. You can find short explanations with comments next to the properties:
map.setOptions ({ draggable: false, //Disables the map drag maxZoom: 12, //Sets maximum zoom level minZoom: 5, //Sets minimum zoom level disableDefaultUI: true, //Removes the default controls scrollwheel: false //Disables the mouse scroll wheel });
Tip
Accessing a map object
Be aware of defining a map object as a global object in order to access it anywhere. This can be a problem in some cases while writing in JavaScript. Please check the following link to get more information on JavaScript and Scopes : http://coding.smashingmagazine.com/2009/08/01/what-you-need-to-know-about-javascript-scope/.
Base maps are one of the most important parts of the process of mapping the APIs. Base maps show the roads, satellite images, or terrains, which can be used for different situations. For example, a road map can be suitable for showing the location of your coffee shop, but a satellite image cannot. Satellite images can also be suitable for showing parcel information to check whether they are drawn correctly. The Google Maps JavaScript API has four different base maps such as ROADMAP, SATELLITE, HYBRID, and TERRAIN. All of these base maps can be seen in the following screenshot wherein they can be compared to each other.

In this recipe, we will go through the Google Maps base maps and learn how to change them programmatically.
In this recipe, we will use the JavaScript arrays in order to make the input parameters of a function readable. I suggest you check Google for the JavaScript arrays if you don't have any experience.
You can find the source code at Chapter 1/ch01_base_map.html
.
If you follow the given steps, you can change the base maps of your map.
Let's start by creating a new empty file named
base_map.html
. Then, copy all of the code in the HTML file (map.html
) that is introduced in the Creating a simple map in a custom DIV element recipe and paste it into the new file.Add the following function after the
initMap()
function. It will listen to the click events of the buttons added to the HTML code in step 4. It simply sets the base map according to the IDs of the buttons.function startButtonEvents () { document.getElementById('btnRoad' ).addEventListener('click', function(){ map.setMapTypeId(google.maps.MapTypeId.ROADMAP); }); document.getElementById('btnSat' ).addEventListener('click', function(){ map.setMapTypeId(google.maps.MapTypeId.SATELLITE); }); document.getElementById('btnHyb' ).addEventListener('click', function(){ map.setMapTypeId(google.maps.MapTypeId.HYBRID); }); document.getElementById('btnTer' ).addEventListener('click', function(){ map.setMapTypeId(google.maps.MapTypeId.TERRAIN); }); }
The
startButtonEvents
function must be called upon initializing the map, so the following line of code is added after the map is initialized.startButtonEvents();
Then, add the following HTML lines of code before the map's
div
element. These are the HTML buttons to change the base map:<input id="btnRoad" type="button" value="RoadMap"> <input id="btnSat" type="button" value="Satellite"> <input id="btnHyb" type="button" value="Hybrid"> <input id="btnTer" type="button" value="Terrain">
Enter the URL of your local server, where your
base_map.html
file is stored, in your favorite browser, and take a look at the result. You will see the map with buttons at the top. Each button changes the base maps according to their names.
As shown in the preceding screenshot, you can easily change the base maps that are provided by Google.
Most of the magic is done by the API itself; you just choose the map type you want to switch to.
These map types are predefined, but there is a possibility to add your own base maps or styled maps to the API and switch to them. Adding your own base maps or styled maps are introduced in Chapter 2, Adding Raster Layers.
You can also define the starting base map at the mapOptions
object as follows:
var mapOptions = { center: new google.maps.LatLng(39.9078, 32.8252), zoom: 10, mapTypeId: google.maps.MapTypeId.TERRAIN };
After changing the map options, your map will be opened with the TERRAIN
base map type.
Changing base maps may seem to be an easy topic, but the math and tech behind them is not as easy as using them. The base maps and overlays used in the Google Maps JavaScript API are processed in the Web Mercator projection system. In this projection system, the angles are preserved, but the size and shape of large objects change. As a result, the poles seem to be bigger than North America, which is not true at all. This projection is a good way to show the whole world in the same map.
Please check the later chapters for detailed information or check the Wikipedia article at https://en.wikipedia.org/wiki/Mercator_projection.