Calculate Google Static Map Image bounding box

HTML

<img id="myimg" height="480" />

JavaScript

const ApiKey = null;

const _C = { x: 128, y: 128 };
const _J = 256 / 360;
const _L = 256 / (2 * Math.PI);

function tb(a) {
	return 180 * a / Math.PI
}

function sb(a) {
	return a * Math.PI / 180
}
	
function bounds(a, b, c) {
	null != b && (a = Math.max(a, b));
	null != c && (a = Math.min(a, c));
	return a
}

function latlonToPt(ll) {
  a = bounds(Math.sin(sb(ll[0])), -(1 - 1E-15), 1 - 1E-15);
  return {
  	x: _C.x + ll[1] * _J,
    y: _C.y + 0.5 * Math.log((1 + a) / (1 - a)) * - _L
  }
}

function ptToLatlon(pt) {
	return [tb(2 * Math.atan(Math.exp((pt.y - _C.y) / -_L)) - Math.PI / 2),(pt.x - _C.x) / _J]
}


function calculateBbox(ll, zoom, sizeX, sizeY, scale) {
	const cp = latlonToPt(ll);
  const pixelSize = Math.pow(2, -(zoom + 1));
  const pwX = sizeX*pixelSize;
	const pwY = sizeY*pixelSize;
  
	return {
  	ne: ptToLatlon({x: cp.x + pwX, y: cp.y - pwY}),
    sw: ptToLatlon({x: cp.x - pwX, y: cp.y + pwY})
	}
}

function start() {
  const center = [37.78770300000001,-122.391971];
  const zoom = 16;
  const size = 640;
  const scale = 2;
  
  const { ne, sw } = calculateBbox(center, zoom, size, size, scale);
  console.log(sw, ne);
  
  const markers = [];
  markers.push(`color:red|${center[0]},${center[1]}`);
  const markerText = markers.map(x => `markers=${encodeURIComponent(x)}`).join('&')

  const polygon = `color:0xff0000cc|weight:5|fillcolor:0xFFFF0033|${ne[0]},${ne[1]}|${ne[0]},${sw[1]}|${sw[0]},${sw[1]}|${sw[0]},${ne[1]}|${ne[0]},${ne[1]}`;

  let url = `https://maps.googleapis.com/maps/api/staticmap?maptype=satellite&format=png32 &scale=${scale}&center=${center[0]},${center[1]}&zoom=${zoom}&size=${size}x${size}&${markerText}&path=${polygon}`;
  if (ApiKey) url += '&key=' + ApiKey;

  document.getElementById('myimg').src = url;
}

start();