问题
I'm working on a geo spatial web app with MongoDB. I have a lot of polygons on a collection with different categories (COUNTRY
, STATE
, etc.), and I want to know which is the COUNTRY
of a certain STATE
but in some cases the border of a neighbour COUNTRY
is touching the border of the STATE
so when I query the intersection I get 2 countries.
I want to calculate the overlapping percentage between the state and both countries to know which one is the parent. I've been looking but I didn't found any library with this kind of operation and I'm not very good doing this kind of algorithms.
EDIT: Adding more context
This is the model I'm working with
type GeoEntity struct {
ID bson.ObjectId `json:"id" bson:"_id"`
Type string `json:"type" bson:"type"` // COUNTRY, STATE, etc.
Geometry Geometry `json:"geometry" bson:"geometry"`
}
// GeoJSON entity
type Geometry struct {
Type string `json:"type" bson:"type"`
Coordinates [][][][]float64 `json:"coordinates" bson:"coordinates"`
}
And this is the chunk of code I have right now:
func findParent(state *GeoEntity) GeoEntity{
session, err := mgo.Dial("localhost")
check(err)
defer session.Close()
entities := session.DB("geo").C("entity")
query := bson.M{
"geometry": bson.M{
"$geoIntersects": bson.M{
"$geometry": state.Geometry,
},
},
"type": "COUNTRY",
}
var countries []GeoEntity
err = entities.Find(query).All(&countries)
check(err)
var parent GeoEntity
if len(countries) > 1 {
//TODO: parent = findTheTrueParent(countries, state)
} else {
parent = countries[0]
}
return parent
}
And here is an image example of the problem I'm having. When I make the query I get both countries, the red and green one, but the true parent is the green one.
回答1:
If you can assume that one polygon is always a region of another (completely contained by it), you could instead of using the entire polygon for the region just calculate the centre point of it, and use either a point or a very small square at that point to test against parents. If you have a bounding box the centre point should be easy to find.
That way you avoid the problems you're seeing with edges which overlap two parents, and it should work for any region as long as you know the region is within its parent and not just overlapping it.
So you may not even need two queries, just reduce state.Geometry to a small square around its centre-point and query with that instead.
来源:https://stackoverflow.com/questions/46455730/polygon-overlapping-percentage