如何将带有geojson的numered标记放在传单

时间:2018-06-05 21:04:45

标签: javascript json leaflet geojson markers

忘掉一切,直到这里,我花了一个曙光,试着看看能不能前进,我会解释。我有一张地图,我需要列举1到15个标记。标记是正确的,这个问题只标记了1,15次。这是我的json:

https://github.com/eltonsantos/analise_integrada/blob/master/path.js

简单的json,没什么了

我的代码是:

var rotas = L.geoJSON(paradas, {
    onEachFeature: onEachFeature,
    pointToLayer: function(feature, latlng){
        console.log("Qtd: " + paradas.features.length)
        for(var i = 1; i <= paradas.features.length; i++){
            return L.marker(latlng, {
                icon: new L.AwesomeNumberMarkers({
                    number: i,
                    markerColor: 'purple'
                })
            })
        }
    }
}).addTo(map);

此代码不会显示任何错误消息,它只显示我的所有点编号全部用1.我只是希望它们从1到15编号,根据json中的数量

1 个答案:

答案 0 :(得分:4)

pointToLayer功能选项每个标记一次称为(确切地说,每"Point"类型功能)。每个函数调用都有 latlng值。

因此,您会理解尝试循环播放paradas.features.length毫无意义。

此外,您的循环return在第一次迭代时,这就是为什么您只看到带有“1”枚举的图标。

由于您希望L.geoJSON工厂在每次调用pointToLayer函数时递增枚举,您只需将计数器放在外部范围内:

var map = L.map('map');

// Hold the counter in an outer scope.
var i = 0;

var rotas = L.geoJSON(paradas, {
  //onEachFeature: onEachFeature,
  pointToLayer: function(feature, latlng) {
    console.log("Qtd: " + paradas.features.length)
    // Increment the counter.
    i += 1;
    // No need to loop.
    //for (var i = 1; i <= paradas.features.length; i++) {
      // Directly return the Marker for the given `latlng`
      return L.marker(latlng, {
        icon: new L.AwesomeNumberMarkers({
          number: i,
          markerColor: 'purple',
        }),
      });
    //}
  }
}).addTo(map);

map.fitBounds(rotas.getBounds());

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
<!-- Leaflet assets -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin="" />
<script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet-src.js" integrity="sha512-IkGU/uDhB9u9F8k+2OsA6XXoowIhOuQL1NTgNZHY1nkURnqEGlDZq3GsfmdJdKFe1k1zOc6YU2K7qY+hF9AodA==" crossorigin=""></script>

<!-- Leaflet.AwesomeNumberMarkers assets -->
<link rel="stylesheet" href="https://rawgit.com/Zahidul-Islam/Leaflet.awesome-numbered-marker/f7b5b594e9fc451cd006ee345220a86390eb1cf1/src/leaflet_awesome_number_markers.css" />
<script src="https://rawgit.com/Zahidul-Islam/Leaflet.awesome-numbered-marker/f7b5b594e9fc451cd006ee345220a86390eb1cf1/src/leaflet_awesome_number_markers.js"></script>

<!-- your GeoJSON data that defines the `paradas` global variable -->
<script src="https://rawgit.com/eltonsantos/analise_integrada/8b771bed3bd0bbfe1da3d02ce09b37630a637a0c/path.js"></script>

<div id="map" style="height: 180px"></div>