Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Google Maps JavaScript API Cookbook
Google Maps JavaScript API Cookbook

Google Maps JavaScript API Cookbook: This book will help you use the amazing resource that is Google Maps to your own ends. From showing maps on mobiles to creating GIS applications, this lively, recipe-packed guide is all you need.

eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Google Maps JavaScript API Cookbook

Chapter 1. Google Maps JavaScript API Basics

In this chapter, we will cover the following topics:

  • Creating a simple map in a custom DIV element
  • Creating a simple fullscreen map
  • Moving from the Web to mobile devices
  • Changing map properties programmatically
  • Changing base maps

Introduction

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.

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.
    How to do it…

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)

Creating a simple fullscreen map

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.

Getting ready

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.

How to do it…

You can easily create a simple fullscreen map by following the given steps:

  1. 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.
  2. Find the following lines of code in the new file:
        <style type="text/css">
             #mapDiv { width: 800px; height: 500px; }
        </style>
  3. Add the following lines and change them according to the new values stated. The width and height values are changed to 100% in order to make the map full screen in the browser viewport. Also, the margin value of the body element is changed to 0 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>
  4. 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.
    How to do it…

Thus we have successfully created a simple fullscreen map.

How it works...

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.

There's more...

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.

See also

  • The Creating a simple map in a custom DIV element recipe

Moving from the Web to mobile devices

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.

Getting ready

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.

How to do it…

If you want to create a map that is optimum for mobile devices, you should follow the given steps:

  1. 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.
  2. 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>
  3. 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" />
  4. 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>
  5. 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);
        });
    }
  6. 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.
    How to do it…

This is how we achieve the goal of creating a simple map for mobile devices.

How it works...

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.

There's more...

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

See also

  • The Creating a simple map in a custom DIV element recipe

Changing map properties programmatically

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.

Getting ready

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.

How to do it…

Changing the map properties is quite easy if you follow the given steps:

  1. 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.
  2. 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 });
    }
  3. 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();
        });
    }
  4. The startButtonEvents function must be called on initializing the map, so the following line of code is added:
    startButtonEvents();
  5. Then, add the following HTML lines of code inside the <body> tag. These are the <button> tags to be shown on the web page. Each button 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">
  6. 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.
    How to do it…

As a result of the recipe, we can change map properties programmatically.

How it works...

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

See also

  • The Creating a simple map in a custom DIV element recipe

Changing base maps

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.

Changing base maps

In this recipe, we will go through the Google Maps base maps and learn how to change them programmatically.

Getting ready

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.

How to do it…

  1. If you follow the given steps, you can change the base maps of your map.
  2. 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.
  3. 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);
        });
    }
  4. The startButtonEvents function must be called upon initializing the map, so the following line of code is added after the map is initialized.
    startButtonEvents();
  5. 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">
  6. 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.
    How to do it…

As shown in the preceding screenshot, you can easily change the base maps that are provided by Google.

How it works...

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.

There's more...

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.

See also

  • The Creating a simple map in a custom DIV element recipe
Left arrow icon Right arrow icon

Key benefits

  • Add to your website's functionality by utilizing Google Maps' power
  • Full of code examples and screenshots for practical and efficient learning
  • Empowers you to build your own mapping application from the ground up

Description

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.

Who is this book for?

Google Maps JavaScript API Cookbook is for developers who wish to learn how to do anything from adding a simple embedded map to a website to developing complex GIS applications with the Google Maps JavaScript API. It is targeted at JavaScript developers who know how to get by but who are also seeking the immediacy of recipe-based advice.

What you will learn

  • Create simple maps and display them on mobile devices
  • Style your own base maps
  • Add your own tile maps as base maps or overlays
  • Show vector layers on base maps in various types such as points, polylines or polygons
  • Parse various vector formats such as KML, GeoRSS, GeoJSON, WKT, and so on
  • Create a custom UI and customize your own ways to control it
  • Respond to various events including mobile gestures
  • Add additional libraries to extend the capabilities of the API
  • Work with Google Services for geocoding, directions, StreetView, and so on
  • Integrate open source or commercial GIS servers or services
Estimated delivery fee Deliver to Greece

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 26, 2013
Length: 316 pages
Edition : 1st
Language : English
ISBN-13 : 9781849698825
Vendor :
Google
Category :
Languages :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Greece

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Publication date : Dec 26, 2013
Length: 316 pages
Edition : 1st
Language : English
ISBN-13 : 9781849698825
Vendor :
Google
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 120.97
PostGIS Cookbook
€41.99
Google Maps JavaScript API Cookbook
€36.99
Learning Geospatial Analysis with Python
€41.99
Total 120.97 Stars icon

Table of Contents

9 Chapters
1. Google Maps JavaScript API Basics Chevron down icon Chevron up icon
2. Adding Raster Layers Chevron down icon Chevron up icon
3. Adding Vector Layers Chevron down icon Chevron up icon
4. Working with Controls Chevron down icon Chevron up icon
5. Understanding Google Maps JavaScript API Events Chevron down icon Chevron up icon
6. Google Maps JavaScript Libraries Chevron down icon Chevron up icon
7. Working with Services Chevron down icon Chevron up icon
8. Mastering the Google Maps JavaScript API through Advanced Recipes Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3
(8 Ratings)
5 star 37.5%
4 star 50%
3 star 12.5%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Tanongkiet Upanno Jun 18, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I love this kind of IT book. Since it is not only explain the application features by example but also explain each coding in the example.
Amazon Verified review Amazon
VitoshAcademy May 04, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
[Disclosure - I have a blog, reviewing books and I write reviews there - [...] I have also written three articles, concerning some of the code in the book there.I was not asked by the authors or anyone to review the book, I just needed a book, concerning Google Maps API and this one was quite a good match. At lеast prior to reading the book I had almost no experience with Java Script]What this book has to offer to a reader who has almost NO experience with Java Script (like me, for example)? Actually, pretty much EVERYTHING you need to know. It starts with the ABC of Java Script and Google API, giving you one really simple example, how to build a map. In the next examples, everything build upon this first example is explained in huge details. Sometimes, I think that the authors go to much into details, but this is probably a good thing! :)What I liked - the book is really a "CookBook" - you do not need to read it page by page, chapter by chapter, but you can simply read the first chapter and the introduction and then you may go to any page, to any recipe and use it as a pro :) This is really a big plus for beginners, who do not have full 3 days to read it properly and test the code in it.What you should do after buying the book - the examples are quite well built, but they will not function on your pc immediately - that is because the google api code, which has some limitations. Thus you should go and make your own account at code.google.com and change the code from the book at that place. Fortunately, the procedure is well described.What is inside? Pretty much anything a beginner in Google API & Java Script would dream about. The table of contents is really well composed for beginners.So, my last word is the following - if you are a beginner in either Java Script or Google API - go for the book, it is suited for you! No specific pre-knowledge is required, indeed (probably, just some really basic knowledge in programming)! If you are wondering whether this book is for you, you may go to the book's website and browse the examples, which are generously provided there - at the site of the book, go to the support tab and click "Download Now". Then the code is fully at your disposal!Thank you for reading the review! I hope you have enjoyed it!Regards,vitoshacademy.com
Amazon Verified review Amazon
ervin kenan aydin Jan 31, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I have the Kindle Version of this book. It has easy to understand examples and clear explanations. I loved it!
Amazon Verified review Amazon
Cristian Scutaru Sep 16, 2014
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
In the true spirit of a "cookbook" publication, many many samples for the most recent Google Maps API.
Amazon Verified review Amazon
Fernando Doglio Mar 12, 2014
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Disclosure: I was asked by the publisher to review this book.The book“Google Maps JavaScript API Cookbook” is relatively a short book, it’s full of, like the name of the book suggests, recipes to work with the Google Maps API.Both authors, Alper Dincer and Balkan Uraz share a MS degree in Geographical Sciences and have over 10 years of experience working on Geographic Information Systems. So it’s safe to say they know their GIS. That being said, this is a programming cookbook, so the quality of the recipes is not assured.The badLet’s first start with the bad, or the not-so-good to be honest.Like I said before, the book’s authors are experts when it comes to Geographical Systems, and have worked in several Geo related projects over the last 10 years, but it shows that they are not experienced programmers.The recipes do their work, don’t get me wrong, but their code is not the best, they just don’t follow regular best practices.The entire book could’ve been thought out to end up developing a small framework to work with Google Maps API. Instead, the recepies’ code are only related to that recepie’s task instead. Leaving the reader with a bunch of individual examples and a lot of repeated code.The other programming related issue I had with this book, was that the authors kept talking about creating classes. If you’ve used JavaScript for a while, you’d know that that’s not entirely right, actually, it’s pretty misleading to the less versed developer. I know this isn’t a JavaScript-heavy book or anything like that, but they could’ve at least bothered to get the names right.The goodYeap, that’s right, that’s about all that really “bothered” me from the book. To be honest, this book is a really useful reference manual.It’s quite easy to read, each example is easily understood and very well explained. You’ll probably find yourself coming back to it, just to quickly check how something was done.Call me skeptic, but I had my doubts about the cookbook format of it. I was afraid that the lack of technical depth about the Google Maps API would hurt and hinder my learning. On the contrary, this gave me a super quick, yet complete, overview of what I could possibly accomplish with this powerful API.I had already done some easy and mid-level stuff with the API but by the end of the book, I had learned how to fully customize the map, load external data and use the services provided by the API.Would I recommend it?Yes I would, if you’re just starting, get the book and learn all you can eventually accomplish with it. If you’ve already worked with the API, get it anyways, you’ll end up learning a few tricks on the way.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela