I use Leaflet.js, FreeDraw, and Laravel to create a real estate system. The functionality I am trying to set up is that when the user draws a polygon on the map, it should trigger an API call and only load the markers inside it. I have the following JavaScript for drawing:
freeDraw.on('markers', event => {
// Handle the case where no polygons are drawn yet
if (event.latLngs.length > 0) {
event.latLngs.forEach((polygonLatLngs) => {
var polygon = L.polygon(polygonLatLngs, {
color: 'black',
fillColor: 'green',
fillOpacity: 0.5
}).addTo(map);
polygonObjects.push(polygon);
});
$("#freeDrawingMap").removeClass("active");
freeDraw.mode(FreeDraw.NONE); // Change to VIEW mode or disable drawing as needed
callGetListingMarkersAPI();
}
});
function callGetListingMarkersAPI() {
var polygonsData = polygonObjects.map(polygon => {
return polygon.getLatLngs()[0].map(latlng => ({
lat: latlng.lat,
lng: latlng.lng
}));
});
console.log(polygonsData);
var formData = {
_token: '{{ csrf_token() }}',
markers: JSON.stringify(polygonsData)
};
$.ajax({
type: 'POST',
url: '{{ route('getListingMarkers') }}',
contentType: "application/x-www-form-urlencoded",
data: formData,
success: function(response) {
console.log(response);
window.updateMapMarkers(response.markers);
},
error: function(xhr) {
console.error("Error fetching markers:", xhr.responseText);
}
});
}
In my API, I have:
if ($request->has('markers') && !empty($request->markers)) {
$polygons = json_decode($request->markers, true);
$multiPolygonWKT = 'MULTIPOLYGON((';
foreach ($polygons as $polygon) {
$polygonWKT = '(';
foreach ($polygon as $vertex) {
$lng = $vertex['lng'] ?? 0;
$lat = $vertex['lat'] ?? 0;
$polygonWKT .= "$lng $lat,";
}
$polygonWKT = rtrim($polygonWKT, ',') . ')';
$multiPolygonWKT .= $polygonWKT . ',';
}
$multiPolygonWKT = rtrim($multiPolygonWKT, ',') . '))';
$query->whereRaw("ST_Within(location, ST_GeomFromText('$multiPolygonWKT', 4326))");
$sql = $query->toSql();
$bindings = $query->getBindings();
echo 'Query: ' . $sql . "\n";
echo 'Bindings: ' . implode(', ', $bindings) . "\n";die;
}
Further down in the function, I have the code to generate the markers based on my $query
. I have set up everything in my database, and I can load the points from my field without an issue. I have also added a lot of logging to see what is happening, and I can see the polygons being passed correctly to the backend and an empty array being passed to the frontend. I have tested this with different values and polygon sizes and can't seem to get it to return anything. I also printed out my SQL and placed it directly into my database, but again, I got no output. Am I missing a package or something, or do I have an error I'm not seeing?