0

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?

1
  • NEVER put variables directly into a database query. And if your database query isn't working, why bother with all the JavaScript and PHP code in the question?
    – miken32
    Commented Apr 11 at 21:05

1 Answer 1

0

My issue turned out being that I needed to add the first marker in my polygon as the last marker as well, ensuring that the polygon is closed and therefore loading correctly. I originally placed everything in the question because i'm dumb.

2
  • Hi, can you post in the answer the working code ?
    – erwan
    Commented Apr 14 at 12:42
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Apr 14 at 12:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.