I am using leaflet maps to draw polygons , I save only one polygon each time , coordinates data are saved in mongodb , here is how one saved polygon data looks like in database:
{
"_id": {
"$oid": "66951c1f1d5ccea27f03cd28"
},
"id": 405,
"type": "polygon",
"coords": [
[
30.608626407820356,
31.720967336485014
],
[
30.09193235135625,
31.753944088506564
],
[
30.006344842807106,
31.28677343486776
],
[
30.281861608344087,
31.171354802792283
],
[
30.608626407820356,
31.720967336485014
]
],
"options": {
"color": "#47dd3c"
},
"zone": {
"code": "1",
"name": "sddsa",
"description": "sddas",
"color": "#9a7474",
"updated_at": "2024-07-15T12:54:55.000000Z",
"created_at": "2024-07-15T12:54:55.000000Z",
"id": 1
},
"updated_at": {
"$date": "2024-07-15T13:15:30.700Z"
},
"created_at": {
"$date": "2024-07-15T12:54:55.972Z"
}
}
and here is how the polygon data are sent to backend:
"
[{"id":362,"type":"polygon","coords":[[29.744370137958683,30.967977436404976],[29.069636417803626,31.97926449839962],[28.78116333312449,30.88003943101416]],"options":{"stroke":true,"color":"#3388ff","weight":4,"opacity":0.5,"fill":true,"fillColor":null,"fillOpacity":0.2,"clickable":true}}]
◀
"
I use json_decode to be able to handle the data and manipulate it and save it to database.
Is there a method to validate that this polygon doesn’t intersect with or contains or is contained in any previously saved polygon?
I tried making this function to validate polygon data after using json_decode() :
public function validateGeoData($geoData, $currentZoneId = null)
{
$coords = $geoData->coords;
if ($coords[0] !== end($coords)) {
$coords[] = $coords[0];
}
// Ensure coordinates are properly formatted as arrays of arrays
$formattedCoords = array_map(function ($coord) {
return is_array($coord) ? $coord : [$coord];
}, $coords);
$geoJson = [
'type' => 'Polygon',
'coordinates' => [$formattedCoords]
];
// Start with a base query for checking intersections
$query = GEOZone::whereRaw([
'coords' => [
'$geoIntersects' => [
'$geometry' => $geoJson
]
]
]);
// Exclude the current zone ID if provided (for update scenario)
if ($currentZoneId) {
$query->where('zone.id', '!=', $currentZoneId);
}
// Check for intersections
$intersectingZones = $query->exists();
if ($intersectingZones) {
return __('Zone.this_zone_intersects_with_an_existing_zone');
}
// Additional custom validations can be added here if needed
return null; // Return null if validation passes
}
And I then add its return to validation errors and it works fine in case of the new polygon contains a previously existing polygon and in some cases of intersection. But in other cases of intersection and if new polygon is contained in a previously existing polygon, validation doesn’t work and record is saved successfully.