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.

terça-feira, 2 de setembro de 2014

Aprendizagem - Elifoot

1. Relatório de experiência no jogo
  • O jogo permite até 05 jogadores (treinadores).
     
  • A interação com o jogo é toda via comandos no teclado.
     
  • Ele exibe interativamente o sorteio dos jogos.
     
  • Oferece a possibilidade de compra de jogadores por meio de leilão. Informa parâmetros para a avaliação do jogador, como Posição, Força e Preço.
     
  • Quando na tela de escalação, exibe os menus de atalhos por meio da tecla Enter. Estes menus são de Táticas, Campeonato, Finanças e Diversos.
     
  • Táticas: Permite que você escolha uma dentre as táticas possíveis com sua escalação de jogadores atual. A interação neste menu é feita por meio das teclas de F1 a F8.
     
  • Campeonato: Onde é possível exibir o calendário dos jogos de sua equipe e informa se o mesmo é em casa ou fora e exibir o placar de jogos que já ocorreram, além de exibir as estatíticas do campeonato, como melhores atacantes e classificação. A interação é feita por meio do Shift + (F1 a F6).
     
  • Finanças: Permite vender jogadores, alterar seus preços, exibir os prêmios, as transferências do mercado, e as receitas atuais. A interação é feita por meio do Crtl + (F1 a F5).
     
  • Diversos: Permite alterar seu estádio, selecionar os melhores jogadores e exibir os treinadores atuais e seus times, além de permitir a saída do jogo. A interação é feita por meio do Alt + (F1 a F10).
     
  • Como o padrão de cores da interface é baseado nas cores do time, em algumas combinações fica bem difícil a leitura, como, por exemplo, o São Paulo, onde o fundo fica preto com as letras vermelhas:


  • Pode ser um bug da versão que baixei, mas existem casos onde não é possível ver nada além do menu:


  • Após a escolha das táticas, é iniciada a rodada, onde em uma mesma tela são exibidos os resultados de todos jogos, à medida que os mesmos vão se construindo, só que em tempo acelerado. Ao término do 1º tempo é fornecida a opção de substituição de jogadores a todos os treinadores.
     
  • Após o término da rodada é exibida a classificação das 4 divisões do campeonato e, após isto, o ciclo do jogo é reiniciado com o leilão dos jogadores de outras equipes.
     
  • O grande “segredo” do sucesso do Elifoot, para mim, é proporcionar ao jogador, com apenas algumas interações, uma experiência virtualmente completa de treinador de futebol. Num país onde este é o esporte nacional, como o Brasil, o jogo sem dúvida fez um tremendo sucesso, pois permitia a todos alcançar o status de treinador e desenvolver uma equipe dentro de um campeonato, começando em sua 4ª divisão, subindo de nível, partida por partida, até alcançar o campeonato da 1ª divisão.


2. Invenção de um jogo semelhante para outro contexto
  • Podemos ter uma simulação de Bolsa de Valores, onde o jogador seria um investidor, iniciaria com uma certa quantia em dinheiro, e avaliaria os cenários atuais das melhores empresas onde pudesse investir.
     
  • Seria exibido a ele os últimos acontecimentos de uma empresa, por exemplo: “OGX descobre que campo de Tubarão Martelo produzirá muito mais do que o esperado”. Também poderia ser exibido os resultados dos últimos fechamentos da bolsa para aquele papel específico.
     
  • A interação poderia ser plenamente Textual, como no Elifoot. Este jogo poderia, inclusive, rodar como uma API, onde as interações seriam registros JSON trafegando na rede, para o servidor X ou Y.
     
  • Seria possível, inclusive, criar um ambiente completo de simulação de bolsa, onde vários jogadores desempenhariam diversos papéis, tanto do investidor que compra como do especulador que vende ações.
     
  • Os dados das empresas e os fechamentos das bolsas podem ser baseados na realidade.
     
  • Este jogo tem potencial para treinar quem quer ser um investidor na bolsa, mas tem medo de se arriscar sem antes conhecer a forma de se trabalhar.

Apresentação - JDA 2014/2

Qual a sua experiência com jogos, de uma maneira geral:
Tenho 26 anos de experiência com jogos, desde NES, SNES, Mega Drive, Sega Saturn, PC, PS1-4, XBOX, ... :]
Com desenvolvimento de jogos, criei apenas algumas POCs em HTML5 (Canvas), como Pong, Pac Man, Mario e Asteroids.

Sua experiência com jogos na Educação:
NaN.

Que jogos digitais você joga ou já jogou, e por quanto tempo:
A lista é imensa e o tempo seria melhor representado em anos... :] Em ordem decrescente alguns dos mais jogados:
Counter-Strike: 08 anos  
Super Mario World: 06 anos 
Super Mario Kart: 06 anos
Battlefield 2: 03 anos
Age of Empires 3: 03 anos 
NFSU2: 02 anos 
Warface: 01 ano

Qual o jogo que você está jogando no momento? Quantas horas por semana você joga?
MSc... No time for games :(

Você já desenvolveu ou participou do desenvolvimento de jogos, quais? Quando? 
Criei apenas algumas POCs em HTML5 (Canvas), como Pong, Pac Man, Mario e Asteroids. Este ano.

Por que você está interessado em cursar esta disciplina?
Possui certo nível de aderência com minha proposta de dissertação, no que tange a ambientes de simulação e ambientes competitivos.