Retrieving latitude/longitude of map click

This tutorial will show how we can retrieve latitude / longitude coordinates of a click on map.

The task

When user clicks or taps anywhere on the Map, we want to retrieve the geographical coordinates (latitude and longitude) of the target point.

We also want to make something useful with it, say, placing a marker on the target coordinates.

Let's go.

Retrieving coordinates of a click

To catch a click/tap we need to define a "hit" event handler. Since we want to catch clicks anyway on the map - both over "land" and "sea" - the perfect object to attach such event is seriesContainer.

chart.seriesContainer.events.on("hit", function(ev) {
// ...
});
chart.seriesContainer.events.on("hit", function(ev) {
// ...
});
{
// ...
"seriesContainer": {
"events": {
"hit": function(ev) {
// ...
}
}
}
}

Examining the "hit" event, we can see, that object received by handler, will have a svgPoint property.

This property holds X and Y coordinates of the click location within the seriesContainer.

Those are screen coordinates, though. We'll need to convert them to longitude and latitude respectively.

For that task, MapChart has a handy function: svgPointToGeo(svgPoint).

All we need to do is to pass svgPoint thorugh the above function, and we have our coordinates.

chart.seriesContainer.events.on("hit", function(ev) {
console.log(chart.svgPointToGeo(ev.svgPoint));
});
chart.seriesContainer.events.on("hit", function(ev) {
console.log(chart.svgPointToGeo(ev.svgPoint));
});
{
// ...
"seriesContainer": {
"events": {
"hit": function(ev) {
var chart = ev.target.parent.parent;
console.log(chart.svgPointToGeo(ev.svgPoint));
}
}
}
}

See the Pen amCharts 4: Retrieving lat/long coordinates of a map click by amCharts team (@amcharts) on CodePen.0

Placing markers on click

Now, let's use above knowledge to do something more useful. Let's place a new marker every time we click on a map.

We'll need to prepare a MapImageSeries which we'll be using to create new markers in. Then we can just "cookie-cut" new markers on click, and set coordinates.

chart.seriesContainer.events.on("hit", function(ev) {
var coords = chart.svgPointToGeo(ev.svgPoint);
var marker = imageSeries.mapImages.create();
marker.latitude = coords.latitude;
marker.longitude = coords.longitude;
});
chart.seriesContainer.events.on("hit", function(ev) {
var coords = chart.svgPointToGeo(ev.svgPoint);
var marker = imageSeries.mapImages.create();
marker.latitude = coords.latitude;
marker.longitude = coords.longitude;
});
{
// ...
"seriesContainer": {
"events": {
"hit": function(ev) {
var chart = ev.target.parent.parent;
var coords = chart.svgPointToGeo(ev.svgPoint);
var marker = chart.series.getIndex(1).mapImages.create();
marker.latitude = coords.latitude;
marker.longitude = coords.longitude;
}
}
}
}

Go ahead, click on a map:

See the Pen amCharts 4: Retrieving lat/long coordinates of a map click by amCharts team (@amcharts) on CodePen.0

Related content