【问题标题】:Parsing Foursquare API JSON for Leaflet为 Leaflet 解析 Foursquare API JSON
【发布时间】:2019-04-17 23:29:53
【问题描述】:

我正在尝试将 JSON 映射到从 Foursquare 提取的传单上,但我很难让它显示出来。

这是一个使用 JSON 的工作脚本,我从 NYC Open Data 获取。

fetch('complaintdata.json')
          .then(function (response) {
            // Read data as JSON
            return response.json();
          })
          .then(function (data) {
            // Create the Leaflet layer for the data
            var complaintData = L.geoJson(data, {
              pointToLayer: function (feature, latlng) {
                return L.marker(latlng, {icon: myIcon});
              },

              onEachFeature: function (feature, layer) {
                layer.on('click', function () {
                  // This function is called whenever a feature on the layer is clicked
                  console.log(layer.feature.properties);

                  // Render the template with all of the properties. Mustache ignores properties
                  // that aren't used in the template, so this is fine.
                  var sidebarContentArea = document.querySelector('.sidebar-content');
                  console.log(sidebarContentArea);
                  sidebarContentArea.innerHTML = Mustache.render(popupTemplate, layer.feature.properties);
                });
              }
            });

            // Add data to the map
            complaintData.addTo(map);

          });

这是使用 Google 地图的working example,但我很难将其转移到 Leaflet。

这是JSON 我想复制这个过程:

【问题讨论】:

    标签: javascript json parsing leaflet foursquare


    【解决方案1】:

    您需要首先获取数据,然后遍历对象以构建标记和弹出内容。

    您的 geojson 似乎不符合本地 L.geoJSON 内置方法,因此像处理常规 JavaScript 对象一样遍历对象。

    也只是为了通知您,我使用 axios 来获取响应。

    import axios from "axios";
    
    const url =
      "https://api.foursquare.com/v2/venues/search?near=London&categoryId=4bf58dd8d48988d14c941735&client_id=BOCHQZ4NF0D2NNFP2HM0INIKPUESPUX3RMRDUX02MPWIYSM2&client_secret=EDNX150PKLS4SMRHWL21Q0KLBAQXYQUQV5RAZI0HZSA1IYGG&v=20161111";
    
    let geoJson = {};
    
    axios.get(url).then(response => {
      geoJson = { ...response.data.response.venues };
      // console.log(geoJson);
      for (let key in geoJson) {
        let restaurant = geoJson[key];
        // console.log(restaurant);
        const { lat, lng, address } = restaurant.location;
        const { name } = restaurant;
        const popupContent = `<b>Name</b>: ${name} 
                              <br> <b>Address</b>: ${address}
                              <br> <b>Lat</b>: ${lat}, 
                              <br> <b>Lon</b>: ${lng} 
        `;
        L.marker([lat, lng], { icon: customMarker })
          .bindPopup(popupContent)
          .addTo(map);
      }
    });
    

    Demo

    【讨论】:

    • 成功了!现在我必须弄清楚如何让信息显示在侧边栏上,而不是像以前那样作为弹出窗口显示。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    • 2017-01-24
    • 2013-07-26
    相关资源
    最近更新 更多