Skip to content

9 Add Click Interaction

Oliver Heilig edited this page Jan 19, 2016 · 22 revisions

The data from http://thematicmapping.org/downloads/world_borders.php is incomplete and has errors. Italy has a population of 5 mio!? Better get some professional data from DDS.

Now we want to make our map interactive, so we can click on a country to get detailed information. We add a click hander 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);
        }
    });
});

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

var strSql = string.Format(CultureInfo.InvariantCulture,
    @"SELECT WorldGeom.Id, AsText(Geometry), Name, Region, Area, Pop FROM WorldGeom " +
    @"JOIN WorldData on WorldData.Id = WorldGeom.Id " +
    @"WHERE Intersects(Geometry, MakePoint({0}, {1}));",
    lng, lat);

From the result we build a GeoJSON that can be interpreted by leaflet. The result is a handler like this: http://80.146.239.139/SpatialTutorial/08-SpatialPickingHandler.ashx?lat=49&lng=8.4, the response can be testet 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: http://80.146.239.139/SpatialTutorial/08-SpatialPicking.html

I don't think Intl.NumberFormat() works in every browser.