【问题标题】:Leaflet.js - Create marker and show popup on a mapLeaflet.js - 创建标记并在地图上显示弹出窗口
【发布时间】:2018-08-07 21:42:37
【问题描述】:

当我单击某个 HTML 元素时,我使用Leaflet JavaScript API 创建一个弹出窗口。问题是弹出窗口不会显示在我的地图上。我不确定我的代码有什么问题。

以下是 json 文件中的功能示例。请注意,为方便起见,我将整个 json 对象分配为 var dataset

var dataset = {
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "stemburo": "Sporthal Nieuwland",
        "aantal_stemmen": 3753,
        "lat": 52.2006665,
        "lng": 5.3758691,
        "Actief": 34,
        "Amersfoort 2014": 348,
        "Blanco lijst Chel": 5,
        "Burger Partij Amersfoort": 258,
        "Christen Democratisch App\u00e9l": 556,
        "ChristenUnie": 350,
        "DENK": 117,
        "Democraten 66": 525,
        "GroenLinks": 345,
        "Partij van de Arbeid": 239,
        "Socialistische Partij": 189,
        "Staatkundig Gereformeerde Partij": 42,
        "Volkspartij voor Vrijheid en Democratie": 717,
        "Vrede en Recht": 28
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          5.3758691,
          52.2006665
        ]
      }
    }

下面是我创建 HTML 元素的 JavaScript 代码的一部分。我使用 JQuery 的$.each 来读取数据集。我将 'stemburo' 属性值(来自 json 对象)分配为元素的 id 属性。

当点击一个元素时,它会检查点击的 id 值是否与properties.stemburo 值之一相同。随后,应根据属性的坐标显示一个弹出窗口。

$.each(dataset.features,function(key,val){
    var stemlocaties =val.properties.stemburo;
    var newElement= document.createElement('a');
    newElement.id= stemlocaties;
    newElement.className='list-group-item list-group-item-action';
    newElement.innerHTML=stemlocaties;
    document.getElementById('stemlocaties').appendChild(newElement);

    newElement.onclick=function(){
        if (val.properties.stemburo===this.id){
            var lng = val.geometry.coordinates[0];
            var lat = val.geometry.coordinates[1];
            L.popup()
              .setLatLng([lat,lng])
              .setContent('New popup text!')
              .openOn(map);

        }
    };

    }); 

我还是 JavaScript 新手。对于任何反馈,我们都表示感谢。

【问题讨论】:

    标签: javascript html leaflet


    【解决方案1】:

    这是解决您面临的问题的另一种方法。如果您阅读了leaflet.js docs,可以了解如何添加marker 并附加popup dialog

    这是添加标记并将弹出窗口附加到它的行。 L.marker(location).addTo(myMap).bindPopup(popupContent)

    安排数据以便能够轻松地在其上映射、创建位置和可用于在弹出窗口中填充信息的 popupContent 变量需要更多的努力。下面是一个示例,说明如何使用您提供的数据集并使用弹出窗口创建标记。

    // Create the map and set the view and some properties
    var myMap = L.map('mapid').setView([52.2, 5.37], 12);
    L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
      // maxZoom: 5,
      attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
        '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
        'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
      id: 'mapbox.streets'
    }).addTo(myMap);
    
    var dataset = {
      "type": "FeatureCollection",
      "features": [
        {
          "type": "Feature",
          "properties": {
            "stemburo": "Sporthal Nieuwland",
            "aantal_stemmen": 3753,
            "lat": 52.2006665,
            "lng": 5.3758691,
            "Actief": 34,
            "Amersfoort 2014": 348,
            "Blanco lijst Chel": 5,
            "Burger Partij Amersfoort": 258,
            "Christen Democratisch App\u00e9l": 556,
            "ChristenUnie": 350,
            "DENK": 117,
            "Democraten 66": 525,
            "GroenLinks": 345,
            "Partij van de Arbeid": 239,
            "Socialistische Partij": 189,
            "Staatkundig Gereformeerde Partij": 42,
            "Volkspartij voor Vrijheid en Democratie": 717,
            "Vrede en Recht": 28
          },
          "geometry": {
            "type": "Point",
            "coordinates": [
              52.2006665,
              5.3758691
            ]
          }
        }
      ]
    };
    
    // map over the dataset features, create a marker for each and link a popup.
    dataset.features.map(function(feature) {
    	const location = feature.geometry.coordinates;
      let partijen = Object
      	.keys(feature.properties)
        .filter(item => !['stemburo', 'lat', 'lng'].includes(item));
      
      const popupContent = 
      	'<h2>' + 
        	feature.properties.stemburo + 
        '</h2>' + 
        partijen.map((naam) => '<p><strong>' + naam + '</strong>: ' + feature.properties[naam] + '</p>').join('');
      
      // add the marker and popup to the map.
      L.marker(location).addTo(myMap).bindPopup(popupContent);
    });
    #mapid {
      height: 400px;
    }
    
    .leaflet-popup-content p {
        margin: 3px 0 !important;
    }
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.3/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin="" />
    
    <script src="https://unpkg.com/leaflet@1.3.3/dist/leaflet.js" integrity="sha512-tAGcCfR4Sc5ZP5ZoVz0quoZDYX5aCtEm/eu1KhSLj2c9eFrylXZknQYmxUssFaVJKvvc0dJQixhGjG2yXWiV9Q==" crossorigin=""></script>
    
    <div id="mapid"></div>

    这里还有一个jsFiddle 具有相同的示例。

    【讨论】:

    • 嗨@Wonka,如果这解决了您的问题,请告诉我。如果是这样,请不要忘记将此答案标记为已接受的答案。这将帮助稍后查看此内容的人们知道我们找到了解决方案。谢谢! :)
    猜你喜欢
    • 1970-01-01
    • 2015-12-11
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多