I have this pice of code:
and I'm getting this result:
The centroids are not in center of parcels, and some are outside their parcels.
There is no point in publishing all code (I can do that on request), but changing this line:
for ilustrating the center of the extent of the parcel instead of the centroid give better results:
Note that this is not a good solution:
I have added the extent for the last two parcels to show that the centre of the extent is not the desired solution, but this is a lot better solution that the getCentroid function the way I got it.
The coordinates are projected? If they are, and are in Web Mercator, it is not a very good projection to use for anything that requires spatial calculations (ie distance, area etc). Your extent center seems appropriate for your examples, but may fail elsewhere. Does your interface have labelPoint ? worth a try particularly for 'centers' that may fall outside of polygons.
I get that the code was OK.
Now here is some data (one of the center of an extent):
I’ve completed a short demo for the getCentroid issue.
You may find the code at:
and execute the application at:
You may need credentials to see our layer service – let us know.
When running the “get Centroid” button there is a 50/50 chance to get a(n almost) correct centroid, so, give it a chance: inspect more than one parcel…
The docs claim that getCentroid finds the centroid of the largest ring in a multi-part polygon, however, i have observed that to not be the case. It seems to randomly pick one of the rings (maybe it's the first) and do the centroid of that. I had a county that was on the coast and so had some islands and it picked one of the tiny islands to do the centroid of. I wonder if some of those parcels that are giving bad centroids are multi-part (or self intersecting) and have had their geometry fixed causing them to have tiny slivers you aren't seeing, but that are being chosen to do the centroid on. I would get a hold of the source data and inspect the polygons that don't work and see where their vertices are. I bet they have a sliver jutting out from them or something.
In my case, I look only at polygons with a single ring, and I have observed the error there (as the returned point in not a centroid, sometimes being totaly out of a convex pologon.)
But in your case, I wonder what the largest ring is: is it the largest in surface, or in number of vertexes? In the second case, you may have an small island with more vertexes that the big land body...