Creating maps with Gmaps.js

First of all, this entrance have been selected by webucator for an educational video. You can see the video here. I encourage you to join their courses: Javascript courses.

This entrance is dedicated of how to use Google Maps API by using Gmaps.js, a library to easyfy working with the Google Maps API, and it’s based on the jQuery library.

Google Maps is one of the most sucessful apps from Google, but working with the API is a little bit tricky.

A small example with gmaps.js

What a better way to start with gmaps.js that writting a small example to see how useful this library is. You can link here to try, and the code is also available on  GitHub.

The app is a very simple app to calculate paths to go driving. I have added a button to compress the route (recalculate the path from starting point to last point). Also, the point information will be stored using localStorage , giving the user the option to clear with another button.

To start building the example, let’s use PureCSS to beautify the front-end part. I have also included CSS to make it responsive desing (I have tried!!). Of course, I need jQuery.js (another option is to use zepto.js, a light version of jQuery, and it’s the one used for out purpose) and GMaps.js, using the last version available (I have used 0.4.11).

The HTML code:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Curso Firefox OS - Ejercicio Final Semana 4</title>

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- pureCSS -->
<link rel="stylesheet" href="css/manejandodatos_purecss.css" media="screen" />
<link href="css/movil.css" rel="stylesheet" type="text/css" media="handheld, only screen and (max-device-width: 540px)" />
<link rel="stylesheet" href="css/purecss-min.css"/>
<link rel="stylesheet" href="css/smoke.css"/>

<script type="text/javascript" src="js/zepto.min.js"></script>
<script type="text/javascript" src="js/smoke.min.js"></script>
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" src="js/gmaps_0.4.11.js"></script>

</head>

<body>

<header>

<h1>Firefox OS - Geolocalización</h1>

</header>



<div id="map"></div>


<footer class="fixed-bar">
<button id="compactar" class="pure-button">Compactar</button>
<button id="limpiar" class="pure-button">Limpiar</button>
Desarrollado por <a href="http://www.manejandodatos.es" target="_blank">www.manejandodatos.es</a>
</footer>

</body>
</html>

Javascript code

For the Javascript code, let’s declare a map and a ruta variables (this variable is an Array whose values will be the same as stored on the localStorage (it is important to say that for storing an Array on localStoraje we need to use the functions JSON.stringify y JSON.parse, the first for writting and the second for reading).

It is neccesary also new functions like clear to clear the path variable and also to clear the data on localStorage. the main function is geolocalizar, that create and present the map, or show warnings error (in case they arise). We need two more functions, one for creating the path (function enlazaMarcador) and another one mostrar for painting the path and markers on the map.

The final Javascript code is:


var map;
var ruta = [];

$(function(){
function clear () { ruta = []; localStorage.ruta = JSON.stringify(ruta); };

$('#compactar').on('click', function () {
ruta1 = ruta[0]; ruta2 = ruta[ruta.length - 1];
ruta = [ruta1, ruta2];
geolocalizar();
} );
$('#limpiar').on('click', function () {
clear();
geolocalizar();
} );

function muestra (origen, fin) {
// muestra ruta entre marcas anteriores y actuales
map.drawRoute({
origin: origen,  // origen en coordenadas anteriores
destination: fin, // destino en coordenadas del click o toque actual
travelMode: 'driving',
strokeColor: '#3B9313',
strokeOpacity: 0.6,
strokeWeight: 5
});
map.addMarker({ lat: fin[0], lng: fin[1]});  // pone marcador en mapa
map.setCenter( fin[0], fin[1]);
};

function enlazarMarcador(e){
var lat2 = e.latLng.lat(); var lng2 = e.latLng.lng();  // guarda coords para marca siguiente
if (ruta.length &gt; 0)
{ muestra(ruta[ruta.length - 1], [lat2, lng2]) }
else {
map.addMarker({ lat: lat2, lng: lng2});  // pone marcador en mapa
}
ruta.push([lat2, lng2]);
// console.log(ruta);
localStorage.ruta = JSON.stringify(ruta);
};

function geolocalizar(){
GMaps.geolocate({
success: function(position){
var lt, ln;
if (ruta.length == 0) {
lt = position.coords.latitude;  // guarda coords en lat y lng
ln = position.coords.longitude;
}
else
{ lt = ruta[0][0]; ln = ruta[0][1];    }
map = new GMaps({  // muestra mapa centrado en coords [lat, lng]
el: '#map',
lat: lt,
lng: ln,
//setZoom: 8,
click: enlazarMarcador,
tap: enlazarMarcador
});
if (ruta.length &gt; 0) {
map.addMarker({ lat: ruta[0][0], lng: ruta[0][1]});  // marcador en [lat, lng]
}
if (ruta.length &gt; 1) {
for (i=1; i&lt;ruta.length; i++) { muestra(ruta[i-1], ruta[i]); }
}
map.fitZoom();
},
error: function(error) { smoke.alert('Error en la Geolocalización: '+error.message); },
not_supported: function(){ smoke.alert(&quot;Su navegador no soporta geolocalización&quot;); },
});
};

try { ruta = JSON.parse(localStorage.ruta);  // console.log( ruta.length );
}   catch (e) { console.log(&quot;Parsing error:&quot; + e); }
geolocalizar();
});

The final result:

ejemplo GMaps

using GMaps

I also added more features, for example, every time a new locations is added to the route, the map will be centered on this point (setCenter function). And even more, because when you refresh the app and a route exists, the zoom is applied to the whole route (fitZoom function).

Documentation of gmaps.js is available here, with lots of examples for you to try with this library, such as load KML files, paint polygons and polylines, work with JSON files, …

MapStylr

To end with, I would like to introduce you to MapStylr, a tool for creating online maps without programming a line of code. I haven’t tried.

Have a nice day!