Last active
August 29, 2015 14:06
-
-
Save laurentperroteau/cf8ddf538a85efaa5a9f to your computer and use it in GitHub Desktop.
Google map exemple : get Json list of place, can display itinary to my place depend type of transport and can display list of place with custom infobox
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// GOOGLE MAPS | |
// ---------------------------- | |
/*jshint sub:true*/ | |
/*jshint indent:4 */ | |
var MyMap = { | |
data: { | |
mapItinerary: document.getElementById('map-itinary'), | |
panelItineray: document.getElementById('panel-itinary'), // id du <div> où écrire l'itinéraire | |
objItinerary: '', // objet de la map itinerary | |
icon: Global.data.imgPath + 'visual/marker.png', | |
cross: Global.data.imgPath + 'visual/white-cross.png', | |
mapShops: document.getElementById('map-shops'), | |
objMapShops: '', // l'objet de la map shops | |
infowindowOpen: '', // garde en mémoire la bulle ouverte | |
shops: '' // json de la liste des magasins | |
}, | |
load: function() { | |
if( typeof google != 'undefined' ) | |
{ | |
// Si page magasin | |
if( MyMap.data.mapItinerary ) | |
MyMap.radioItinary(); | |
// Si page magasin ou change magasin | |
if( MyMap.data.mapItinerary || MyMap.data.mapShops ) | |
MyMap.getJsonMapShops(); | |
} | |
}, | |
// Apel ajax qui récupère le Json de tous les magasins | |
getJsonMapShops: function() { | |
console.log('dans getJsonMapShops'); | |
console.log(Master.d('m')); | |
console.log(MyMap.data.mapShops); | |
if( Master.d('m') && MyMap.data.mapShops ) | |
{ | |
console.log('dans 1er condition'); | |
MyMap.findShop(); | |
} | |
else { | |
var jsonFile = window.location.hostname == 'lyon.altima.fr' ? '/grandfrais/_js/shop.json' : '/_js/shop.json', | |
jsonFile = window.location.protocol+ '//' +window.location.hostname + jsonFile; | |
$.getJSON( jsonFile, function(data) | |
{ | |
// Sauvegarde du json | |
MyMap.data.shops = data.shops; | |
// Lancement de la suite des scripts selon la page | |
if( MyMap.data.mapItinerary ) | |
MyMap.initItinary(); | |
else | |
MyMap.initMapShops(); | |
}) | |
.fail(function(jqxhr, textStatus, error) { | |
console.log( "Request Failed: " + error ); | |
$.merge(MyMap.data.panelItineray, MyMap.data.mapShops).html('ERREUR DE CHARGEMENT DE LA CARTE GOOGLE'); | |
}); | |
} | |
}, | |
// Comportement des boutons voiture, vélo et piéton | |
radioItinary: function() { | |
$trans = $('#transport li'); | |
$trans.on('click', function(e) { | |
e.preventDefault(); | |
$trans.removeClass('active'); | |
$(this).addClass('active'); | |
$(this).find('input[type=radio]').prop("checked", true); | |
}); | |
}, | |
// Initialise la map de l'itinéraire | |
initItinary: function() { | |
// Coordonnée du magasin de référence | |
var currentShopId = $( document.getElementById('destination-id') ).val(), | |
destiX = parseFloat( $( document.getElementById('destination-x') ).val() ), | |
destiY = parseFloat( $( document.getElementById('destination-y') ).val() ); | |
// Position central (pour ne pas faire de boucle, j'en mes une par defaut) | |
var myLatlng = new google.maps.LatLng( destiX, destiY ); | |
var myOptions = { | |
zoom : 14, | |
maxZoom : 20, | |
center : myLatlng, | |
scrollwheel: false, | |
scaleControl: false, | |
streetViewControl: false, | |
overviewMapControl: false, | |
mapTypeId : google.maps.MapTypeId.ROADMAP, // Type de carte, différentes valeurs possible HYBRID, ROADMAP, SATELLITE, TERRAIN | |
}; | |
// Création de l'objet google map | |
MyMap.data.objItinerary = new google.maps.Map( MyMap.data.mapItinerary, myOptions); | |
// Création du marker et récupération de son objet | |
var marker = MyMap.setMarker(MyMap.data.objItinerary, currentShopId, true); | |
// Création de l'objet qui contiendra l'itinéraire | |
var direction = new google.maps.DirectionsRenderer({ | |
map : MyMap.data.objItinerary, | |
panel : MyMap.data.panelItineray | |
// suppressMarkers: true | |
}); | |
// Calculer l'itinéraire au clic sur "J'y vais" | |
if( document.getElementById('print-itinery') == null) { | |
$( document.getElementById('calculate-itinary') ).on('submit', function(e) { | |
e.preventDefault(); | |
MyMap.calculateItinerary(direction, myLatlng, marker, MyMap.data.infowindowOpen); | |
}); | |
} | |
else { | |
MyMap.calculateItinerary(direction, myLatlng, marker, MyMap.data.infowindowOpen); | |
} | |
}, | |
/** | |
* Calcul de l'itinéraire et insertion dans le panel | |
* ================================================= | |
* @param {obj} direction => qui contiendra l'itinéraire | |
* @param {obj} coordDestination => coordonée du magasin courant | |
* @param {obj} marker => le marker crée du magasin courant | |
* @param {obj} infoWindow => la bulle crée du magasin courant | |
* @see "Directions Service": https://developers.google.com/maps/documentation/directions/ | |
*/ | |
calculateItinerary: function(direction, coordDestination, marker, infoWindow){ | |
var origin = document.getElementById('origin').value, | |
transport = $('input[name="transport"]:checked').val(); | |
// Si point de départ non renseigné | |
if( origin == '' ) | |
{ | |
$('#container-origin').addClass('parsley-error'); | |
$('#error-itinery').hide(); | |
$('#empty-itinery').show(); | |
} | |
else { | |
var request = { | |
origin : origin, | |
destination : coordDestination, | |
travelMode : google.maps.DirectionsTravelMode[transport], // Type de transport DRIVING (voiture), WALKING (piéton) et BICYCLING (vélo) | |
provideRouteAlternatives : true | |
}; | |
// Service de calcul d'itinéraire | |
var directionsService = new google.maps.DirectionsService(); | |
// Envoie de la requête pour calculer le parcours | |
directionsService.route(request, function(response, status){ | |
// console.log(response); | |
if(status == google.maps.DirectionsStatus.OK) | |
{ | |
$('#container-origin').removeClass('parsley-error'); | |
$('#error-itinery').hide(); | |
$('#empty-itinery').hide(); | |
// Elimine info bulle et marker | |
infoWindow.close(); | |
marker.setMap(null); | |
$blockPanel = $('#block-panel-itinary, #block-panel-itinary + .bottom'); | |
// Ouvrir le block | |
$blockPanel.addClass('open'); | |
// Tracer l'itinéraire sur la carte et les différentes étapes du parcours | |
direction.setDirections(response); | |
Master.goTo($blockPanel); | |
} | |
else { | |
$('#container-origin').addClass('parsley-error'); | |
$('#error-itinery').show(); | |
$('#empty-itinery').hide(); | |
} | |
}); | |
} | |
}, | |
printItinerary: function(){ | |
var f = document.getElementById('calculate-itinary-print'); | |
f.submit(); | |
}, | |
/** | |
* Initialise la map des magasins avec les options de base | |
* ======================================================= | |
* @see: https://developers.google.com/maps/documentation/javascript/tutorial | |
*/ | |
initMapShops: function() { | |
if( Master.d('h') ) | |
{ | |
// Coordonnée du magasin de référence | |
var currentShopId = $( document.getElementById('destination-id') ).val(), | |
destiX = parseFloat( $( document.getElementById('destination-x') ).val() ), | |
destiY = parseFloat( $( document.getElementById('destination-y') ).val() ); | |
// Position central (pour ne pas faire de boucle, j'en mes une par defaut) | |
var myLatlng = new google.maps.LatLng( destiX, destiY ); | |
// Options | |
var mapOptions = { | |
zoom: 7, | |
maxZoom: 20, | |
center: myLatlng, | |
scrollwheel: false, | |
scaleControl: false, | |
streetViewControl: false, | |
overviewMapControl: false, | |
mapTypeId: google.maps.MapTypeId.ROADMAP | |
}; | |
// Création de la carte et sauvegarde de l'objet | |
MyMap.data.objMapShops = new google.maps.Map( MyMap.data.mapShops, mapOptions); | |
// Ajout les points sur la carte | |
MyMap.setMarker(MyMap.data.objMapShops, currentShopId); | |
} | |
// On charge alors les scripts pour choisir de magasin | |
MyMap.findShop(); | |
}, | |
/** | |
* Ajoute une liste de marker sur la carte | |
* ======================================= | |
* @param {obj} objMap => object de la map | |
* @param {int} currentShopId => id du magasin de référence | |
* @param {bol} onlyCurrentShop => si l'on ne souhaite que le magasin de référence | |
* @return {obj} => quand seulement 1 marker, on le retourne | |
*/ | |
setMarker: function(objMap, currentShopId, onlyCurrentShop) { | |
// console.log(objMap, currentShopId, onlyCurrentShop); | |
if (typeof onlyCurrentShop == 'undefined') | |
onlyCurrentShop = false; | |
var s = MyMap.data.shops, | |
tmpMarker; | |
// Place sur la carte les markers avec leur bulle | |
for (var i = s.length - 1; i >= 0; i--) | |
{ | |
// Si la destination contient toutes les informations | |
if( s[i].shopId !== '' && s[i].coordX !== '' && s[i].coordY !== '' && s[i].name !== '' && s[i].address !== '' ) | |
{ | |
// Par defaut, on montre tous les magasin (onlyCurrentShop == false), si "true" => on ne montre que le magasin de référence | |
if( !onlyCurrentShop || onlyCurrentShop && s[i].shopId == currentShopId ) | |
{ | |
// Place le marker en le créant (et en le gardant en mémoire) | |
tmpMarker = MyMap.createMarker(objMap, s[i].coordX, s[i].coordY ); | |
// J'ajoute à l'objet json le marker avec la clé "marker" | |
s[i]['marker'] = tmpMarker; | |
// Si magasin de référence, on ouvrira sa bulle | |
var openShop = s[i].shopId == currentShopId ? true: false; | |
// Si pas magasin de ref, on montrera le bouton pour changer de magasin | |
var showBtn = openShop ? false : true; | |
// Place la bulle du marker en la créant(et en le gardant en mémoire) | |
var infoWindow = MyMap.createInfoBox(objMap, tmpMarker, s[i].name, s[i].address, showBtn, s[i].link, openShop); | |
} | |
} | |
} | |
return tmpMarker; | |
}, | |
/** | |
* Création d'un nouveau marker | |
* ============================ | |
* @param {obj} objMap => l'objet de la map | |
* @param {numb} x / y => coordonées du magasin | |
* @return {obj} => le marker | |
*/ | |
createMarker: function(objMap, x, y) { | |
var marker = new google.maps.Marker({ | |
position: new google.maps.LatLng( x, y), | |
map: objMap, | |
icon: MyMap.data.icon | |
}); | |
return marker; | |
}, | |
/** | |
* Creation de la bulle (en utilisant "infobox") | |
* ============================================= | |
* @param {obj} objMap => l'objet de la map | |
* @param {obj} marker => obj du marker | |
* @param {str} name => nom du magasin | |
* @param {str} address => adresse du magasin | |
* @param {bol} showBtn => si l'on montre le bouton 'choisir ce magasin' | |
* @param {str} link => lien du bouton | |
* @param {bol} openShop => si on ouvre la bulle | |
* @see: http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/docs/reference.html | |
*/ | |
createInfoBox: function(objMap, marker, name, address, showBtn, link, openShop) { | |
// Création de la bulle | |
var content = document.createElement("div"); | |
$(content).addClass('custom-modal modal-google'); | |
content.innerHTML = '<p class="title uppercase">' + | |
'Magasin Grand frais<br />' + | |
name + '</p>'+ | |
'<p class="text">' + | |
address + '</p>'; | |
// Ajout du bouton | |
if( showBtn ) | |
content.innerHTML += '<a href="' + link + '" class="btn">' + | |
'<span>Choisir ce magasin</span>' + | |
'</a>'; | |
var myOptions = { | |
content: content, | |
alignBottom: true, | |
pixelOffset: new google.maps.Size(-35, -40), // le décalage depuis le pointer | |
zIndex: 100, | |
boxStyle: { background: 'white'}, | |
closeBoxURL: MyMap.data.cross, | |
infoBoxClearance: new google.maps.Size(60, 60) // la distance entre la bulle et la bord de la carte | |
}; | |
var infoWindow = new InfoBox(myOptions); | |
// Afficher la bulle au click | |
google.maps.event.addListener(marker, 'click', function() { | |
// Fermer la bulle si il y a déjà 1 d'ouverte | |
if( MyMap.data.infowindowOpen !== '' ) | |
MyMap.data.infowindowOpen.close(); | |
// On garde en mémoire la bulle ouverte | |
MyMap.data.infowindowOpen = infoWindow; | |
infoWindow.open( objMap, marker ); | |
}); | |
// Ouvrir la bulle du magasin courant | |
if( openShop ) { | |
infoWindow.open( objMap, marker ); | |
// On garde la bulle ouverte | |
MyMap.data.infowindowOpen = infoWindow; | |
} | |
return infoWindow; | |
}, | |
/** | |
* Ouvrir infowindow et centrer la carte (optinnel) | |
* ================================================ | |
* @param {int} shopId => id de la destination | |
* @param {bol} centering => si on veut centrer la carte | |
*/ | |
showInfoWindow: function(shopId, centering) { | |
var s = MyMap.data.shops; | |
for (var i = s.length - 1; i >= 0; i--) | |
{ | |
if( s[i].shopId == shopId ) | |
{ | |
if( centering && s[i].coordX !== '' && s[i].coordY !== '' ) | |
{ | |
var center = new google.maps.LatLng( s[i].coordX, s[i].coordY ); | |
// Center la carte sur les coordonée du magasin | |
MyMap.data.objMapShops.panTo(center); | |
} | |
// On click sur le marker (donc on ouvre la bulle) | |
if( s[i].marker != '' ) | |
{ | |
setTimeout(function() { | |
google.maps.event.trigger( s[i].marker, 'click'); | |
}, 100); | |
} | |
break; | |
} | |
}; | |
}, | |
findShop: function() { | |
console.log('dans findShop'); | |
var $formSearch = $( document.getElementById('find-map') ), | |
$selectShop = $( document.getElementById('select-magasin') ); | |
console.log($formSearch); | |
// TODO: AU CLIC SUR RECHERCHER ON REGARDE SI C EST UN CODE POSTAL OU UN NOM, ON APPEL LES 2 FONCTIONS DU DESSOUS QUI RENVOI L ID DU MAGASIN SI CORRECT | |
$formSearch.on('submit', function(e) { | |
e.preventDefault(); | |
console.log('dans submit'); | |
var info = $(this).find('input[type=text]').val(), | |
shopId; | |
// Si form valide | |
if( $(this).parsley( 'validate' ) ) | |
{ | |
if( $.isNumeric( info ) && info.length == 5 ) | |
shopId = MyMap.findClosestCodePostal(info); | |
else | |
shopId = MyMap.findClosestShopName(info); | |
// Si pas false, on montre la bulle du magasin dans la carte et on le sélectionne dans la liste déroulante | |
if( shopId !== false) { | |
if( Master.d('h') ) | |
MyMap.showInfoWindow(shopId, true); | |
$selectShop.find('option[value=' + shopId + ']').prop('selected', true); | |
if( Master.d('m') ) | |
Master.goTo('select-magasin', -120); | |
} | |
} | |
}); | |
// Au changment sur le <select> des magasins, on montre la bulle correspondante | |
$selectShop.on('change', function(e) { | |
e.preventDefault(); | |
MyMap.showInfoWindow( $(this).val() , true); | |
}); | |
}, | |
// Function qui retrounera l'id ou la code magasin au code postal le plus proche | |
findClosestCodePostal: function() { | |
return 26; | |
// retourné false si vous n'avez rien trouvé | |
}, | |
// Function qui retrounera l'id ou la code magasin au code postal le plus proche | |
findClosestShopName: function() { | |
return 26; | |
// retourné false si vous n'avez rien trouvé | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment