格式化数组存在,但点不会绘制

时间:2017-10-26 02:03:33

标签: javascript leaflet

我试图制作地图时遇到了障碍。 geojson格式化的数组将进入JS,每个控制台日志记录没有问题。

但是,我似乎无法弄清楚如何让这段代码工作。

var js_var;
$.get("my_file.php", function(data) {
      js_var=data;
       console.log(js_var)
});
  function onEachFeature(feature, layer) {
        var popupContent = "<p>I started out as a GeoJSON " +
                feature.geometry.coordinates + ", but now I'm a Leaflet vector!</p>";

        if (feature.properties && feature.properties.prop1) {
            popupContent += feature.properties.prop2;
        }

        layer.bindPopup(popupContent);
    }


  L.geoJSON(feature, {

        style: function (feature) {
            return feature.properties && feature.properties.style;
        },

        onEachFeature: onEachFeature,

        pointToLayer: function (feature, latlng) {
            return L.circleMarker(latlng, {
                radius: 8,
                fillColor: "#ff7800",
                color: "#000",
                weight: 1,
                opacity: 1,
                fillOpacity: 0.8
            });
        }
    }).addTo(mymap);

我的geojson看起来像这样:

"type": "FeatureCollection",
"Features": [
    {
        "type": "Feature",
        "properties": {
            "prop1": "value",
            "prop2": "value",

        },
        "geometry": {
            "type": "Point",
            "coordinates": "[-89.853567,39.840856]"
        }
    },

我查看了支持文档,但无法解决这个问题。

视图源:http://leafletjs.com/examples/geojson/example.html http://leafletjs.com/examples/geojson/sample-geojson.js

我错过了什么?

编辑:我发现了一个不同的例子,但仍然没有运气。

function onEachFeature(feature, layer) {
    // does this feature have a property named popupContent?
    if (feature.properties && feature.properties.prop1) {
        layer.bindPopup(feature.properties.prop1);
    }
}

var js_var;
$.get("my_file.php", function(data) {
      js_var=data;
    console.log(js_var)
});


L.geoJSON(js_var, {
    onEachFeature: onEachFeature
}).addTo(mymap); 

1 个答案:

答案 0 :(得分:1)

当您期待JSON时,您需要将dataType选项设置为json或使用$.getJSON为您执行此操作:

$.getJSON('my_file.php', function (json) {
    // here 'json' is a JSON object
});

接下来,您必须记住,XHR函数$.get$.post等是异步函数。在使用之前,您需要等待它解决。例如:

// This gets executed first
var geojson;

// This is second
$.getJSON('my_file.php', function (json) {
    // This needs to load so will be fourth
    geojson = json;
});

// Third, at which point 'geojson = json' has not been
// executed yet so it fails.
new L.GeoJSON(geojson);

将您的逻辑放入$.getJSON的回调函数中,它只能工作™:

$.getJSON('my_file.php', function (json) {
    new L.GeoJSON(json);
});