quinta-feira, 7 de janeiro de 2016

Working with the Google Maps API and Javascript

Google Maps is an amazing product. It has really come a long way in the last 4-5 years or so. In a planet of 7 billion people, we have a huge market to consume maps, and Google realized that ten years ago when created Google Maps. The search engine giant used its omnipresence on web to spread the Google Maps over the world. When the GPS enabled smartphones emerged, the use of Google Maps was boosted to hundreds of millions of requests per second.
Maps are everywhere. When you get in the car to go to work, there is your tiny and cheap travel buddy, docked over your car’s dashboard or under your windshield, showing (and talking) you through your morning journey to the best route. Then the iPhone, the Waze app, and the google maps mobile app took over navigational powers for most people. It’s never going to end. We will eventually be micro-chipped and have on our contact lenses the routes and directions.
As developers, we should offer to our clients the possibility of integrating maps with their website or application to enhance their market strategy, perform sales analysis, or to create new features to offer to their customers.
There are other good map platforms, as Bing Maps, MapQuest and OpenStreetMap, but Google Maps leads by far the maps market, offering APIs for Android, iOS, Web (client-side) and Web Services (server-side).
Our goal here is to create a Google Maps experiment using Web (client-side), which is the most achievable cross-platform environment.

Get a Key

To integrate any Google services with your application you need to get a key. To get this key, you need to access the Google Developer Console at https://console.developers.google.com.
First, create a project, clicking on Create an empty project or in Select a Project -> Create a Project.

Google is a bit creative to suggest your project ID. For me, it suggested excellent-badge-115403. Accept the terms and click on Create. After few seconds your project will be created and available at the front page of your Dashboard.
Click in the box named “Use Google APIs” to enable and manage APIs. This will open the API Manager. There you can create and enable the APIs to integrate with all Google services. Here you will choose Google Maps JavaScript API.
Then, click on the button Enable API. After that, a warning will appear informing that you can’t use this API in your project until the creation of your credentials. So, go to Credentials at the left menu or click on the button Go to Credentials.
At the Credentials page, click on the button Add credentials and then API key. As you want to allow your user to access the map direct in his browser, you will need to create a Browser key.
You can optionally configure your API key to accept requests of specific HTTP referrers. This is a very important step because the free access of Google Maps JavaScript API is limited by a quota of 25,000 requests/day and 1 request/second/user. As the browser key will be public in your HTML code, I strongly recommend you to specify your HTTP referrers, to ensure that just your client’s website will access this API, denying improper external use, ensuring the website functioning and saving money. After the quota is exceeded, you will be billed at $ 0.50 USD / 1,000 additional requests, up to 1,000,000 per 24 hours. If you create an API key without restricting HTTP referrer, the console will return to you the message: This key has no referrer restrictions, so other applications might be able to use this key and consume quota.
You can see more about the JavaScript API Usage Limits at https://developers.google.com/maps/documentation/javascript/usage.
To add all your website URLs and subdomains, use the asterisks for wildcard (e.g., *.edgar.systems/*).
Now you’re able to use the API in your project. At the API Manager, go to Overview at the left menu. After, click on the link Google Maps JavaScript API at the Google Maps APIs group. There you can see and overview of this API, your usage and the quotas already used.

Integrate with your Website

Maps themselves are nice, but when we’re working on a client strategy to attract more users we need a well-defined purpose. There are countless kinds of ways and possibilities to integrate your client business with Google Maps. You will need to list some of these strategies and define with your client what is the best way for you to achieve his goals.
With a well-defined map strategy, it’s time to code! First, open the HTML file where you want to insert the map.
Create a <div> element to be the map container.
<div id="mapContainer">
</div>
If you want to fill the document with your map, you will need to change to 100% the width and height of thediv, and the height of html and body, with zero margin and padding.
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

div#mapContainer {
  width: 100%;
  height: 100%;
}
You can set those dimensions and positions to follow your strategies for website layout and UI design.
Now you need to create the JavaScript function to initialize your map inside the container <div> element.
First, you declare a variable map to instantiate your map. Declare it outside the function scope to make it available for all your local functions.
The function init() will create a new instance of the object google.maps.Map in your variable map.
The google.maps.Map constructor method receives the <div> container element as the first parameter, and an object with the map options as the second parameter.
In this example, we’re centering the map on Anaheim, CA, US, passing a google.maps.LatLng object to propertycenter. This object has the properties lat and lng. Google Maps uses decimal degrees (DD) for coordinates which positive latitudes represent Northern Hemisphere, negative latitudes represent Southern Hemisphere, positive longitudes represent Eastern Hemisphere and negative longitudes represent Western Hemisphere.
You can define the zoom property for the your map. As higher the zoom is closer you are to the center of your map. The zoom is an integer value that starts with 0, showing the entire Earth, and generally can go up to 21.
var map;

function init() {
  map = new google.maps.Map(document.getElementById('mapContainer'), {
    center: {
      lat: 33.8665502,
      lng: -117.7464312
    },
    zoom: 17
  })
}
With the initialization function defined, you need to include the Google Maps JavaScript API script to your HTML. Before the </body>, create a <script> element with the src parameter referring the URL below. Ensure to change YOUR_API_KEY_HERE to your Browser Key created at the Google Developers Console. Your map will not work if the domain running the map is not properly defined as a HTTP referrer (in the case of you defined one). The URL can accept a callback parameter that receives the name of your map initialization function and will call it as soon as the script loads.
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY_HERE&callback=init">
</script>
This finishes your first Google Maps JavaScript API integration! Upload this HTML to your server and open it in any browser. Below you can see a screenshot with this example running and the full HTML code created.
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Google Maps JavaScript API</title>
    <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }

      div#mapContainer {
        width: 100%;
        height: 100%;
      }
    </style>
  </head>
  <body>
    <div id="mapContainer">
    </div>
    <script>
      var map;

      function init() {
        map = new google.maps.Map(document.getElementById('mapContainer'), {
          center: {
            lat: 33.8665502,
            lng: -117.7464312
          },
          zoom: 17
        })
      }
    </script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY_HERE&callback=init">
    </script>
  </body>
</html>

Get the User Location

You can increase your map by getting the user location and center the map on it. HTML5 brought the possibility to get the user location directly on browser by using the property Navigator.geolocation that returns aGeolocation object.
To obtain the user location you can use the method getCurrentPosition() of the Geolocation object. When you call it, the browser will ask user to allow for share his location with your page. This method initiates an asynchronous request to the user position and receives a success callback function as its required parameter, returning to it a Position object. You can see more about geolocation at https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation.
With the user position received, you can set the center of your map to it by calling the method setMap() of yourmap instance. This method receives a google.maps.LatLng object, containing the lat and lng properties.
You can call the getCurrentPosition() inside the function init() after initiate your map.
navigator.geolocation.getCurrentPosition(function getPosition(userPosition){
  map.setCenter({
    lat: userPosition.coords.latitude, 
    lng: userPosition.coords.longitude
  });
});

Add some Markers

Markers are essential if you need to identify places in your map. Every clickable point you see at Google Maps (https://www.google.com/maps) is an istance of google.maps.Marker created at runtime. At Google Maps, when you increase the zoom in certain region, you can realize that more places are loaded, so, more markers are created in the map. Google Maps loads this places by integrating with Google Places API (https://developers.google.com/places/).
To create a marker you will need to create a new instance of google.maps.Marker. You can instantiate it to a variable marker. Ensure to declare it outside a function scope to make it available for all your local functions.
The constructor of google.maps.Marker receives an Options object that can basically starts from two properties: position, which receives a google.maps.LatLng object, and map, that receives the variable that contains the instance of the map that will receive this marker.
When you create a marker it uses a standard image. You can set this image, referred as icon, if you need. You can see more about Markers at: https://developers.google.com/maps/documentation/javascript/markers.
marker = new google.maps.Marker({
  position: {
    lat: userPosition.coords.latitude,
    lng: userPosition.coords.longitude
  },
  map: map,
  title: 'User Location'
});

Inside the API

As this is a commercial product from Google, there is no much public information about what happens in the core of the Google Maps API. We can get some answers inspecting the Browser Debugger.

Initially, the API calls for a dynamically generated JavaScript, which is the core script of the Map. You can see this script at the image below.

Next, the core script calls many common scripts and stylesheets. At the Network tab of the Browser Debugger you can see clearly the request order performed by the API, starting from the map, to the dynamic JavaScript and to the common files.


To identify how the map view is build we can keep analyzing the Network tab. There you can see many small dynamically generated png files requested by the JavaScript, starting with vt?pb=.

When you open one of those files on the browser, you can see one of the pieces of the current map.

Nenhum comentário:

Postar um comentário