Mapbox gl 1 pixel as distance
Approximate the distance of 1 px
HTML
<script src=" https://npmcdn.com/@turf/turf/turf.min.js"></script>
<script src="https://api.tiles.mapbox.com/mapbox-gl-js/v0.38.0/mapbox-gl.js"></script>
<link rel="stylesheet" href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.38.0/mapbox-gl.css">
<div id="map"></div>
CSS
#map {
height: 500px;
}
JavaScript
mapboxgl.accessToken = 'pk.eyJ1IjoiZmFyYWRheTIiLCJhIjoiTUVHbDl5OCJ9.buFaqIdaIM3iXr1BOYKpsQ';
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.addControl(new mapboxgl.ScaleControl({
maxWidth: 1,
}));
function getDistance() {
const bounds = map.getBounds();
const topLeft = turf.point([bounds._ne.lng, bounds._ne.lat]);
const topRight = turf.point([bounds._sw.lng, bounds._ne.lat]);
const bottomLeft = turf.point([bounds._ne.lng, bounds._sw.lat]);
const bottomRight = turf.point([bounds._sw.lng, bounds._sw.lat]);
const middleLeft = turf.midpoint(topLeft, bottomLeft);
const middleRight = turf.midpoint(topRight, bottomRight);
const distance = turf.distance(middleLeft, middleRight, 'kilometers');
map.getSource('geo').setData(turf.featureCollection([middleLeft, middleRight]));
return distance;
}
map.on('load', () => {
map.addSource('geo', {
'type': 'geojson',
'data': {
'type': 'FeatureCollection',
'features': [],
},
});
map.addLayer({
id: 'points',
source: 'geo',
type: 'circle',
paint: {
'circle-radius': 9,
'circle-color': '#000000',
},
});
map.on('moveend', () => {
const clientWidth = window.innerWidth;
const distance = getDistance();
const onePixel = distance / clientWidth;
console.log(`1px is ~${onePixel.toFixed(3)} km or ${Math.ceil((onePixel) * 1000)} meters`);
});
});