javascript – 如何新增用於在地圖上顯示的文字到單頁中的geojson物件
所以我在傳單中有一個geojson圖層,我可以新增geojson物件到這個圖層,以便在結果圖上顯示.
現在我想新增一個文字標籤來顯示物件附近.
此示例顯示使用自定義L.control()物件在地圖上顯示其他資訊.這似乎接近我想做的事情.
給出這個例子,我想新增位於每個狀態的狀態初始文字標籤(即“TX”,“FL”).可以使用L.control()來做這個,還是有另一種方法?
ofollow,noindex" target="_blank">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);
我最近正在尋找同樣的問題,只是根據google集團的釋出昨天實施了這個問題.
https://groups.google.com/forum/#!topic/leaflet-js/sA2HnU5W9Fw感謝Adrian的原始程式碼示例.
這是解決方案:
擴充套件以下類:
<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>
另外新增這個css:
<style> .leaflet-popup-close-button { display:none; } .leaflet-label-overlay { line-height:0px; margin-top: 9px; position:absolute; } </style>
然後顯示如下文字標籤:
<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>
結果:
程式碼日誌版權宣告:
翻譯自:http://stackoverflow.com/questions/11979729/how-to-add-text-for-display-on-map-to-a-geojson-object-in-leaflet