Siguiendo la documentación de Google Maps, llegué a poder importar los datos desde una BD de mysql.
Hasta logré poder aplicar el análisis del tipo de marcador y le agrega etiquetas a los marcadores, como se ve en la imagen inferior.
Ahora bien, me gustaría quitar esa etiqueta, y poner pines diferentes. Las etiquetas las defino en la siguiente rutina al iniciar el script de js:
var customLabel = {
1: {
label: 'S'
},
2: {
label: 'E'
},
3: {
label: 'M'
},
4: {
label: 'T'
},
};
el marcador se arma en la siguiente rutina:
var icon = customLabel[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
label: icon.label
});
Yo podría en esa misma rutina donde defino que ponga la letra S si el valor es 1, ..., etc elegir el tipo de icono a mostrar ? Intenté seguir la documentación de Google maps sobre los tipos de marcadores, pero sin resultados... Alguien podrá darme una mano ? El customLabel lo armo a partir de un campo de la base que tiene los valores 1, 2, 3, ... Etc
CODIGO QUE TENGO EN LA PAGINA:
TABLA DESDE DONDE TOMO LOS DATOS:
CREATE TABLE `markers` (
`id` bigint(20) UNSIGNED NOT NULL,
`tipo` varchar(60) NOT NULL,
`lat` varchar(30) NOT NULL,
`lng` varchar(30) NOT NULL,
`descripcion` varchar(500) DEFAULT NULL,
`realizo` varchar(200) NOT NULL,
`idtipo` tinyint(4) NOT NULL,
`visible` tinyint(1) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CODIGO PRINCIPAL DE LA PAGINA QUE CARGA LOS DATOS:
<!DOCTYPE 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>Mapa de Google Maps</title>
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map" style="width: 800px; height:500px;"></div>
<script>
var customLabel = {
1: {
label: 'S'
},
2: {
label: 'E'
},
3: {
label: 'M'
},
4: {
label: 'T'
},
};
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(-34.609555, -58.388772),
zoom: 10
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl('resultado.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 = customLabel[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
label: icon.label
});
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>
<input type="text" name="lat" value="">
<input type="text" name="lng" value="">
<script async defer src="https://maps.googleapis.com/maps/api/js?key=*******YOUR API KEY***********&callback=initMap">
</script>
</body>
</html>
CODIGO DEL ARCHIVO resultado.php donde levanto la información de la base de datos:
<?php
session_start(); //Iniciar una nueva sesión o reanudar la existente
require '../../includes/conexion.php';
include '../../includes/funcs_pdo.php';
function parseToXML($htmlStr){
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Select all the rows in the markers table
$conexion = new Conexion();
$stmt = $conexion -> prepare("SELECT id, tipo, lat, lng, descripcion, idtipo FROM markers WHERE visible=1 ORDER BY id DESC");
$stmt->execute();
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
if ($stmt->rowCount() > 0) {
while($row_markers=$stmt->fetch(PDO::FETCH_ASSOC)){
echo '<marker ';
echo 'name="' . parseToXML($row_markers['tipo']) . '" ';
echo 'address="' . parseToXML($row_markers['descripcion']) . '" ';
echo 'lat="' . $row_markers['lat'] . '" ';
echo 'lng="' . $row_markers['lng'] . '" ';
echo 'type="' . $row_markers['idtipo'] . '" ';
echo '/>';
}
}
// End XML file
echo '</markers>';
toda esta información aparece en la documentación de Google Maps y yo lo adapte con mi conexión a la base de datos y el resultado de esto es el mapa que aparece en la imagen superior.