【问题标题】:Need help adding popup info windows to polygons on Leaflet map需要帮助将弹出信息窗口添加到传单地图上的多边形
【发布时间】:2016-04-12 02:19:37
【问题描述】:

我正在尝试将弹出窗口添加到传单地图中,该地图显示不同采矿地点周围的缓冲区。当我单击缓冲区多边形时,我想获取矿井名称信息。这是我的代码,

<html>
<head>
  <title>Buffer Zones around Mine</title>
  <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
  <script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
  <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
  <style>
    #map{ height: 100% }

  </style>
</head>
<body>

  <div id="map"></div>

  <script>

  var map = L.map('map').setView([45, -95], 4); //center map view


  var CartoDB_Positron = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="http://cartodb.com/attributions">CartoDB</a>',
subdomains: 'abcd',
maxZoom: 19
}).addTo(map); 

// load JSON data
 $.getJSON("BufferPolygons.json",function(data){
    // add GeoJSON layer to the map once the file is loaded
    L.geoJson(data).addTo(map);
  });

//get popup info
var myLayer = L.geoJson(polygon, {
onEachFeature: yourOnEachFeatureFunction
}).addTo(map);

function yourOnEachFeatureFunction(feature, layer){
if (feature.properties.mine_name) {
    layer.bindPopup(feature.properties.mine_name);
    }
}
  </script>
</body>
</html>

我是 Leaflet 和 Javascript 的新手,非常感谢任何帮助!

编辑:当滚动多边形与非多边形时,我的光标会发生变化,所以我相信通过鼠标单击可以检索信息。由于没有显示任何内容,我假设这是一个 HTML/CSS 问题,也许我还没有创建任何窗口让这些信息进入?

【问题讨论】:

    标签: javascript leaflet geojson


    【解决方案1】:

    您看到的多边形是在$.getJSON 回调函数中创建的。当您在回调之外定义 myLayer 时,它似乎正在寻找未定义的 polygon 对象,因此永远不会创建该层及其弹出窗口。

    有几种方法可以解决这个问题。最直接的方法就是为您在回调中创建的L.geoJson 设置onEachFeature 选项:

    $.getJSON("BufferPolygons.json",function(data){
      L.geoJson(data, {
        onEachFeature: yourOnEachFeatureFunction
      }).addTo(map);
    });
    

    但是,这样做,您可能无法在其他地方引用该层(例如,如果您想将其添加到层控件),因为它不会在 BufferPolygons.json 完成加载之前创建。在大多数情况下,更好的选择是使用您想要的任何选项创建myLayer,但没有任何数据,并使用addData method 在回调函数中填充这个空层:

    var myLayer = L.geoJson(false, {
      onEachFeature: yourOnEachFeatureFunction
    }).addTo(map);
    
    $.getJSON("BufferPolygons.json",function(data){
      myLayer.addData(data);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-05
      • 2013-03-06
      • 1970-01-01
      • 2015-06-11
      相关资源
      最近更新 更多