Get coordinates of the mouse pointer
Show mouse position on hover with pixel and latitude and longitude coordinates.
NPM module setup
npm install --save @maptiler/sdk
import { Map, MapStyle, config } from '@maptiler/sdk';
import '@maptiler/sdk/dist/maptiler-sdk.css';
config.apiKey = 'YOUR_MAPTILER_API_KEY_HERE';
const map = new Map({
container: 'map', // container id
style: MapStyle.STREETS,
center: [-122.42162, 37.78106], // starting position
zoom: 12.69 // starting zoom
});
map.on('mousemove', function (e) {
document.getElementById('info').innerHTML =
// e.point is the x, y coordinates of the mousemove event relative
// to the top-left corner of the map
JSON.stringify(e.point) +
'<br />' +
// e.lngLat is the longitude, latitude geographical position of the event
JSON.stringify(e.lngLat.wrap());
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex">
<title>Get coordinates of the mouse pointer</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<style type="text/css">
#info {
display: block;
position: relative;
margin: 0px auto;
width: 50%;
padding: 10px;
border: none;
border-radius: 3px;
font-size: 12px;
text-align: center;
color: #222;
background: #fff;
}
</style>
<div id="map"></div>
<pre id="info"></pre>
<script type="module" src="./main.js"></script>
</body>
</html>
body {margin: 0; padding: 0;}
#map {position: absolute; top: 0; bottom: 0; width: 100%;}
Related examples
Show drawn polygon area
ExamplesUse mapbox-gl-draw to draw a polygon and Turf.js to calculate its area in square meters.
Measure distances
ExamplesTo calculate distances on the map, simply click on different points to create lines that will measure the distances using turf.length.
Get features under the mouse pointer
ExamplesShow properties of hovered map elements with queryRenderedFeatures.