Search icon CANCEL
Subscription
0
Cart icon
Cart
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Google Maps JavaScript API Cookbook

You're reading from  Google Maps JavaScript API Cookbook

Product type Book
Published in Dec 2013
Publisher Packt
ISBN-13 9781849698825
Pages 316 pages
Edition 1st Edition
Languages
Toc

Table of Contents (15) Chapters close

Google Maps JavaScript API Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
1. Google Maps JavaScript API Basics 2. Adding Raster Layers 3. Adding Vector Layers 4. Working with Controls 5. Understanding Google Maps JavaScript API Events 6. Google Maps JavaScript Libraries 7. Working with Services 8. Mastering the Google Maps JavaScript API through Advanced Recipes 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)

You have been reading a chapter from
Google Maps JavaScript API Cookbook
Published in: Dec 2013 Publisher: Packt ISBN-13: 9781849698825
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}