使用AJAX调用将GeoJSON数据拉入Leaflet

时间:2012-08-06 16:52:05

标签: ajax geojson leaflet

所以我正在尝试使用Leaflet发布MapBox地图,并希望通过AJAX调用从外部数据源添加一些标记。具体来说,我用this data set映射出纽约市的所有wifi点。我看到它说我可以在JSON中下载wifi位置,但我仍然在尝试自学如何编码,不知道该怎么做。

以下是MapBox使用您站点目录中托管的.js提供的示例。如果我要进行AJAX调用会是什么样子?

<script src="museums.js"></script>
<script type="text/javascript">
// Define a GeoJSON data layer with data
var geojsonLayer = new L.GeoJSON();

// Display the name property on click
geojsonLayer.on('featureparse', function (e) {
    if (e.properties && e.properties.name){
    e.layer.bindPopup(e.properties.name);
}
});

geojsonLayer.addGeoJSON(data);

// Add the GeoJSON layer
map.addLayer(geojsonLayer);
</script>

1 个答案:

答案 0 :(得分:8)

点击wifi点数据集链接后告诉我你可以从这个网址调用json数据:wifi spot

问题是生成的json没有以GEOJSON格式(Wikipedia)格式化......

如果你有一个url给你有效的GEOJSON,你可以使用jQuery以下面的方式进行Ajax调用:

$.ajax({
    type: "POST",
    url: "https://nycopendata.socrata.com/api/views/ehc4-fktp/rows.json",
    dataType: 'json',
    success: function (response) {

        geojsonLayer = L.geoJson(response, {
            style: yourLeafletStyle
        }).addTo(map);
    }
});

此致

艾蒂安