Skip to content

9 Add Click Interaction

Oliver Heilig edited this page Sep 2, 2024 · 22 revisions

Now we want to make our map interactive, so we can click on a country to get detailed information. We add a click handler function that makes a request on our middleware via jQuery and passes the latitude and longitude as paramters.

map.on('click', function onMapClick(e) {
    $.ajax({
        url: "08-SpatialPickingHandler.ashx?lat=" + e.latlng.lat + "&lng=" + e.latlng.lng,
        type: "GET",
        success: function (data, status, xhr) {
            displayResult(data, e.latlng);
        }
    });
});

Inside the handler we build an SQL that queries the properties of the country which contains the point.

// Select elements containing the point, pre-filter with mbr-cache to optimize performance
var query = FormattableString.Invariant(
    $@"
    SELECT WorldData.Id, AsGeoJSON(Geometry), Name, Region, Area, Pop from 
        (SELECT * from WorldGeom 
            WHERE ROWID IN 
                (Select rowid FROM cache_WorldGeom_Geometry WHERE
                    mbr = FilterMbrIntersects({lng}, {lat}, {lng}, {lat}))
            AND Intersects(Geometry, MakePoint({lng}, {lat}))) as g                 
        JOIN WorldData on WorldData.Id = g.Id 
    ");

From the result we build a GeoJSON that can be interpreted by leaflet. The result is a handler like this: https://spatialtutorial.azurewebsites.net/08-SpatialPickingHandler.ashx?lat=49&lng=8.4, the response can be tested at GeoJson Lint.

In Leaflet we can use this result to render the GeoJSON as polygon and display the properties in a popup.

Finally we get this: https://spatialtutorial.azurewebsites.net/08-SpatialPicking.html