1

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.

IMAGENES
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

Me gustaría usar estos iconos iconos


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('<','&lt;',$htmlStr);
  $xmlStr=str_replace('>','&gt;',$xmlStr);
  $xmlStr=str_replace('"','&quot;',$xmlStr);
  $xmlStr=str_replace("'",'&#39;',$xmlStr);
  $xmlStr=str_replace("&",'&amp;',$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.

5

2 respuestas 2

1

Cuando haces:

var marker = new google.maps.Marker({
        map: map,
        position: point,
        label: icon.label
      });

Estás fijando el atributo label que es el texto que ves en tu mapa, pero estás omitiendo el atributo icon y por eso todos se dibujan con el ícono por defecto. Podrías hacer:

var customLabel = {
    1: {
      label: 'S',
      url: 'http://labs.google.com/ridefinder/images/mm_20_purple.png'
    },
    2: {
      label: 'E',
      url: 'http://labs.google.com/ridefinder/images/mm_20_yellow.png'
    },
    3: {
      label: 'M',
      url: 'http://labs.google.com/ridefinder/images/mm_20_blue.png'
    },
    4: {
      label: 'T',
      url: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
    },
  };

Y luego:

var marker = new google.maps.Marker({
        map: map,
        position: point,
        label: icon.label,
        icon: icon.url
      });
1
  • EXCELENTE !!! MUCHISIMAS GRACIAS @amenadiel !!!... igual creo que los iconos que elegí son horribles jajajajajaja
    – MNibor
    el 30 ene. 2018 a las 13:32
0

Revisando los datos que tienes almacenados y como deseas mostrarlos te dejo el siguiente fragmento para que lo adaptes de acuerdo a tu conveniencia.

Este ejemplo muestra la devolución de un formato Json para hacerlo mas dinámico.

$.each(data.mensaje, function(i, item){
//Obteniendo las coordenadas del punto
var posi = new google.maps.LatLng(item.mapa_latitud, item.mapa_longitud);//La posicion del marcador.

var testtitle = item.nombreubicacion;
var etiqueta = item.etiqueta;
//Ruta de la imagen
var iconocliente = 'img/cliente.png';//Obteniendo de directorio local
/*Proveedor de iconos en este caso la direccion que proporciona google*/
var iconoproveedor = 'https://png.icons8.com/street-view/nolan/60';//Aqui escribe la url de google dependiendo de la imagen que necesites, puedes cambiar por un switch en vez del condicional IF. (http://maps.gstatic.com/mapfiles/ridefinder-images/mm_20_green.png)
//cambiar etiqueta
if(etiqueta == "C"){
    etiqueta = "C";
    icono=iconocliente;
}
else{
    etiqueta = "P";
    icono=iconoproveedor;
}
// Leer las propiedades del marcador
var marca = new google.maps.Marker({
    idMarcador:item.mapa_id,
    position:posi,
    clieID:item.cliente_id,
    cx:item.mapa_latitud,
    cy:item.mapa_longitud,
    lugar:item.nombre_ubicacion,
    title:testtitle,
    whois:item.nombreubicacion,
    map:mapa,
    icon:icono//Renderizar propiedad segun corresponda.
});

Captura de ejemplo. introducir la descripción de la imagen aquí

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.