Saltar al contenido

¿Cómo filtrar los marcadores de Google Maps en una matriz con seleccionar?

Te doy la bienvenida a nuestro espacio, en este lugar hallarás la respuesta a lo que estás buscando.

Solución:

Debe agregar una categoría como propiedad de marcador.

markers1 = [
    ['0', 'Title 1', 52.4357808, 4.991315699999973, 'car'],
    ['1', 'Title 2', 52.4357808, 4.981315699999973, 'third'],
    ['2', 'Title 3', 52.4555687, 5.039231599999994, 'car'],
    ['3', 'Title 4', 52.4555687, 5.029231599999994, 'second']
];

Crear marcador. El marcador es un objeto, así que agregue una categoría como propiedad.

var category = markers1[i][4];
var pos = new google.maps.LatLng(markers1[i][2], markers1[i][3]);
marker1 = new google.maps.Marker(
    position: pos,
    map: map,
    category: category,
    icon: image1
);

Y en el cambio de selección, llame a la función que verifica si la categoría es la misma que la seleccionada.

/**
 * Function to filter markers by category
 */

filterMarkers = function(category)

   for (i = 0; i < gmarkers1.length; i++)   

Ejemplo de trabajo

var gmarkers1 = [];
var markers1 = [];
var infowindow = new google.maps.InfoWindow(
    content: ''
);

// Our markers
markers1 = [
    ['0', 'Title 1', 52.4357808, 4.991315699999973, 'car'],
    ['1', 'Title 2', 52.4357808, 4.981315699999973, 'third'],
    ['2', 'Title 3', 52.4555687, 5.039231599999994, 'car'],
    ['3', 'Title 4', 52.4555687, 5.029231599999994, 'second']
];

/**
 * Function to init map
 */

function initialize() 
    var center = new google.maps.LatLng(52.4357808, 4.991315699999973);
    var mapOptions = 
        zoom: 12,
        center: center,
        mapTypeId: google.maps.MapTypeId.TERRAIN
    ;

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    for (i = 0; i < markers1.length; i++) 
        addMarker(markers1[i]);
    


/**
 * Function to add marker to map
 */

function addMarker(marker) 
    var category = marker[4];
    var title = marker[1];
    var pos = new google.maps.LatLng(marker[2], marker[3]);
    var content = marker[1];

    marker1 = new google.maps.Marker(
        title: title,
        position: pos,
        category: category,
        map: map
    );

    gmarkers1.push(marker1);

    // Marker click listener
    google.maps.event.addListener(marker1, 'click', (function (marker1, content) 
        return function () 
            console.log('Gmarker 1 gets pushed');
            infowindow.setContent(content);
            infowindow.open(map, marker1);
            map.panTo(this.getPosition());
            map.setZoom(15);
        
    )(marker1, content));


/**
 * Function to filter markers by category
 */

filterMarkers = function (category) 
    for (i = 0; i < gmarkers1.length; i++) 
        marker = gmarkers1[i];
        // If is same category or category not picked
        if (marker.category == category 


// Init map
initialize();
#map-canvas 
    width: 500px;
    height: 500px;


Filtrar por múltiples categorías en el marcador

EDITAR para el comentario de @Myoji

Para usar varias categorías en cada marcador, simplemente agréguelas como array y editar if condición en filterMarkers.

markers1 = [
    ['0', 'Title 1', 52.4357808, 4.991315699999973, ['car', 'second']],
    ['1', 'Title 2', 52.4357808, 4.981315699999973, ['third']],
    ['2', 'Title 3', 52.4555687, 5.039231599999994, ['car', 'third']],
    ['3', 'Title 4', 52.4555687, 5.029231599999994, ['second']]
];

Y filterMarkers sería

/**
 * Function to filter markers by category
 */

filterMarkers = function(category)
{
   for (i = 0; i < gmarkers1.length; i++)  category.length == 0)
      
          marker.setVisible(true);
      
      // Categories don't match 
      else
                
          marker.setVisible(false);
      
      

Ejemplo de trabajo

var gmarkers1 = [];
var markers1 = [];
var infowindow = new google.maps.InfoWindow(
    content: ''
);

// Our markers
markers1 = [
  ['0', 'Title 1', 52.4357808, 4.991315699999973, ['car', 'second']],
  ['1', 'Title 2', 52.4357808, 4.981315699999973, ['third']],
  ['2', 'Title 3', 52.4555687, 5.039231599999994, ['car', 'third']],
  ['3', 'Title 4', 52.4555687, 5.029231599999994, ['second']]
];

/**
 * Function to init map
 */

function initialize() 
    var center = new google.maps.LatLng(52.4357808, 4.991315699999973);
    var mapOptions = 
        zoom: 12,
        center: center,
        mapTypeId: google.maps.MapTypeId.TERRAIN
    ;

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    for (i = 0; i < markers1.length; i++) 
        addMarker(markers1[i]);
    


/**
 * Function to add marker to map
 */

function addMarker(marker) 
    var category = marker[4];
    var title = marker[1];
    var pos = new google.maps.LatLng(marker[2], marker[3]);
    var content = marker[1];

    marker1 = new google.maps.Marker(
        title: title,
        position: pos,
        category: category,
        map: map
    );

    gmarkers1.push(marker1);

    // Marker click listener
    google.maps.event.addListener(marker1, 'click', (function (marker1, content) 
        return function () 
            console.log('Gmarker 1 gets pushed');
            infowindow.setContent(content);
            infowindow.open(map, marker1);
            map.panTo(this.getPosition());
            map.setZoom(15);
        
    )(marker1, content));


/**
 * Function to filter markers by category
 */

filterMarkers = function (category) 
    for (i = 0; i < gmarkers1.length; i++) 


// Init map
initialize();
#map-canvas 
    width: 500px;
    height: 500px;


Ajustar límites después de filtrar

EDITAR para @bluantinoo comentario

/**
 * Function to filter markers by category
 */

filterMarkers = function(category)

    var bounds = new google.maps.LatLngBounds();
    for (i = 0; i < gmarkers1.length; i++)  category.length == 0)
        
            marker.setVisible(true);
            bounds.extend(marker.getPosition());
        
        // Categories don't match 
        else
                  
            marker.setVisible(false);
        
        map.fitBounds(bounds);
      

Ejemplo de trabajo

var gmarkers1 = [];
var markers1 = [];
var infowindow = new google.maps.InfoWindow(
    content: ''
);

// Our markers
markers1 = [
    ['0', 'Title 1', 52.4357808, 4.991315699999973, 'car'],
    ['1', 'Title 2', 52.4357808, 4.981315699999973, 'third'],
    ['2', 'Title 3', 52.4555687, 5.039231599999994, 'car'],
    ['3', 'Title 4', 52.4555687, 5.029231599999994, 'second']
];

/**
 * Function to init map
 */

function initialize() 
    var center = new google.maps.LatLng(52.4357808, 4.991315699999973);
    var mapOptions = 
        zoom: 12,
        center: center,
        mapTypeId: google.maps.MapTypeId.TERRAIN
    ;

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    for (i = 0; i < markers1.length; i++) 
        addMarker(markers1[i]);
    


/**
 * Function to add marker to map
 */

function addMarker(marker) 
    var category = marker[4];
    var title = marker[1];
    var pos = new google.maps.LatLng(marker[2], marker[3]);
    var content = marker[1];

    marker1 = new google.maps.Marker(
        title: title,
        position: pos,
        category: category,
        map: map
    );

    gmarkers1.push(marker1);

    // Marker click listener
    google.maps.event.addListener(marker1, 'click', (function (marker1, content) 
        return function () 
            console.log('Gmarker 1 gets pushed');
            infowindow.setContent(content);
            infowindow.open(map, marker1);
            map.panTo(this.getPosition());
            map.setZoom(15);
        
    )(marker1, content));


/**
 * Function to filter markers by category
 */

filterMarkers = function(category)

    var bounds = new google.maps.LatLngBounds();
    for (i = 0; i < gmarkers1.length; i++)   


// Init map
initialize();
#map-canvas 
    width: 500px;
    height: 500px;

Sobre la base de la solución de @Rene Korss, aquí hay un filtro con selección múltiple, basado en casillas de verificación, pero se puede convertir fácilmente en una lista de selección múltiple: solo obtenga una matriz con los nombres de las opciones para comparar.

var gmarkers1 = [];
var markers1 = [];
var infowindow = new google.maps.InfoWindow(
  content: ''
);
// Our markers
markers1 = [
  ['0', 'Title 1', 52.4357808, 4.991315699999973, ['car', 'second']],
  ['1', 'Title 2', 52.4357808, 4.981315699999973, ['third']],
  ['2', 'Title 3', 52.4555687, 5.039231599999994, ['car', 'third']],
  ['3', 'Title 4', 52.4555687, 5.029231599999994, ['second']]
];
markerCount = markers1.length
// Function to init map
function initialize() 
  var center = new google.maps.LatLng(52.4357808, 4.991315699999973);
  var mapOptions = 
    zoom: 12,
    center: center,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  ;

  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  for (i = 0; i < markerCount; i++) 
    addMarker(markers1[i]);
  

// Function to add marker to map
function addMarker(marker) 
  var category = marker[4];
  var title = marker[1];
  var pos = new google.maps.LatLng(marker[2], marker[3]);
  var content = marker[1];

  marker1 = new google.maps.Marker(
    title: title,
    position: pos,
    category: category,
    map: map
  );

  gmarkers1.push(marker1);

  // Marker click listener
  google.maps.event.addListener(marker1, 'click', (function(marker1, content) 
    return function() 
      console.log('Gmarker 1 gets pushed');
      infowindow.setContent(content);
      infowindow.open(map, marker1);
      map.panTo(this.getPosition());
      map.setZoom(15);
    
  )(marker1, content));

// Function on Change of checkbox
updateView = function(element) 
  if (element) 
    //Get array with names of the checked boxes
    checkedBoxes = ([...document.querySelectorAll('input[type=checkbox]:checked')]).map(function(o) 
      return o.id;
    );
    console.log(checkedBoxes);
    for (i = 0; i < markerCount; i++) 
      marker = gmarkers1[i];
      console.log(marker.category)
      //Filter to show any markets containing ALL of the selected options
      if (typeof marker.category == 'object' && checkedBoxes.every(function(o) 
          return (marker.category).indexOf(o) >= 0;
        )) 
        marker.setVisible(true);
       else 
        marker.setVisible(false);
      
    
   else 
    console.log('No param given');
  

// Init map
initialize();
#map-canvas 
  width: 500px;
  height: 500px;

Car Second Third

Básicamente, solo obtiene una matriz con los nombres de los identificadores de las casillas de verificación seleccionadas:

checkedBoxes = ([...document.querySelectorAll('input[type=checkbox]:checked')]).map(function(o) return o.id; );

Luego, compara cada categoría de ubicación y la muestra si incluye todas las casillas de verificación seleccionadas, pero es posible que haya más sin seleccionar. Si no se selecciona ninguno, se muestran todos:

if(typeof marker.category == 'object' && checkedBoxes.every(function (o) return (marker.category).indexOf(o) >= 0;))
      marker.setVisible(true);

else 
      marker.setVisible(false);

Aquí también hay un JSfiddle

Actualizar: Según la solicitud de comentario, aquí hay un fragmento de código que no muestra nada a menos que marque algo. Además, la lógica es que debe tener exactamente las mismas categorías seleccionadas como marcador para ser visible.

var gmarkers1 = [];
var markers1 = [];
var infowindow = new google.maps.InfoWindow(
  content: ''
);
// Our markers
markers1 = [
  ['0', 'Title 1', 52.4357808, 4.991315699999973, ['car', 'second']],
  ['1', 'Title 2', 52.4357808, 4.981315699999973, ['third']],
  ['2', 'Title 3', 52.4555687, 5.039231599999994, ['third', 'car']],
  ['3', 'Title 4', 52.4555687, 5.029231599999994, ['second']]
];
markerCount = markers1.length
// Function to init map
function initialize() 
  var center = new google.maps.LatLng(52.4357808, 4.991315699999973);
  var mapOptions = 
    zoom: 12,
    center: center,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  ;

  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  for (i = 0; i < markerCount; i++) 
    addMarker(markers1[i]);
  

// Function to add marker to map
function addMarker(marker) 
  var category = marker[4];
  var title = marker[1];
  var pos = new google.maps.LatLng(marker[2], marker[3]);
  var content = marker[1];

  marker1 = new google.maps.Marker(
    title: title,
    position: pos,
    category: category,
    map: map
  );

  gmarkers1.push(marker1);

  // Marker click listener
  google.maps.event.addListener(marker1, 'click', (function(marker1, content) 
    return function() 
      console.log('Gmarker 1 gets pushed');
      infowindow.setContent(content);
      infowindow.open(map, marker1);
      map.panTo(this.getPosition());
      map.setZoom(15);
    
  )(marker1, content));

// Function on Change of checkbox
updateView = function(element) 
  if (element) 
    //Get array with names of the checked boxes
    checkedBoxes = ([...document.querySelectorAll('input[type=checkbox]:checked')]).map(function(o) 
      return o.id;
    );
    console.log(checkedBoxes);
    for (i = 0; i < markerCount; i++) 
      marker = gmarkers1[i];
      console.log(marker.category)
      //Filter to show any markets containing ALL of the selected options
      if(typeof marker.category == 'object' && marker.category.length === checkedBoxes.length && checkedBoxes.reduce((a, b) => a && marker.category.includes(b), true))
        marker.setVisible(true);
       else 
        marker.setVisible(false);
      
    
   else 
    console.log('No param given');
  

// Init map
initialize();
#map-canvas 
  width: 500px;
  height: 500px;

Car Second Third

Y el JSfiddle

Te mostramos las comentarios y valoraciones de los lectores

Recuerda que tienes autorización de glosar si te fue preciso.

¡Haz clic para puntuar esta entrada!
(Votos: 2 Promedio: 5)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *