GoogleMaps API v3: convert LatLng object to actual pixels

Blog / JavaScript ·

It is not so easy as it looks like. You should get the map object's projection and the map's zoom to be able to calculate it.

function fromLatLngToPoint(latLng, map) {
  var topRight = map.getProjection().fromLatLngToPoint(map.getBounds().getNorthEast());
  var bottomLeft = map.getProjection().fromLatLngToPoint(map.getBounds().getSouthWest());
  var scale = Math.pow(2, map.getZoom());
  var worldPoint = map.getProjection().fromLatLngToPoint(latLng);
  return new google.maps.Point((worldPoint.x - bottomLeft.x) * scale, (worldPoint.y - topRight.y) * scale);
}

The function returns Point object, which has .x and .y property - the actual pixels of your map's container.


Krasimir Tsonev With over two decades of deep programming expertise, I offer comprehensive web consultancy and stack audits, alongside specialized workshops, training, and engaging public speaking to elevate your team's skills and optimize your digital presence. Contact me.

Keywords: map var map getprojection fromlatlngtopoint worldpoint scale object fromlatlngtopoint map getbounds getprojection fromlatlngtopoint map
Share the post on Twitter, Facebook, LinkedIn