经纬度和瓦片互转

/**
 * 经纬度转瓦片编号
 * @param {number} lon 经度
 * @param {number} lat 纬度
 * @param {number} zoom 缩放级别
 * @return {{x: number, y: number, z: number}}
 */
function coordinateToTile(lon, lat, zoom) {
	const [l, z] = [lat * Math.PI / 180, Math.pow(2, zoom)];
	return {
		x: Math.floor((lon + 180) / 360 * z),
		y: Math.floor((1 - Math.log(Math.tan(l) + 1 / Math.cos(l)) / Math.PI) / 2 * z),
		z: zoom
	}
}

/**
 * 瓦片编号转经纬度
 * @param {number} x
 * @param {number} y
 * @param {number} z
 * @return {{lon: number, lat: number}}
 */
function tileToCoordinate(x, y, z) {
	const n = Math.PI - 2 * Math.PI * y / Math.pow(2, z);
	return {
		lon: x / Math.pow(2, z) * 360 - 180,
		lat: 180 / Math.PI * Math.atan(0.5 * (Math.exp(n) - Math.exp(-n)))
	}
}
posted @ 2022-02-12 12:42  风的线条昵称已被使用  阅读(257)  评论(0编辑  收藏  举报