nyroBlog
Bannière NyroBlog, par Nyro
Image par Nyro - ?

Revue de presse de la calculette freemobile

Vous avez peut-etre (sûrement ?) entendu parlé de la calculatrice pour savoir s'il est avantageux de changer d'opérateur mobile, que j'ai mis en place une heure après le l'annonce de l'offre de free mobile.

Comme j'ai été le premier à mettre en ligne cet outil, l'echo a été fulgurant et les partages sur Twitter et Facebook ont dépassé tout ce que j'aurai jamais pu imaginer.

En attendant un vrai retour sur cette expérience à tête reposée, voici la revue de presse (qui évoluera au fil du temps) de cette fabuleuse expérience.

 

Et je ne le dirai jamais assez, mais merci encore à tous ceux qui ont partagé ce lien, qui m'ont conseillé, donné des idées d'amélioration, etc...

Un grand merci à Aymeric aka Miho qui m'a proposé un graphisme rapidement.

Google Map on demand with jQuery

It's pretty common to embed a map on a contact page. But you want this map only on this page. So you don't need to load the Google Map API on every page of your site

Coupled with adress microdata (which you should already have in place), it becomes easy to load a google map on demand with a marker to the desired address.

1. Load Google Map

To load google map is simple. Just call in the URL of the Ajax API. But we must ensure proper load and execute the following script when it's completly loaded. Otherwise, you call functions that doesn't exist on the page.

A simple callback on the load of the script isn't sufficient because Google actually loads an other JS file, corresponding to the current Google Map API version.

I you readSi the doc, you understand you can add a callback that will be called by the APi once loaded

We'll write a function to load this JS file and add a callback given as a parameter. A small addition will permit to load it only one time.

var gmapUrl = 'http://maps.google.com/maps/api/js?sensor=false',
	gmapLoaded = false,
	loadGmap = function(clb) {
		if (!gmapLoaded) {
			window.gMapClb = function() {
				window.gMapClb = null;
				gmapLoaded = true;
				clb();
			};
			$.ajax({url: gmapUrl+'&callback=gMapClb', dataType: 'script'});
		} else {
			clb();
		}
	};

We can now dynamically load the Google Map API and execute a function when everything has come up.

2. Read microdata

The purpose of the code we're writing is to be called on a container, find Address microdata and display the corresponding map.

Once the address is found, we will use geocode from Googme Map to locate the map and add a marker.

Reading microdata is pretty easy thanks to jQuery. We're adding every element in an array:

var adr = me.find('[itemtype="http://data-vocabulary.org/Address"]');
if (adr.length) {
	var search = [],
		elm;
	$.each(['street-address', 'postal-code', 'locality', 'region', 'country-name'], function() {
		elm = adr.find('[itemprop="'+this+'"]');
		if (elm.length)
			search.push(elm.text());
	});
}

Once the address is on the search Array, it only remains to call the geocoder to find its location.

3. Locate address and show the map

We've got the address. We can load the Google Map API on demand with a callback. We still have to find the address location. And if we have it, show the map. To search it, I won't discuss here all the details of Geocoder.

When getting a result from geocoder, a div[class=map] is append to the containing element and the Google Map instance will be created on it. It's the CSS duty to positionnate this div and giving it a height and width.

To allow a toffle of this map, we will save a reference of the map container, a reference of the Google map and the location of the result. A marker is automaticall added at the result location.

loadGmap(function() {
	var geocoder = new google.maps.Geocoder();
	geocoder.geocode({address: search.join(', ')}, function(results, status) {
		if (results.length && status == google.maps.GeocoderStatus.OK) {
			var map = $('<div class="map" />').appendTo(me),
				GMap = new google.maps.Map(map.get(0), {
					center: results[0].geometry.location,
					mapTypeId: google.maps.MapTypeId.ROADMAP,
					zoom: defaultZoom
				});
			new google.maps.Marker({
				map: GMap,
				visible: true,
				position: results[0].geometry.location
			})
			me.data('gmap', {
				map: map,
				GMap: GMap,
				location: results[0].geometry.location
			});
		}
	});
});

Note the defaultZoom variable defined elsewhere. (required to create a map)

 

4. Put it all together

We have the 3 necessary elements to view the map. Let's put that in a jQuery plugin, add functionnality to hide/show it on each call of this plugin and we get this:

$(function() {
	var defaultZoom = 15,
		gmapUrl = 'http://maps.google.com/maps/api/js?sensor=false',
		gmapLoaded = false,
		loadGmap = function(clb) {
			if (!gmapLoaded) {
				window.gMapClb = function() {
					window.gMapClb = null;
					gmapLoaded = true;
					clb();
				};
				$.ajax({url: gmapUrl+'&callback=gMapClb', dataType: 'script'});
			} else
				clb();
		};
	
	$.fn.extend({
		myGmap: function() {
			return this.each(function() {
				var me = $(this);
				if (!me.data('gmap')) {
					var adr = me.find('[itemtype="http://data-vocabulary.org/Address"]');
					if (adr.length) {
						var search = [],
							elm;
						$.each(['street-address', 'postal-code', 'locality', 'region', 'country-name'], function() {
							elm = adr.find('[itemprop="'+this+'"]');
							if (elm.length)
								search.push(elm.text());
						});
						if (search.length) {
							loadGmap(function() {
								var geocoder = new google.maps.Geocoder();
								geocoder.geocode({address: search.join(', ')}, function(results, status) {
									if (results.length && status == google.maps.GeocoderStatus.OK) {
										var map = $('<div class="map" />').appendTo(me),
											GMap = new google.maps.Map(map.get(0), {
												center: results[0].geometry.location,
												mapTypeId: google.maps.MapTypeId.ROADMAP,
												zoom: defaultZoom
											});
										new google.maps.Marker({
											map: GMap,
											visible: true,
											position: results[0].geometry.location
										})
										me.data('gmap', {
											map: map,
											GMap: GMap,
											location: results[0].geometry.location
										});
									}
								});
							});
						}
					}
				} else {
					me.data('gmap').map.fadeToggle(function() {
						if (me.data('gmap').map.is(':not(:visible)')) {
							me.data('gmap').GMap.setZoom(defaultZoom);
							me.data('gmap').GMap.panTo(me.data('gmap').location);
						}
					});
				}
			});
		}
	});
});

When the map is hidden, the map is centered again and the default zoom is resset to the default value.

Enjoy!

Version française de ce billet.

Carte Google Map à la volée avec jQuery

Il n'est pas rare de vouloir intégrer une carte sur une page contact d'un site. Mais on ne veut afficher une carte uniquement sur cette page. C'est donc dommage de charger le javascript de Google Map sur toutes les pages.

Couplé à des micro-data d'adresse (que vous devriez déjà avoir mis en place), il devient facile de charger une carte google à la volée avec un marker à l'adresse désirée.

1. Charger Google Map

Pour charger google map, c'est simple. Il suffit d'appeler en Ajax l'URL de l'API. Mais il faut aussi s'assurer de son bon chargement et n'exécuter la suite du script que lorsqu'il est complètement chargé. Sinon, on se retrouve à appeler des fonctions qui n'existent pas encore sur la page.

Un simple callback sur le chargement du script ne suffit pas puisque Google charge encore un autre fichier JS qui correspond en réalité à la dernière version de l'API.

Si l'on lit la doc, on comprend que l'on peut ajouter un callback que l'API appelera une fois chargée.

Nous allons donc écrire une fonction pour charger le fichier JS et appeler un callback donné en paramètre lorsque celle sera en place. Un petit ajout permettra de ne charger qu'une seule fois si on exécute plusieurs la fonction :

var gmapUrl = 'http://maps.google.com/maps/api/js?sensor=false',
	gmapLoaded = false,
	loadGmap = function(clb) {
		if (!gmapLoaded) {
			window.gMapClb = function() {
				window.gMapClb = null;
				gmapLoaded = true;
				clb();
			};
			$.ajax({url: gmapUrl+'&callback=gMapClb', dataType: 'script'});
		} else {
			clb();
		}
	};

On peut donc maintenant charger dynamiquement l'API de Google Map, et exécuter un code lorsque tout est arrivé.

2. Lire le micro-format

Le but du code que nous sommes en train d'écrire permettra d'être appelé sur un bloc contenant, de chercher le micro-format d'adresse et d'afficher la carte correspondante.

Une fois les informations de l'adresse trouvées, nous l'utiliserons avec le geocoder de Google Map pour positionner la carte et ajouter le marker.

La lecture du mirco-format est hyper simple, on met chacun des éléments à la suite dans un tableau :

var adr = me.find('[itemtype="http://data-vocabulary.org/Address"]');
if (adr.length) {
	var search = [],
		elm;
	$.each(['street-address', 'postal-code', 'locality', 'region', 'country-name'], function() {
		elm = adr.find('[itemprop="'+this+'"]');
		if (elm.length)
			search.push(elm.text());
	});
}

Une fois cette adresse complétée dans le tableau search, il ne restera plus qu'à appeler le geocoder pour chercher cette adresse.

3. Chercher l'adresse et afficher la carte

Nous avons l'adresse. Nous savons charger la Google Map API à la volée avec un callback. Il ne reste plus qu'à chercher l'adresse, et si l'on trouve, affiché cette carte. Pour la recherche d'adresse, je ne détaillerai pas ici les détails du Geocoder.

Au résultat du geocoder, on ajouter une div[class=map] à l'élément contenant et l'instance de la carte Google sera créée dans cette div. Charge à la CSS du site de positionner cette div, en lui donnant une hauteur et largeur adequat.

Pour permettre un toggle de cette map, on enregistrera dans une data la référence du conteneur de la carte, la référence de la carte et la position du résultat. Le marker est automatiquement ajouté à l'emplacement du résultat.

loadGmap(function() {
	var geocoder = new google.maps.Geocoder();
	geocoder.geocode({address: search.join(', ')}, function(results, status) {
		if (results.length && status == google.maps.GeocoderStatus.OK) {
			var map = $('<div class="map" />').appendTo(me),
				GMap = new google.maps.Map(map.get(0), {
					center: results[0].geometry.location,
					mapTypeId: google.maps.MapTypeId.ROADMAP,
					zoom: defaultZoom
				});
			new google.maps.Marker({
				map: GMap,
				visible: true,
				position: results[0].geometry.location
			})
			me.data('gmap', {
				map: map,
				GMap: GMap,
				location: results[0].geometry.location
			});
		}
	});
});

On remarquera la variable defaultZoom défini ailleurs. (indispensable pour la création d'une map)

 

4. On assemble le tout

On a les 3 éléments indispensable pour afficher cette carte. Mettons tout ceci dans un plugin jQuery, ajoutons la fonctionnalité de caché/affiché la carte à chaque appel de ce plugin et nous obtenons ceci :

$(function() {
	var defaultZoom = 15,
		gmapUrl = 'http://maps.google.com/maps/api/js?sensor=false',
		gmapLoaded = false,
		loadGmap = function(clb) {
			if (!gmapLoaded) {
				window.gMapClb = function() {
					window.gMapClb = null;
					gmapLoaded = true;
					clb();
				};
				$.ajax({url: gmapUrl+'&callback=gMapClb', dataType: 'script'});
			} else
				clb();
		};
	
	$.fn.extend({
		myGmap: function() {
			return this.each(function() {
				var me = $(this);
				if (!me.data('gmap')) {
					var adr = me.find('[itemtype="http://data-vocabulary.org/Address"]');
					if (adr.length) {
						var search = [],
							elm;
						$.each(['street-address', 'postal-code', 'locality', 'region', 'country-name'], function() {
							elm = adr.find('[itemprop="'+this+'"]');
							if (elm.length)
								search.push(elm.text());
						});
						if (search.length) {
							loadGmap(function() {
								var geocoder = new google.maps.Geocoder();
								geocoder.geocode({address: search.join(', ')}, function(results, status) {
									if (results.length && status == google.maps.GeocoderStatus.OK) {
										var map = $('<div class="map" />').appendTo(me),
											GMap = new google.maps.Map(map.get(0), {
												center: results[0].geometry.location,
												mapTypeId: google.maps.MapTypeId.ROADMAP,
												zoom: defaultZoom
											});
										new google.maps.Marker({
											map: GMap,
											visible: true,
											position: results[0].geometry.location
										})
										me.data('gmap', {
											map: map,
											GMap: GMap,
											location: results[0].geometry.location
										});
									}
								});
							});
						}
					}
				} else {
					me.data('gmap').map.fadeToggle(function() {
						if (me.data('gmap').map.is(':not(:visible)')) {
							me.data('gmap').GMap.setZoom(defaultZoom);
							me.data('gmap').GMap.panTo(me.data('gmap').location);
						}
					});
				}
			});
		}
	});
});

Lorsqu'on cache la carte, on en profite pour recentrer la map et remettre le niveau de zoom à celui paramétré par défaut.

Enjoy!

English version of this post.

jQuery UI Position : Change the collision function

For a tooltip script quickly developed for a big current project I'm working on, I'm using the position plugin of jQuery UI.

This function allow you to positionnate an element exactly how you need relative to another element. The ultimate function when dealing with tooltip.

This plugin comes with a detection collision with the windows. In other words, if the positionnate element goes outside the window, then it's positionnate on the other side.

The only problem is that there is no possibility to detect when this collision is happening.

By reading the code I found a simple solution to detect it and a way to add a class to the positionnating element. In my case it is useful in order to change the arrow of the tooltip on the other side.

 

Here is the code:

var currentlyPositionning,
    initPos;
$.ui.position.custom = {
    left: function(position, data) {
        initPos = position.left;
        $.ui.position.flip.left(position, data);
        if (initPos != position.left) {
            currentlyPositionning.addClass('tooltipFlip');
        }
    },
    top: function(position, data) {
        initPos = position.top;
        $.ui.position.flip.top(position, data);
        if (initPos != position.top) {
            currentlyPositionning.addClass('tooltipFlip');
        }
    }
};

Actually we're simply adding a custom option to the plugin. For each top ou left properties, the code is checking if the value is changed by the original collision detection function. If it's the case, then we're adding a class to the element.

You probably notice the currentlyPositionning variable; It should correspond to the element that is currently positionned. Indeed there is no information on the data object to let us find it back.

 

Finally, to use this new functionnality you should call the position function as following::

currentlyPositionning = elem;
elem.position({
    of: me,
    my: 'left bottom',
    at: 'right top',
    offset: '15px',
    collision: 'custom'
});

Et voilà.

Version française de ce billet.

jQuery UI Position : Modifier la fonction de collision

Pour un script de tooltip développé rapidement sur un gros projet en cours, j'ai utilisé le plugin position de jQuery UI.

Cette fonction permet de positionner exactement comme on veut un élément par rapport à un autre. La fonction utlime pour une infobulle.

Et ce plugin vient même avec une détection de collision avec la fenêtre. Autrement dit, si l'élément positionné dépasse de la fenêtre, alors on le positionne de l'autre côté. Un must !

Le seul problème est qu'il n'existe actuellement aucune possibilité de détecter lorsque cela arrive.

En lisant le code de ce plugin, il existe en réalité un moyen très simple pour détecter cette collision et ajouter une classe à l'élément positionné. Dans mon cas, cela me permet de modifier l'affichage de l'infobulle de façon à avoir la flèche du bon côté.

 

Le code en question :

var currentlyPositionning,
    initPos;
$.ui.position.custom = {
    left: function(position, data) {
        initPos = position.left;
        $.ui.position.flip.left(position, data);
        if (initPos != position.left) {
            currentlyPositionning.addClass('tooltipFlip');
        }
    },
    top: function(position, data) {
        initPos = position.top;
        $.ui.position.flip.top(position, data);
        if (initPos != position.top) {
            currentlyPositionning.addClass('tooltipFlip');
        }
    }
};

En réalité, on ajoute simplement une option custom au plugin position. Pour chacune des propriétés top ou left pour lesquels le plugin détecte une collision, on vérifie si la propriété a été modifié par la fonction de détection originelle du plugin. Et si oui, dans mon cas, j'ajoute une classe à l'élément.

Vous avez sans doute remarqué la variable currentlyPositionning ; Elle doit correspondre à l'élément sur lequel on applique actuellement la position. En effet, aucune information dans l'objet data ne permet de remonter jusqu'à cet élément.

 

Enfin, pour utiliser cette nouvelle fonctionnalité, il suffit d'appeler le plugin position comme suit :

currentlyPositionning = elem;
elem.position({
    of: me,
    my: 'left bottom',
    at: 'right top',
    offset: '15px',
    collision: 'custom'
});

Et voilà, le tour est joué.

 

English version of this post.