Skip to content

Retrieving latitude/longitude of map click

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

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.

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) { // ...});

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));});
Open in CodePen

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;});

Go ahead, click on a map:

Open in CodePen