Nessa aula eu vou te mostrar 4 exemplos de utilização do Google Maps/Geolocalização com o Ionic.
Você vai aprender:
- Exibir mapas estáticos
- Exibir mapas dinâmicos
- Recuperar a localização do usuário e exibir no mapa
- Traçar rotas entre dois pontos distintos
Esse tutorial está utilizando as seguintes versões das dependências:
- Ionic: 3.19.0
O que é o Google Maps
O Google Maps é um serviço de mapas do Google onde é possível buscar endereços, lugares e traçar rotas.
O que é Geolocalização
Basicamente Geolocalização é prover serviços personalizados com base na localização do usuário.
Obter uma chave de API
- Acesse Google API Console.
- Crie ou selecione um projeto.
- Clique em Continue para ativar a API e serviços relacionados.
- Na página Credentials, obtenha uma chave de API.
- Copie o código gerado para ser usado mais tarde nesse tutorial.
Você pode acessar a documentação do Google para gerar uma chave de API clicando aqui.
Criando uma aplicação de exemplo
O passo a passo abaixo é o mesmo mostrado no vídeo.
- Passo 1: Criar o aplicativo.
- Passo 2: Instalar o plugin de geolocalização do Ionic Native.
- Passo 3: Adicionar a API do Google Maps
- Passo 4: Criar as páginas.
Passo 1: Criar o aplicativo
ionic start NOME_DO_APP blank
Passo 2: Instalar o plugin de geolocalização do Ionic Native
ionic cordova plugin add cordova-plugin-geolocation --variable GEOLOCATION_USAGE_DESCRIPTION="To locate you" npm install --save @ionic-native/geolocation
No arquivo app.module.ts adicionar a o provider “Geolocation”
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { Geolocation } from '@ionic-native/geolocation';
@NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
Geolocation
]
})
export class AppModule {}
Passo 3: Adicionar a API do Google Maps
Adicionar o script abaixo no arquivo index.html
<script src="http://maps.google.com/maps/api/js?key=SUA KEY AQUI"></script>
Arquivo index.html completo
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8">
<title>Ionic App</title>
<meta name="viewport" content="viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<link rel="icon" type="image/x-icon" href="assets/icon/favicon.ico">
<link rel="manifest" href="manifest.json">
<meta name="theme-color" content="#4e8ef7">
<!-- add to homescreen for ios -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<script src="http://maps.google.com/maps/api/js?key=SUA KEY AQUI"></script>
<!-- cordova.js required for cordova apps (remove if not needed) -->
<script src="cordova.js"></script>
<!-- un-comment this code to enable service worker
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service-worker.js')
.then(() => console.log('service worker installed'))
.catch(err => console.error('Error', err));
}
</script>-->
<link href="build/main.css" rel="stylesheet">
</head>
<body>
<!-- Ionic's root component and where the app will load -->
<ion-app></ion-app>
<!-- The polyfills js is generated during the build process -->
<script src="build/polyfills.js"></script>
<!-- The vendor js is generated during the build process
It contains all of the dependencies in node_modules -->
<script src="build/vendor.js"></script>
<!-- The main bundle js is generated during the build process -->
<script src="build/main.js"></script>
</body>
</html>
Passo 4: Criar as páginas
ionic g page exemplo1 ionic g page exemplo2 ionic g page exemplo3 ionic g page exemplo4
Página Exemplo1
Arquivo exemplo1.ts
import { Component } from '@angular/core';
import { IonicPage } from 'ionic-angular';
@IonicPage()
@Component({
selector: 'page-exemplo1',
templateUrl: 'exemplo1.html',
})
export class Exemplo1Page {
imoveis: Array<Imovel>;
constructor() { }
ionViewDidLoad() {
this.getImoveis();
}
getImoveis() {
this.imoveis = [
new Imovel('Apartamento com 2 Quartos para Venda ou Aluguel, 80 m²', 295.000, 'Rua Eduardo Viviani', '400', 'Boa Vista', 'Juiz de Fora', 'MG'),
new Imovel('Parque Jardim dos Bandeirantes, 80 m²', 152.074, 'Avenida Garcia Rodrigues Paes', '0', 'Jóckey Club', 'Juiz de Fora', 'MG'),
new Imovel('Apartamento com 2 Quartos à Venda, 72 m²', 138.000, 'Rua Aurora Tôrres', '10', 'Santa Luzia', 'Juiz de Fora', 'MG')];
}}
export class Imovel {
nome: string;
valor: number;
logradouro: string;
numero: string;
bairro: string;
cidade: string;
estado: string
mapa: string;
constructor(nome: string, valor: number, logradouro: string, numero: string, bairro: string, cidade: string, estado: string) {
this.nome = nome;
this.valor = valor;
this.logradouro = logradouro;
this.numero = numero;
this.bairro = bairro;
this.cidade = cidade;
this.estado = estado;
this.mapa = this.getMapa();
}
private getEndereco() {
return this.logradouro + ', ' + this.numero + ' - ' + this.bairro + ', ' + this.cidade + ' - ' + this.estado;
}
private getMapa() {
return 'https://maps.googleapis.com/maps/api/staticmap?zoom=15&size=400x400&markers=color:red|' + this.getEndereco() + '&key=AIzaSyCxqgKqZMHNzOV2TETOwjRJAUpuh3aeK1c'
}
}
Arquivo exemplo1.html
<ion-header>
<ion-navbar>
<ion-title>Google maps</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-card *ngFor="let imovel of imoveis">
<div class="mapa">
<img src="{{ imovel.mapa }}">
</div>
<ion-item>
<h2 text-wrap>{{ imovel.nome }}</h2>
<p>{{ imovel.valor | currency:'BRL' }}</p>
</ion-item>
</ion-card>
</ion-content>
Página Exemplo2
Arquivo exemplo2.ts
import { Component } from '@angular/core';
import { IonicPage } from 'ionic-angular';
declare var google;
@IonicPage()
@Component({
selector: 'page-exemplo2',
templateUrl: 'exemplo2.html',
})
export class Exemplo2Page {
map: any;
constructor() { }
ionViewDidLoad() {
const position = new google.maps.LatLng(-21.763409, -43.349034);
const mapOptions = {
zoom: 18,
center: position,
disableDefaultUI: true
}
this.map = new google.maps.Map(document.getElementById('map'), mapOptions);
const marker = new google.maps.Marker({
position: position,
map: this.map,
//Titulo
title: 'Minha posição',
//Animção
animation: google.maps.Animation.DROP, // BOUNCE
//Icone
icon: 'assets/imgs/pessoa.png'
});
}
}
Arquivo exemplo2.html
<ion-header>
<ion-navbar>
<ion-title>Google maps</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<div #map id="map"></div>
</ion-content>
Arquivo exemplo2.scss
page-exemplo2 {
#map {
height: 100%;
}
}
Página Exemplo3
Arquivo exemplo3.ts
import { Component } from '@angular/core';
import { IonicPage } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
declare var google;
@IonicPage()
@Component({
selector: 'page-exemplo3',
templateUrl: 'exemplo3.html',
})
export class Exemplo3Page {
map: any;
constructor(private geolocation: Geolocation) { }
ionViewDidLoad() {
this.geolocation.getCurrentPosition()
.then((resp) => {
const position = new google.maps.LatLng(resp.coords.latitude, resp.coords.longitude);
const mapOptions = {
zoom: 18,
center: position
}
this.map = new google.maps.Map(document.getElementById('map'), mapOptions);
const marker = new google.maps.Marker({
position: position,
map: this.map
});
}).catch((error) => {
console.log('Erro ao recuperar sua posição', error);
});
}
}
Arquivo exemplo3.html
<ion-header>
<ion-navbar>
<ion-title>Google maps</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<div #map id="map"></div>
</ion-content>
Arquivo exemplo3.scss
page-exemplo3 {
#map {
height: 100%;
}
}
Página Exemplo4
Arquivo exemplo4.ts
import { Component } from '@angular/core';
import { IonicPage } from 'ionic-angular';
declare var google;
@IonicPage()
@Component({
selector: 'page-exemplo4',
templateUrl: 'exemplo4.html',
})
export class Exemplo4Page {
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
map: any;
startPosition: any;
originPosition: string;
destinationPosition: string;
constructor() { }
ionViewDidLoad() {
this.initializeMap();
}
initializeMap() {
this.startPosition = new google.maps.LatLng(-21.763409, -43.349034);
const mapOptions = {
zoom: 18,
center: this.startPosition,
disableDefaultUI: true
}
this.map = new google.maps.Map(document.getElementById('map'), mapOptions);
this.directionsDisplay.setMap(this.map);
const marker = new google.maps.Marker({
position: this.startPosition,
map: this.map,
});
}
calculateRoute() {
if (this.destinationPosition && this.originPosition) {
const request = {
// Pode ser uma coordenada (LatLng), uma string ou um lugar
origin: this.originPosition,
destination: this.destinationPosition,
travelMode: 'DRIVING'
};
this.traceRoute(this.directionsService, this.directionsDisplay, request);
}
}
traceRoute(service: any, display: any, request: any) {
service.route(request, function (result, status) {
if (status == 'OK') {
display.setDirections(result);
}
});
}
}
Arquivo exemplo4.html
<ion-header>
<ion-navbar>
<ion-title>Google maps</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-list>
<ion-item>
<ion-label>De onde?</ion-label>
<ion-input type="text" [(ngModel)]="originPosition"></ion-input>
</ion-item>
<ion-item>
<ion-label>Para onde?</ion-label>
<ion-input type="text" [(ngModel)]="destinationPosition"></ion-input>
</ion-item>
<div padding>
<button ion-button (click)="calculateRoute()">Traçar rota</button>
</div>
</ion-list>
<div #map id="map"></div>
</ion-content>
Arquivo exemplo4.scss
page-exemplo4 {
#map {
height: 80%;
}
}
Clique no botão abaixo para ver o código fonte gerado nessa aula
[button style=”btn-primary btn-lg” type=”link” target=”true” title=”Código fonte gerado na aula” link=”https://github.com/fabricadecodigo/IonicGoogleMapsBasicExample” linkrel=””]
Referências
- Obter uma chave/autenticação: https://developers.google.com/maps/documentation/javascript/get-api-key
- Guia do desenvolvedor da Google Static Maps API: https://developers.google.com/maps/documentation/static-maps/intro
- Como adicionar um mapa Google com marcador ao seu site: https://developers.google.com/maps/documentation/javascript/adding-a-google-map
- Serviço Directions: https://developers.google.com/maps/documentation/javascript/directions
- Ionic Native – Geolocation: https://ionicframework.com/docs/native/geolocation
Gostou desse artigo? Aproveite e curta e compartilhe para que mais pessoas possam também visualiza-lo!
Ainda ficou alguma dúvida ou tem alguma sugestão? Deixa aí nos comentários!