我之前曾问过这个问题,但是简化了这个问题。我有一个要在d3 /传单中映射的带有地理坐标的JSON:
这是控制台登录JSON allSFEvents
时的结构:
(36) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
并深入研究一项:
@context: "http://schema.org"
@type: "MusicEvent"
endDate: "2019-01-27"
image: ""
location:
@type: "Place"
address: "San Francisco, CA"
geo:
@type: "GeoCoordinates"
latitude: 37.775
longitude: -122.4183333
__proto__: Object
name: "Natoma Cabana"
__proto__: Object
name: "Winter Olympics"
performer: {url: "https://www.bandsintown.com/a/217960-
winter-olympics?came_from=244", image: "", @type:
"MusicGroup", name: "Winter Olympics"}
startDate: "2019-01-27"
url: "https://www.bandsintown.com/e/1013280443-winter-olympics-at-natoma-cabana?came_from=244"
__proto__: Object
当我尝试转换为latLong坐标时:
allSFEvents.forEach(function(d) {
d.latLong = new L.LatLng(allSFEvents.location.geo[0],//first position is latitude
allSFEvents.location.geo[1];//second position is longitude
console.log(d.latLong)
})
这给了我一个错误:
Cannot read property 'geo' of undefined
如何遍历每个项目并在此处运行L / .LatLong?我似乎被困住了。目的是为每个项目获取不同的经/纬度对,以便进行映射。预先感谢。
答案 0 :(得分:0)
forEach-function遍历列表的每个元素,并且该函数的参数是列表的一项。所以d是allSFEvents-Array的一项。
https://www.w3schools.com/jsref/jsref_forEach.asp
因此,请尝试以下操作:
allSFEvents.forEach(function(d) {
//here replace allSFEEvents with d then location should be set. And replace geo[0] with geo.latitude and geo[1] with geo.longitude because geo is not an array
d.latLong = new L.LatLng(d.location.geo.latitude,//first position is latitude
d.location.geo.longitude;//second position is longitude
console.log(d.latLong)
})