2012-08-16 180 views
14

Así que tengo una capa geojson en el folleto, y puedo agregar objetos geojson a esta capa para mostrar en el mapa resultante.cómo agregar texto para mostrar en el mapa a un objeto geojson en el folleto

Ahora me gustaría agregar una etiqueta de texto para mostrar cerca del objeto.

Este ejemplo muestra el uso de un objeto personalizado L.control() para mostrar información adicional en el mapa. Lo cual parece cercano a lo que quiero hacer.

Dado este ejemplo, me gustaría agregar etiquetas de texto iniciales del estado (es decir, "TX", "FL") situadas sobre cada estado. ¿Se puede usar L.control() para hacer esto, o hay otra manera?

http://leaflet.cloudmade.com/examples/choropleth.html

var info = L.control(); 

info.onAdd = function (map) { 
    this._div = L.DomUtil.create('div', 'info'); // create a div with a class "info" 
    this.update(); 
    return this._div; 
}; 

// method that we will use to update the control based on feature properties passed 
info.update = function (props) { 
    this._div.innerHTML = '<h4>US Population Density</h4>' + (props ? 
     '<b>' + props.name + '</b><br />' + props.density + ' people/mi<sup>2</sup>' 
     : 'Hover over a state'); 
}; 

info.addTo(map); 

Respuesta

14

que estaba buscando la misma pregunta hace poco y acaba en práctica ayer sobre la base de un anuncio en el grupo de Google. https://groups.google.com/forum/#!topic/leaflet-js/sA2HnU5W9Fw

Gracias a Adrian por el código original de la muestra.

Aquí está la solución:

Extender la siguiente clase de la siguiente manera:

<script> 

    L.LabelOverlay = L.Class.extend({ 
     initialize: function(/*LatLng*/ latLng, /*String*/ label, options) { 
      this._latlng = latLng; 
      this._label = label; 
      L.Util.setOptions(this, options); 
     }, 
     options: { 
      offset: new L.Point(0, 2) 
     }, 
     onAdd: function(map) { 
      this._map = map; 
      if (!this._container) { 
       this._initLayout(); 
      } 
      map.getPanes().overlayPane.appendChild(this._container); 
      this._container.innerHTML = this._label; 
      map.on('viewreset', this._reset, this); 
      this._reset(); 
     }, 
     onRemove: function(map) { 
      map.getPanes().overlayPane.removeChild(this._container); 
      map.off('viewreset', this._reset, this); 
     }, 
     _reset: function() { 
      var pos = this._map.latLngToLayerPoint(this._latlng); 
      var op = new L.Point(pos.x + this.options.offset.x, pos.y - this.options.offset.y); 
      L.DomUtil.setPosition(this._container, op); 
     }, 
     _initLayout: function() { 
      this._container = L.DomUtil.create('div', 'leaflet-label-overlay'); 
     } 
    }); 

</script> 

añadir Además, este CSS:

<style> 
    .leaflet-popup-close-button { 
     display:none; 
    } 

    .leaflet-label-overlay { 
     line-height:0px; 
     margin-top: 9px; 
     position:absolute; 
    } 
</style> 

y luego mostrar las etiquetas de texto de la siguiente manera:

<script> 
    var map = L.map('map').setView([51.898712, 6.7307100000001], 4); 

    // add markers 
    // ... 

    // add text labels: 
    var labelLocation = new L.LatLng(51.329219337279405, 10.454119349999928); 
    var labelTitle = new L.LabelOverlay(labelLocation, '<b>GERMANY</b>'); 
    map.addLayer(labelTitle); 


    var labelLocation2 = new L.LatLng(47.71329162782909, 13.34573480000006); 
    var labelTitle2 = new L.LabelOverlay(labelLocation2, '<b>AUSTRIA</b>'); 
    map.addLayer(labelTitle2); 

    // In order to prevent the text labels to "jump" when zooming in and out, 
    // in Google Chrome, I added this event handler: 

    map.on('movestart', function() { 
     map.removeLayer(labelTitle); 
     map.removeLayer(labelTitle2); 
    }); 
    map.on('moveend', function() { 
     map.addLayer(labelTitle); 
     map.addLayer(labelTitle2); 
    }); 
</script> 

Resultado:

enter image description here

+0

Hola Mathias y gracias por el excelente código. No estoy tan familiarizado con JavaScript y HTML. ¿Tienes un archivo html + javascript completo que pueda usar? tnx. – Ash

+0

Hola. Esto es genial, pero no centra la etiqueta. Trabajé este jquery para ejecutar en un evento moveend. También puede considerar mostrarlos en un mapend después de ocultarlos en un movestart para que no se vean raros cuando se escale el resto del mapa. $ (". Leaflet-label-overlay").cada uno (función (i) { $ (esto) .css ("tamaño de fuente", Math.pow (2, map.getZoom())/2000 + "%") .css ("margin-left" , - $ (this) .width()/2) .css ("margin-top", - $ (this) .height()/2); }); } –

+0

(modifique el 2000 al gusto. También puede usar alguna técnica para ocultar las etiquetas con un zoom bajo o alto, o para modificar la negrita que tengan, etc.) –

15

superposición de etiquetas en Cunas Usando marcador Clase y Clase Divicon Con 'html' Propiedad

Personalmente, yo uso este método para aplicar etiquetas de texto en el mapa. De esta forma, puedo utilizar todos los métodos y eventos existentes de Marker Class sin esfuerzo adicional. Es un poco como usar una etiqueta de texto para reemplazar un ícono, supongo.

 var textLatLng = [35.1436, -111.5632]; 
     var myTextLabel = L.marker(textLatLng, { 
      icon: L.divIcon({ 
       className: 'text-labels', // Set class for CSS styling 
       html: 'A Text Label' 
      }), 
      draggable: true,  // Allow label dragging...? 
      zIndexOffset: 1000  // Make appear above other map features 
     }); 

Mi CSS se ve así:

 .text-labels { 
      font-size: 2em; 
      font-weight: 700; 
      /* Use color, background, set margins for offset, etc */ 
     } 

Además, no he explorado todavía, pero tal vez se puede añadir un png a la CSS y luego desplazar el texto, de modo que se puede envolver un ícono y una etiqueta en el mismo objeto Marker usando la clase DivIcon Leaflet ?? Esto sería fácil con una forma de div (por ejemplo, caja, círculo), pero no estoy seguro acerca de agregar un png al CSS para el objeto Marker, porque de ninguna manera soy un gurú de CSS.

+1

Esta es una buena solución simple. Necesito agregar cambiar el tamaño/estilo de acuerdo con Zoom para hacerlo aún mejor. – Foton

Cuestiones relacionadas