Skip to content

Instantly share code, notes, and snippets.

@synga
Last active June 2, 2017 19:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save synga/0a19e1f0edd05a09e52edf42032960fc to your computer and use it in GitHub Desktop.
Save synga/0a19e1f0edd05a09e52edf42032960fc to your computer and use it in GitHub Desktop.
My maps on ionic 2
/*
TODO:
O CONTEUDO DAS CHAMADAS DO GEOQUERY, AS FUNÇÕES, DEVEM ESTAR DENTRO DO METODO DE RETORNO DELE OU NÃO FUNCIONAM, ELES NÃO ENXERGAM NADA FORA DO ESCOPO DO PROPRIO GEOQUERY
*/
import { Component } from '@angular/core';
import { NavController, IonicPage, LoadingController } from 'ionic-angular';
import { GoogleMaps, GoogleMap, GoogleMapsEvent, LatLng, CameraPosition, MarkerOptions, Marker } from '@ionic-native/google-maps';
import { Geolocation } from '@ionic-native/geolocation';
import * as firebase from 'firebase';
import GeoFire from 'geofire';
@IonicPage()
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public locais: any[] = [];
public map: GoogleMap;
public meuMarcador: MarkerOptions;
public geoWatcher;
public boundingRadius: number = 1;
// Generate a random Firebase location
public firebaseRef = firebase.database().ref('/geofire/');
// Create a new GeoFire instance at the random Firebase location
geoFire = new GeoFire(this.firebaseRef);
geoQuery: any;
queryKey: any;
constructor(
public navCtrl: NavController,
public googleMaps: GoogleMaps,
public geolocation: Geolocation,
public loadingCtrl: LoadingController) {
}
loadMap() {
// ADICIONA OS MARKERS AO MAPA
function adicionaMarcadores(localizacao, key) {
let marker;
let latlng: LatLng = new LatLng(localizacao['0'], localizacao['1']);
if (!markerExists(localizacao['0'], localizacao['1'])) {
// VAI PUXAR AS INFORMAÇÕES DO MARCADOR NO FIREBASE
// PROCURAR SE NÃO TEM UMA FORMA DE ALTERAR E PUXAR OUTRAS INFORMAÇÕES JÁ NO BUSCA DO ANGULARFIRE
firebase.database().ref('/garagens/').child(String(key)).once('value').then(snap => {
console.log(snap.val());
// create new marker
marker = {
position: latlng,
title: snap.val().nome + '<br> Valor/hora: ' + snap.val().valor
};
HomePage.prototype.map.addMarker(marker)
.then((marker: Marker) => {
marker.showInfoWindow();
});
HomePage.prototype.locais.push(marker);
});
};
}
// VERIFICA SE O MARKER JÁ EXISTE NO MAPA
function markerExists(lat, lng) {
let exists = false;
this.locais.forEach((marker) => {
if (marker.lat === lat && marker.lng === lng) {
exists = true;
}
});
return exists;
}
const loader = this.loadingCtrl.create({ content: 'Aguarde...' });
// CRIA UM NOVO ELEMENTO DA DIV MAPA E SETA UM NOVO MAPA PRA ELA.
let element: HTMLElement = document.getElementById('mapa');
// OPÇÕES DO MAPA
let mapOptions = {
zoom: 18,
tilt: 40,
scrollwheel: false,
disableDefaultUI: true,
disableDoubleClickZoom: true,
styles: [
{
"featureType": "administrative.land_parcel",
"elementType": "labels",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "poi",
"elementType": "labels.text",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "poi.business",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "road",
"elementType": "labels.icon",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "road.local",
"elementType": "labels",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "transit",
"stylers": [
{
"visibility": "off"
}
]
}
]
};
this.map = this.googleMaps.create(element, mapOptions);
// ADICIONA O MARCADOR DO USUARIO NO MAPA
this.geolocation.getCurrentPosition().then(pos => {
// CRIA O GEOQUERY QUE IRÁ PEGAR LOCAIS NO RAIO DESEJADO
this.geoQuery = this.geoFire.query({
center: [pos.coords.latitude, pos.coords.longitude],
radius: this.boundingRadius
});
this.meuPromise().then(res => {
this.geoQuery.on("key_entered", function (key, location, distance) {
adicionaMarcadores(location, key);
});
this.geoQuery.on("key_exited", function (key, location, distance) {
console.log(key + " exited query to " + location + " (" + distance + " km from center)");
});
this.geoQuery.on("key_moved", function (key, location, distance) {
console.log(key + " moved within query to " + location + " (" + distance + " km from center)");
});
});
// create LatLng object
let eu: LatLng = new LatLng(pos.coords.latitude, pos.coords.longitude);
// create CameraPosition
let position: CameraPosition = {
target: eu,
zoom: 18,
tilt: 40
};
// ATUALIZA A CAMERA MOVENDO PARA O LOCAL CORRETO
this.map.moveCamera(position);
// create new marker
this.meuMarcador = {
position: eu,
title: 'Eu'
};
this.map.addMarker(this.meuMarcador)
.then((marker: Marker) => {
marker.showInfoWindow();
});
});
// CHAMA O LOADER QUE IRÁ CHAMAR A FUNÇÃO DO MAPA PELA PRIMEIRA VEZ
loader.present().then(() => {
// listen to MAP_READY event
// You must wait for this event to fire before adding something to the map or modifying it in anyway
this.map.one(GoogleMapsEvent.MAP_READY).then(() => {
console.log('Map is ready!');
// CRIA UM OBSERVABLE PARA A POSIÇÃO ATUAL, TODA VEZ QUE MUDAR CHAMARÁ A FUNÇÃO NOVAMENTE
this.geoWatcher = this.geolocation.watchPosition().subscribe(pos => {
let x = pos.coords.latitude;
let y = pos.coords.longitude;
console.log(this.map.getCameraPosition());
// create LatLng object
let eu: LatLng = new LatLng(x, y);
// create CameraPosition
let position: CameraPosition = {
target: eu,
zoom: 18,
tilt: 40
};
// ATUALIZA A CAMERA MOVENDO PARA O LOCAL CORRETO
this.map.moveCamera(position);
// ATUALIZA O MARCADOR DO USUARIO
this.meuMarcador.position = eu;
// PEGA O BOUNDARIE DO MAPA
this.map.getVisibleRegion().then(res => {
this.boundingRadius = this.getDistanceBetweenPoints(eu, res.northeast);
this.geoQuery.updateCriteria({ radius: this.boundingRadius });
loader.dismiss();
});
});
});
});
}
// PEGA A DISTANCIA ENTRE DOIS PONTOS
getDistanceBetweenPoints(pos1, pos2) {
let R = 6371; // RAIO DA TERRA EM KM
let lat1 = pos1.lat;
let lon1 = pos1.lng;
let lat2 = pos2.lat;
let lon2 = pos2.lng;
let dLat = this.toRad((lat2 - lat1));
let dLon = this.toRad((lon2 - lon1));
let a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(this.toRad(lat1)) * Math.cos(this.toRad(lat2)) *
Math.sin(dLon / 2) *
Math.sin(dLon / 2);
let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
let d = R * c;
return d;
}
toRad(x) {
return x * Math.PI / 180;
}
// Load map only after view is initialized
ngAfterViewInit() {
this.loadMap();
}
// VAI PARAR OS WATCHERS QUANDO SAIR DA TELA
ionViewWillLeave() {
this.geoWatcher.unsubscribe();
}
// ADICIONA OS MARKERS AO MAPA
adicionaMarcadores(localizacao, key) {
let marker;
let latlng: LatLng = new LatLng(localizacao['0'], localizacao['1']);
if (!this.markerExists(localizacao['0'], localizacao['1'])) {
// VAI PUXAR AS INFORMAÇÕES DO MARCADOR NO FIREBASE
// PROCURAR SE NÃO TEM UMA FORMA DE ALTERAR E PUXAR OUTRAS INFORMAÇÕES JÁ NO BUSCA DO ANGULARFIRE
firebase.database().ref('/garagens/').child(String(key)).once('value').then(snap => {
console.log(snap.val());
// create new marker
marker = {
position: latlng,
title: snap.val().nome + '<br> Valor/hora: ' + snap.val().valor
};
this.map.addMarker(marker)
.then((marker: Marker) => {
marker.showInfoWindow();
});
this.locais.push(marker);
});
};
}
// VERIFICA SE O MARKER JÁ EXISTE NO MAPA
markerExists(lat, lng) {
let exists = false;
this.locais.forEach((marker) => {
if (marker.lat === lat && marker.lng === lng) {
exists = true;
}
});
return exists;
}
// TESTE PROMISE
meuPromise = (): Promise<boolean> => {
return new Promise<boolean>(res => {
this.geoQuery.on("ready", function () {
res(true)
});
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment