gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:11:04 26 4
gpt4 key购买 nike

我在尝试制作 map 时遇到了障碍。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);

最佳答案

当您需要 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);
});

关于javascript - 存在格式化数组,但点不会绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46944716/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com