Pregunta

Estoy tratando de compensar ligeramente los iconos de clúster creados por Google Maps MarkerClusterer (V3). Aparte de modificar el código existente, no puedo encontrar una manera de hacer esto. Alguien tiene una idea?

El objeto de estilos en el que puede proporcionar una URL de imagen personalizada acepta una propiedad de anclaje, pero esto es para compensar el recuento de elementos del marcador generado.

¡Gracias!

¿Fue útil?

Solución

Puede agregar algo de espacio transparente a un lado del PNG de su icono de clúster, de modo que la parte del icono que le gustaría centrarse también se centre en su PNG. Esto no debería aumentar el peso de su imagen en más de unos pocos bytes.

Otros consejos

La forma correcta de hacerlo es ajustar el anchorIcon Propiedad como esta:

var clusterStyles = [
{
    height: 64,
    width: 53,
    anchorIcon: [20, 140]
},
{
    height: 64,
    width: 53,
    anchorIcon: [20, 140]
},
{
    height: 64,
    width: 53,
    anchorIcon: [20, 140]
}
];

var mcOptions = {
    styles: clusterStyles
};

var markerCluster = new MarkerClusterer(map, markers, mcOptions);

La respuesta aceptada no funciona lo suficientemente bien para mí: agregar espacio transparente a la imagen del icono puede cambiar la forma en que los eventos de clic y desplazamiento se comportan debido al mayor tamaño del objeto.

Yo usaría el anchorIcon propiedad, excepto que solo está disponible en Marker Clusterer Plus, no el otro Clúster marcador complemento (que estoy usando).

Para aquellos que específicamente quieren usar Marker Clusterer, puede anular ClusterIcon.prototype.getPosFromLatLng_. los ClusterIcon El objeto es global, por lo que podemos modificarlo en el nivel superior de cualquier archivo de script sin jugar con el código fuente del complemento.

Esto anclará el marcador en la parte inferior del icono:

ClusterIcon.prototype.getPosFromLatLng_ = function (latlng) {
  var pos = this.getProjection().fromLatLngToDivPixel(latlng);
  pos.x -= parseInt(this.width_ / 2);
  pos.y -= parseInt(this.height_);
  return pos;
};

Cambié el código de marcclusterer.js para admitir el parámetro Anchortext modificando las siguientes dos funciones:

/**
 * Sets the icon to the the styles.
 */
ClusterIcon.prototype.useStyle = function() {
  var index = Math.max(0, this.sums_.index - 1);
  index = Math.min(this.styles_.length - 1, index);
  var style = this.styles_[index];
  this.url_ = style['url'];
  this.height_ = style['height'];
  this.width_ = style['width'];
  this.textColor_ = style['textColor'];
  this.anchor_ = style['anchor'];
  this.anchorText_ = style['anchorText']; //added to support anchorText parameter by Frane Poljak, Locastic
  this.textSize_ = style['textSize'];
  this.backgroundPosition_ = style['backgroundPosition'];
};


/**
 * Adding the cluster icon to the dom.
 * @ignore
 */
ClusterIcon.prototype.onAdd = function() {
  this.div_ = document.createElement('DIV');
  if (this.visible_) {
    var pos = this.getPosFromLatLng_(this.center_);
    this.div_.style.cssText = this.createCss(pos);

      ////added to support anchorText parameter by Frane Poljak, Locastic

      if (typeof this.anchorText_ === 'object' && typeof this.anchorText_[0] === 'number' && typeof this.anchorText_[1] === 'number') {
          this.div_.innerHTML = '<span style="position:relative;top:' + String(this.anchorText_[0]) + 'px;left:' + String(this.anchorText_[1]) + 'px;">' + this.sums_.text + '</span>'
      } else this.div_.innerHTML = this.sums_.text;
  } 

  var panes = this.getPanes();
  panes.overlayMouseTarget.appendChild(this.div_);

  var that = this;
  google.maps.event.addDomListener(this.div_, 'click', function() {
    that.triggerClusterClick();
  });
};

Anchor / Anchoricon / Anchortext Propiedades no funcionó para mí ... así que hice una especie de solución:

yo suelo setCalculator() función para establecer el texto del clúster:

https://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/docs/reference.html

Cuando estoy configurando la propiedad de texto del clúster, estoy envolviendo el valor <span>, algo como esto:

markerCluster.setCalculator(function (markers) {
   return {
      text: '<span class="myClass">' + value+ '</span>',
      index: index                   
   };
});

Ahora puede controlar la posición de la etiqueta del clúster con ".myclass":

span.myClass{
   position: relative;
   top: -15px;
   .....
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top