<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>markercluster &#8211; danisanchez.net</title>
	<atom:link href="https://danisanchez.net/tag/markercluster/feed/" rel="self" type="application/rss+xml" />
	<link>https://danisanchez.net</link>
	<description></description>
	<lastBuildDate>Tue, 13 Apr 2021 08:16:09 +0000</lastBuildDate>
	<language>es</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://danisanchez.net/wp-content/uploads/2026/07/cropped-favicon-32x32.png</url>
	<title>markercluster &#8211; danisanchez.net</title>
	<link>https://danisanchez.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Agrupar marcadores en clusters en OpenStreetMap</title>
		<link>https://danisanchez.net/agrupar-marcadores-en-clusters-en-openstreetmap/</link>
		
		<dc:creator><![CDATA[dani.sanchez]]></dc:creator>
		<pubDate>Tue, 13 Apr 2021 08:16:09 +0000</pubDate>
				<category><![CDATA[Publicaciones]]></category>
		<category><![CDATA[Tutoriales]]></category>
		<category><![CDATA[markercluster]]></category>
		<category><![CDATA[openstreetmap]]></category>
		<guid isPermaLink="false">https://www.gestionatuweb.net/?p=10500</guid>

					<description><![CDATA[Cuando en determinadas zonas de nuestro mapa se aglutinan varios marcadores, un buen recurso suele ser agruparlos en clusters, de forma que el número de elementos en el mapa disminuya mejorando así la usabilidad y visibilidad. Esta funcionalidad no viene integrada directamente en la API de OpenStreetMap (LeafletJS) y tenemos que implementarla mediante un sencillo [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Cuando en determinadas zonas de nuestro mapa se aglutinan varios marcadores, un buen recurso suele ser agruparlos en clusters, de forma que el número de elementos en el mapa disminuya mejorando así la usabilidad y visibilidad.</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img fetchpriority="high" decoding="async" width="466" height="402" src="https://danisanchez.net/wp-content/uploads/2021/04/imagen.png" alt="" class="wp-image-10501" srcset="https://danisanchez.net/wp-content/uploads/2021/04/imagen.png 466w, https://danisanchez.net/wp-content/uploads/2021/04/imagen-300x259.png 300w" sizes="(max-width: 466px) 100vw, 466px" /></figure></div>



<p class="wp-block-paragraph">Esta funcionalidad no viene integrada directamente en la API de OpenStreetMap (<a rel="noreferrer noopener" href="https://leafletjs.com/" target="_blank">LeafletJS</a>) y tenemos que implementarla mediante un sencillo plugin, <a rel="noreferrer noopener" href="https://github.com/Leaflet/Leaflet.markercluster" target="_blank">Leaflet MarkerCluster</a>.</p>



<p class="wp-block-paragraph">Para el ejemplo vamos a crear un mapa en OpenStreetMap como lo haríamos normalmente y como vimos en artículos anteriores:  <em><a href="https://danisanchez.net/integra-openstreetmap-en-tus-aplicaciones-web-con-leaflet-y-mapbox/">Integra OpenStreetMap en tus aplicaciones web con LeafLet y MapBox</a></em>.</p>



<pre class="wp-block-code"><code>&lt;!DOCTYPE html>
&lt;html lang="es">
&lt;head>
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;meta http-equiv="X-UA-Compatible" content="ie=edge">
    &lt;link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css"
   integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
   crossorigin=""/>
    &lt;script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js"
    integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew=="
    crossorigin="">&lt;/script>
    &lt;title>Mapa con OpenStreetMap&lt;/title>
    
    &lt;style>
    	#mimapa {height: 600px;}
    &lt;/style>
&lt;/head>

&lt;body>
    &lt;div id="mimapa">&lt;/div>
    
    &lt;script>
    	var mymap = L.map('mimapa').setView(&#91;37.1698, -3.965], 18);
    	
    	L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
    		maxZoom: 25,
    		attribution: 'Datos del mapa de &amp;copy; &lt;a href="https://www.openstreetmap.org/">OpenStreetMap&lt;/a>, ' + '&lt;a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA&lt;/a>, ' + 'Imágenes © &lt;a href="https://www.mapbox.com/">Mapbox&lt;/a>', 
    		id: 'mapbox/streets-v11'
		}).addTo(mymap);
	&lt;/script>
&lt;/body>
&lt;/html></code></pre>



<p class="wp-block-paragraph">Ejecutando este código ya deberíamos poder visualizar un mapa vacío. Si no carga, revisa el código. Puedes modificar las coordenadas por las de tu zona, si lo prefieres.</p>



<figure class="wp-block-image size-large"><img decoding="async" width="980" height="659" src="https://danisanchez.net/wp-content/uploads/2021/04/imagen-1.png" alt="" class="wp-image-10502" srcset="https://danisanchez.net/wp-content/uploads/2021/04/imagen-1.png 980w, https://danisanchez.net/wp-content/uploads/2021/04/imagen-1-300x202.png 300w, https://danisanchez.net/wp-content/uploads/2021/04/imagen-1-768x516.png 768w" sizes="(max-width: 980px) 100vw, 980px" /></figure>



<p class="wp-block-paragraph">Ahora vamos a añadir unos cuantos marcadores en un espacio reducido:</p>



<pre class="wp-block-code"><code>/*MARCADORES*/
var marker1 = L.marker(&#91;37.1698, -3.965]).addTo(mymap);
var marker2 = L.marker(&#91;37.1698, -3.966]).addTo(mymap);
var marker3 = L.marker(&#91;37.1700, -3.966]).addTo(mymap);
var marker4 = L.marker(&#91;37.1700, -3.967]).addTo(mymap);
var marker5 = L.marker(&#91;37.1696, -3.964]).addTo(mymap);
var marker6 = L.marker(&#91;37.1694, -3.964]).addTo(mymap);</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img decoding="async" width="607" height="423" src="https://danisanchez.net/wp-content/uploads/2021/04/imagen-2.png" alt="" class="wp-image-10504" srcset="https://danisanchez.net/wp-content/uploads/2021/04/imagen-2.png 607w, https://danisanchez.net/wp-content/uploads/2021/04/imagen-2-300x209.png 300w" sizes="(max-width: 607px) 100vw, 607px" /></figure></div>



<p class="wp-block-paragraph">Hasta aquí bien, tenemos 6 marcadores agrupados en una zona reducida, lo que a simple vista dificulta un poco la visibilidad. Para poder agrupar estor marcadores en clusters vamos a añadir los scripts del plugin MarkerCluster en el &lt;head> de nuestra página a continuación de los scripts de Leaflet:</p>



<pre class="wp-block-code"><code>&lt;link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.1.0/dist/MarkerCluster.css" />
&lt;link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.1.0/dist/MarkerCluster.Default.css" />
&lt;script src="https://unpkg.com/leaflet.markercluster@1.1.0/dist/leaflet.markercluster.js">&lt;/script></code></pre>



<p class="wp-block-paragraph">Bien, lo primero que vamos a hacer es volver al código de marcadores y quitarles el método addTo(mymap), ya que no vamos a añadirlos de forma indepeniente y dejar este método puede crear repeticiones y comportamientos extraños.</p>



<pre class="wp-block-code"><code>/*MARCADORES*/
var marker1 = L.marker(&#91;37.1698, -3.965]);
var marker2 = L.marker(&#91;37.1698, -3.966]);
var marker3 = L.marker(&#91;37.1700, -3.966]);
var marker4 = L.marker(&#91;37.1700, -3.967]);
var marker5 = L.marker(&#91;37.1696, -3.964]);
var marker6 = L.marker(&#91;37.1694, -3.964]);</code></pre>



<p class="wp-block-paragraph">A continuación de los marcadores, vamos a declarar un grupo de clusters:</p>



<pre class="wp-block-code"><code>var grupos = L.markerClusterGroup(); </code></pre>



<p class="wp-block-paragraph">Y lo único que tenemos que hacer es añadir cada marcador a este grupo:</p>



<pre class="wp-block-code"><code>grupos.addLayer(marker1);
grupos.addLayer(marker2);
grupos.addLayer(marker3);
grupos.addLayer(marker4);
grupos.addLayer(marker5);
grupos.addLayer(marker6);</code></pre>



<p class="wp-block-paragraph">Huelga decir que si tienes cientos de marcadores no es necesario escribir todo manualmente, usa un bucle que para eso están!</p>



<pre class="wp-block-code"><code>/*POR EJEMPLO:*/
for(var i=1; i &lt;= 6; i++){
    grupos.addLayer(marker+i);
}</code></pre>



<p class="wp-block-paragraph">Por último agregamos el grupo al mapa:</p>



<pre class="wp-block-code"><code>mymap.addLayer(grupos);</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="978" height="656" src="https://danisanchez.net/wp-content/uploads/2021/04/imagen-3.png" alt="" class="wp-image-10506" srcset="https://danisanchez.net/wp-content/uploads/2021/04/imagen-3.png 978w, https://danisanchez.net/wp-content/uploads/2021/04/imagen-3-300x201.png 300w, https://danisanchez.net/wp-content/uploads/2021/04/imagen-3-768x515.png 768w" sizes="auto, (max-width: 978px) 100vw, 978px" /></figure></div>



<p class="wp-block-paragraph">Los marcadores se irán agrupando dinámicamente según el zoom que apliquemos al mapa.</p>



<p class="wp-block-paragraph">Os dejo el código del archivo html final comentado:</p>



<pre class="wp-block-code"><code>&lt;!DOCTYPE html>
&lt;html lang="es">
&lt;head>
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;meta http-equiv="X-UA-Compatible" content="ie=edge">
    
    &lt;!-- API LEAFLET -->
    &lt;link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css"
   integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
   crossorigin=""/>
    &lt;script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js"
    integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew=="
    crossorigin="">&lt;/script>
    	
    &lt;!--PLUGIN MARKERCLUSTER -->	
   	&lt;link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.1.0/dist/MarkerCluster.css" />
	&lt;link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.1.0/dist/MarkerCluster.Default.css" />
	&lt;script src="https://unpkg.com/leaflet.markercluster@1.1.0/dist/leaflet.markercluster.js">&lt;/script> 
    &lt;title>Mapa con Open Street Map&lt;/title>
    
    &lt;style>
    	#mimapa {height: 600px;}
    &lt;/style>
&lt;/head>

&lt;body>
    &lt;div id="mimapa">&lt;/div>
    
    &lt;script>
    	/*DECLARAR EL MAPA*/
    	var mymap = L.map('mimapa').setView(&#91;37.1698, -3.965], 16);
    	
    	/*DIBUJAR EL MAPA*/
    	L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
    maxZoom: 25,
    attribution: 'Datos del mapa de &amp;copy; &lt;a href="https://www.openstreetmap.org/">OpenStreetMap&lt;/a>, ' + '&lt;a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA&lt;/a>, ' + 'Imágenes © &lt;a href="https://www.mapbox.com/">Mapbox&lt;/a>', 
    id: 'mapbox/streets-v11'
}).addTo(mymap);
		
/*DEFINIR MARCADORES*/
var marker1 = L.marker(&#91;37.1698, -3.965]);
var marker2 = L.marker(&#91;37.1698, -3.966]);
var marker3 = L.marker(&#91;37.1700, -3.966]);
var marker4 = L.marker(&#91;37.1700, -3.967]);
var marker5 = L.marker(&#91;37.1696, -3.964]);
var marker6 = L.marker(&#91;37.1694, -3.964]);
		
/*CREAR GRUPO DE CLUSTERS*/
var grupos = L.markerClusterGroup(); 
		
/*AÑADIR CADA MARCADOR AL CLUSTER*/
grupos.addLayer(marker1);
grupos.addLayer(marker2);
grupos.addLayer(marker3);
grupos.addLayer(marker4);
grupos.addLayer(marker5);
grupos.addLayer(marker6);
		
//AÑADIR CLUSTER AL MAPA
mymap.addLayer(grupos);
&lt;/script>
&lt;/body>
&lt;/html></code></pre>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
