Reputation: 498
I am querying each point of a polygon object (e in this case) using esri leaflet. To do so I have the following function that I use on a polgon that is passed to it:
const queryFeature = (e: any) => {
let nearbyCollection: any = new Array()
console.log(e)
const latlngParcel = new L.Polygon(e)
console.log(latlngParcel)
for (let n=0; n < e[0].length; n++) {
let point = L.latLng(e[0][n])
featureRef
.query()
.nearby(point, 1)
.run(function (error: any, featureCollection: any) {
if (error) {
console.log(error);
return;
} else {
featureCollection.features.forEach((i: any) => {
nearbyCollection.push({ id: i.id, name: i.properties.Situs1})})
}
})
};
return nearbyCollection
};
Which when I run console.log on the array "nearbyCollection" it shows it's contents however if I run nearbyCollection.length it is 0.
Furthermore I cant iterate over the array or pass this information to a new Array...
I am guessing it is because I am pushing to this array during an async call but I am not sure how to resolve this.
Upvotes: 0
Views: 115
Reputation: 162
I agree with John's response. I think what he is suggesting you is to do something like this:
async const queryFeature = (e: any) => {
let nearbyCollection: any = new Array()
console.log(e)
const latlngParcel = new L.Polygon(e)
console.log(latlngParcel)
for (let n = 0; n < e[0].length; n++) {
let point = L.latLng(e[0][n])
await featureRef
.query()
.nearby(point, 1)
.run(function(error: any, featureCollection: any) {
if (error) {
console.log(error);
return;
} else {
featureCollection.features.forEach((i: any) => {
nearbyCollection.push({
id: i.id,
name: i.properties.Situs1
})
})
}
})
}
return nearbyCollection;
};
const nearbyCollection = queryFeature.then(nearbyCollection => nearbyCollection).catch(err => {
console.log(err);
});
Note: Update, I'm checking do not 100% sure if this will work, in case it doesn't, I would wrap the featureRef.query().nearby(point, 1)...
in a function like this.
Upvotes: 0
Reputation: 404
the problem is indeed the async call you're making within your loop.
i'd recommend checking out 'Serializing with promises and async/await' section of the answer below...
Asynchronous Process inside a javascript for loop
it sounds a little strange that you're making a web request to do a spatial query for each individual vertex of your parcel polygons, but i'm sure you have your reasons.
Upvotes: 2