Book Image

Google Maps JavaScript API Cookbook

Book Image

Google Maps JavaScript API Cookbook

Overview of this book

Day by day, the use of location data is becoming more and more popular, and Google is one of the main game changers in this area. The Google Maps JavaScript API is one of the most functional and robust mapping APIs used among Geo developers. With Google Maps, you can build location-based apps, maps for mobile apps, visualize geospatial data, and customize your own maps.Google Maps JavaScript API Cookbook is a practical, hands-on guide that provides you with a number of clear, step-by-step recipes that will help you to unleash the capabilities of the Google Maps JavaScript API in conjunction with open source or commercial GIS servers and services through a number of practical examples of real world scenarios. This book begins by covering the essentials of including simple maps for Web and mobile, adding vector and raster layers, styling your own base maps, creating your own controls and responding to events, and including your own events.You will learn how to integrate open source or commercial GIS servers and services including ArcGIS Server, GeoServer, CartoDB, Fusion Tables, and Google Maps Engine with the Google Maps JavaScript API. You will also extend the Google Maps JavaScript API to push its capabilities to the limit with additional libraries and services including geometry, AdSense, geocoding, directions, and StreetView.This book covers everything you need to know about creating a web map or GIS applications using the Google Maps JavaScript API on multiple platforms.
Table of Contents (15 chapters)
Google Maps JavaScript API Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Creating a simple map in a custom DIV element


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.

Getting ready

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.

How to do it…

Here are the steps we will use to create our first map using the Google Maps JavaScript API.

  1. 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.

  2. 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>
  3. 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);
      }
  4. 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>
  5. 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.

How it works...

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)