Change the type of marker in multiple markers

1

Following the Google Maps documentation, I was able to import the data from a MySQL database.
Until I was able to apply the analysis of the type of marker and add tags to the markers, as seen in the image below.


Now, I would like to remove that label, and put different pins. I define the labels in the following routine when starting the js script:

var customLabel = {
    1: {
      label: 'S'
    },
    2: {
      label: 'E'
    },
    3: {
      label: 'M'
    },
    4: {
      label: 'T'
    },
  };

the marker is armed in the following routine:

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

I could in that same routine where I define that I put the letter S if the value is 1, ..., etc choose the type of icon to show? I tried to follow the Google maps documentation on the types of markers, but without results ... Can someone give me a hand? The customLabel is assembled from a field of the base that has the values 1, 2, 3, ... Etc

I would like to use these icons

CODE I HAVE ON THE PAGE:

TABLE FROM WHERE I TAKE THE DATA:

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;

MAIN CODE OF THE PAGE THAT LOADS THE DATA:

<!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>

FILE CODE result.php where I raise the information from the database:

<?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>';

All this information appears in the Google Maps documentation and I adapt it with my connection to the database and the result of this is the map that appears in the image above.

    
asked by MNibor 29.01.2018 в 18:06
source

2 answers

1

When you do:

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

You are setting the label attribute which is the text you see on your map, but you are omitting the icon attribute and that is why all are drawn with the default icon. You could do:

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'
    },
  };

And then:

var marker = new google.maps.Marker({
        map: map,
        position: point,
        label: icon.label,
        icon: icon.url
      });
    
answered by 30.01.2018 / 13:36
source
0

Reviewing the data you have stored and how you want to show them I leave the following fragment so you can adapt it according to your convenience.

This example shows the return of a Json format to make it more dynamic.

$.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.
});

Sample capture.

    
answered by 29.01.2018 в 22:54