JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://yandex.st/jquery/2.2.3/jquery.min.js"></script>
<div id="result" style="width: 500px;"></div>
JavaScript
// Available projections and corresponding eccentricity values.
var projections = [{
name: 'wgs84Mercator',
eccentricity: 0.0818191908426
}, {
name: 'sphericalMercator',
eccentricity: 0
}],
// To calculate the number of the required tile, you should set the parameters:
// - map zoom level;
// - geographic coordinates of the object falling within the tile;
// - projection for which you need to get the tile.
params = {
z: 0,
geoCoords: [55.733776, 37.587936],
projection: projections[0]
};
// Function for converting the geographic coordinates of an object
// into global pixel coordinates.
function fromGeoToPixels (lat, long, projection, z) {
var x_p, y_p,
pixelCoords,
tilenumber = [],
rho,
pi = Math.PI,
beta,
phi,
theta,
e = projection.eccentricity;
rho = Math.pow(2, z + 8) / 2;
beta = lat * pi / 180;
phi = (1 - e * Math.sin(beta)) / (1 + e * Math.sin(beta));
theta = Math.tan(pi / 4 + beta / 2) * Math.pow(phi, e / 2);
x_p = rho * (1 + long / 180);
y_p = rho * (1 - Math.log(theta) / pi);
return [x_p, y_p];
}
// Function to calculate tile number based on global pixel coordinates.
function fromPixelsToTileNumber (x, y) {
return [
Math.floor(x / 256),
Math.floor(y / 256)
];
}
// Convert the geographic coordinates of the object to global pixel coordinates.
pixelCoords = fromGeoToPixels(
params.geoCoords[0],
params.geoCoords[1],
params.projection,
params.z
);
// Calculate the tile number based on pixel coordinates.
tileNumber = fromPixelsToTileNumber(pixelCoords[0], pixelCoords[1]);
// Display the result.
document.addEventListener("DOMContentLoaded", function () {
document.getElementById("result").innerHTML = "<b>Initial data:</b><p>" +
"– zoom level: " + params.z + "<br/>" +
"– geographic coordinates: [" +...