Latitude to Longitude to Pixel
by Jason Bellis
HTML
<script src="https://api.tiles.mapbox.com/mapbox-gl-js/v0.28.0/mapbox-gl.js"></script>
<link rel="stylesheet" href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.28.0/mapbox-gl.css">
<div id="map" class="map"></div>
<pre id='info'></pre>
CSS
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
#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;
}
JavaScript
mapboxgl.accessToken = 'pk.eyJ1Ijoic3Rvb2t5IiwiYSI6ImNpZWxncnU5MDAwYTNzZWt1N2VoNHBiajYifQ.PPBpAP3rWcAAnMiAu1iJLg';
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/streets-v9', //stylesheet location
center: [-74.50, 40], // starting position
zoom: 9 // starting zoom
});
map.on('mousemove', function (e) {
//Try using project!
var pixel = map.project([Number(e.lngLat.lng), Number(e.lngLat.lat)]);
pixel.x = Math.round(pixel.x);
pixel.y = Math.round(pixel.y);
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) + '<br />' +
//JSON.stringify(e.lngLat.lng);
JSON.stringify(pixel);
});