这是一个(希望得到很好的评论)示例,说明如何迭代 json 对象并使用数据创建标记。
// Pretend this is the response from reading a file
var geoJson = {
resources: [{
x: 4288,
y: -4288,
}, {
x: -2320,
y: -4000,
}, {
x: -2320,
y: -4080,
}, {
x: -2400,
y: -804,
}, {
x: -2370,
y: -1092,
},
{
x: -2470,
y: -1192,
},
{
x: -2320,
y: -1122,
},
{
x: -2570,
y: -1125,
},
{
x: -1350,
y: -1252,
},
{
x: -1355,
y: -2125,
}]
};
// Iterate over the resources array of the geoJson object
// Nested properties of object literals (JSON) can be accessed using dot notation or array syntax
// eg: dot notation: geoJson.resources
// eg: array syntax: geoJson["resources"]
for (var i = 0; i < geoJson.resources.length; i++) {
// Create a local variable pointing to the
// coordinate pair object at index i in the resources array of objects
var currentCoordPair = geoJson.resources[i];
// Construct a 2 item array containing the x and y values of the current object
var xyArray = [currentCoordPair.x, currentCoordPair.y];
// Create a new marker object just like you did before
var marker = L.marker(xyArray, {icon: icon01});
// Add the marker to the map
var addedMarker = marker.addTo(map);
// Bind your popup
addedMarker.bindPopup("Base");
}
还有一个指向 plunker 的链接,它只是您的代码的一个分支。
http://plnkr.co/edit/O8xqcQlWJM3JiztQXePP
我注意到您正在处理您提供的 Plunker 的其他区域中的 LatLng 值。假设你有一个像下面这样的对象:
{lat: 152.25151, long: 125.51251} // Just example values
在这种情况下,您可以按照我上面展示的相同方式访问这些值并将其应用于标记。不同之处在于您将访问 currentCoordPair.lat 而不是 currentCoordPair.x
希望有帮助