Personalizando markers con Google maps API

0
3100

En esta entrada vamos a personalizar marcas de Google Maps API en función de su categoría.

Antes de empezar con Google Maps API, necesitaremos mysql, PHP5, apache2 y una plataforma para ejecutarlo, cualquier otro gestor de base de datos o servidor web os servirá igual.

Para utilizar la API de Google Maps necesitaremos una API-KEY. Para ello deberemos ir a la consola de Google Developers y generar una.

Mediante la siguiente URL de Google Maps tendremos que dar a obtener clave.

Generaremos un nuevo proyecto y nos guardaremos en un notepad nuestra API-KEY.

El siguiente paso es generar la base de datos. Accederemos a nuestro mysql

mysql -u «usuario» -p

Entroducimos la password y proseguimos, tenemos dos opciones, crear la tabla en nuestra base de datos de producción dónde queramos integrar el Google Maps o crear una nueva. En mi caso, crearemos una base de datos nuevas ya que solamente haremos una prueba.

create database maps;

use maps;

CREATE TABLE `markers` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 60 ) NOT NULL ,
`address` VARCHAR( 80 ) NOT NULL ,
`lat` FLOAT( 10, 6 ) NOT NULL ,
`lng` FLOAT( 10, 6 ) NOT NULL ,
`type` VARCHAR( 30 ) NOT NULL
) ENGINE = MYISAM ;

INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`) VALUES ('Gatuno', 'Barcelona', '41.385064', '2.173403', 'cat');
INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`) VALUES ('Perruno', 'Valencia', '39.469907', '-0.376288', 'dog');
INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`) VALUES ('Pajaruno', 'Madrid', '40.416775', '-3.703790', 'bird');

Podemos copiar directamente todos los comandos en la consola de mysql. En este tramo hemos creado una base de datos maps, que contiene una tabla llamada markers. Con varias columnas, el campo ID que es nuestro primary key, campo nombre, dirección, latitud, longitud y tipo.

Luego hemos introducido en la tabla markers una serie de datos de prueba. Cabe destacar que lo ideal para capturar estos datos es utilizar alguna herramienta de geolocalización como la API de geolocation de Google, con ella podremos recopilar los datos de latitud y longitud de forma desatendida ya que como podréis comprobar, en esta práctica los hemos introducido manualmente.

Una vez hecho esto ya podemos montar el código:

index.php

<!DOCTYPE html >
<html>
<head>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
        <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
        <title>Using MySQL and PHP with Google Maps</title>
        <style>
                /* Always set the map height explicitly to define the size of the div
                 * element that contains the map. */
                #map {
                        height: 100%;
                }
                /* Optional: Makes the sample page fill the window. */
                html, body {
                        height: 100%;
                        margin: 0;
                        padding: 0;
                }
        </style>
</head>

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

<script>
    var customIcon = {
        cat: {
            icons: 'cat.png'
        },
        dog: {
            icons: 'dog.png'
        },
        bird: {
            icons: 'bird.png'
        }
    };
    function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
            center: new google.maps.LatLng(40.438072, -3.679536),
            zoom: 7
        });
        var infoWindow = new google.maps.InfoWindow;

        // Change this depending on the name of your PHP or XML file
        downloadUrl('./content.php', function(data) {
            var xml = data.responseXML;
            var markers = xml.documentElement.getElementsByTagName('marker');
            Array.prototype.forEach.call(markers, function(markerElem) {
                var name = markerElem.getAttribute('name');
                var address = markerElem.getAttribute('address');
                var type = markerElem.getAttribute('type');
                var point = new google.maps.LatLng(
                    parseFloat(markerElem.getAttribute('lat')),
                    parseFloat(markerElem.getAttribute('lng')));

                var infowincontent = document.createElement('div');
                var strong = document.createElement('strong');
                strong.textContent = name;
                infowincontent.appendChild(strong);
                infowincontent.appendChild(document.createElement('br'));

                var text = document.createElement('text');
                text.textContent = address;
                infowincontent.appendChild(text);
                var icon = customIcon[type] || {};
                var marker = new google.maps.Marker({
                    map: map,
                    position: point,
                    icon: icon.icons
                });
                marker.addListener('click', function() {
                    infoWindow.setContent(infowincontent);
                    infoWindow.open(map, marker);
                });
            });
        });
    }
    function downloadUrl(url, callback) {
        var request = window.ActiveXObject ?
            new ActiveXObject('Microsoft.XMLHTTP') :
            new XMLHttpRequest;

        request.onreadystatechange = function() {
            if (request.readyState === 4) {
                request.onreadystatechange = doNothing;
                callback(request, request.status);
            }
        };

        request.open('GET', url, true);
        request.send(null);
    }

    function doNothing() {}
</script>
<script async defer
        src="https://maps.googleapis.com/maps/api/js?key=AQUI_VA_TU_API_KEY_DE_GOOGLE&callback=initMap">
</script>
</body>

database-connect.php

<?php
$host="tu_host";
$username="tu_user";
$password="tu_password";
$database="tu_database";
?>

content.php

<?php

require("database-connect.php");

// Start XML file, create parent node

$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);

// Opens a connection to a MySQL server

//$connection=mysql_connect ('localhost', $username, $password);
$connection = mysqli_connect($host, $username, $password);

//if (!$connection) {  die('Not connected : ' . mysql_error());}
if (!$connection) {  die('Not connected : ' . mysqli_error($connection));}

// Set the active MySQL database

//$db_selected = mysql_select_db($database, $connection);
$db_selected = mysqli_select_db($connection, $database);
if (!$db_selected) {
//	die ('Can\'t use db : ' . mysql_error());
	die ('Can\'t use db : ' . mysqli_error($connection));
}

// Select all the rows in the markers table

$query = "SELECT * FROM markers WHERE 1";
//$result = mysql_query($query);
$result = mysqli_query($connection, $query);
if (!$result) {
//	die('Invalid query: ' . mysql_error());
	die('Invalid query: ' . mysqli_error($connection));
}

header("Content-type: text/xml");

// Iterate through the rows, adding XML nodes for each

//while ($row = @mysql_fetch_assoc($result)){
while ($row = @mysqli_fetch_assoc($result)){
	// Add to XML document node
	$node = $dom->createElement("marker");
	$newnode = $parnode->appendChild($node);
	$newnode->setAttribute("name",$row['name']);
	$newnode->setAttribute("address", $row['address']);
	$newnode->setAttribute("lat", $row['lat']);
	$newnode->setAttribute("lng", $row['lng']);
	$newnode->setAttribute("type", $row['type']);
}

echo $dom->saveXML();

?>

Las lineas comentadas corresponden a PHP 5.6

En la siguiente entrada deberemos introducir nuestro clave API-KEY copiada anteriormente, recomendamos restringir el acceso a dicha clave para IPS públicas por ejemplo, así evitaremos usos no autorizados de nuestra clave.

src="https://maps.googleapis.com/maps/api/js?key=AQUI_VA_TU_API_KEY_DE_GOOGLE&callback=initMap">

Todo el código utilizado es de las propias plantillas de Google developers con una pequeña modificación. Encontraréis dichas guías en la siguiente página de Google Maps API.

Básicamente en esta parte del código de index.php es donde hacemos el cambio. Le indicamos que para el constructor del marker seleccionemos la variable icon, la cual utiliza la variable customIcon en función de su categoría, ya definida anteriormente.

var icon = customIcon[type] || {}; 
var marker = new google.maps.Marker({ map: map, position: point, icon: icon.icons
var customIcon = { 
cat: { icons: 'cat.png' }, 
dog: { icons: 'dog.png' }, 
bird: { icons: 'bird.png' } };

Simplemente cambiando los archivos *.png y sustituyendo por los iconos que queramos podremos comprobar que nos asignará una imagen u otra en función de la categoría definida en nuestra base de datos. Esto se puede extrapolar a cualquier cosa. Al igual a que es ampliable hasta que nosostros queramos.

Podéis ver el siguiente entorno funcionando en la siguiente URL:

Prueba de Google Maps

Un saludo y hasta la próxima!.

DEJA UNA RESPUESTA

Por favor ingrese su comentario!
Por favor ingrese su nombre aquí