Lat/Lng to Pixel X/Y - Google Maps

by iamjpg

HTML

<script src="https://maps.googleapis.com/maps/api/js?v=3&amp;amp;sensor=false"></script>
<div id="map_div">

</div>

CSS

body {
  font-family: Helvetica, Verdana, Arial, sans-serif;
}

#map_div {
  width: 100%;
  height: 600px;
}

.new_div {
  position: absolute;
  width: 50px;
  height: 50px;
  border-radius: 50px;
  background: magenta;
  text-align: center;
  line-height: 50px;
}

JavaScript

// Random Lat-Lng in Seattle
var _lat = 47.68684970494409,
  _lng = -122.28802442550659;

// Set some default map values centering on the above value.
var _map_options = {
  center: new google.maps.LatLng(47.68684970494409, -122.28802442550659),
  zoom: 17,
  mapTypeId: google.maps.MapTypeId.ROADMAP
};

// Set the map.
var _map = new google.maps.Map(document.getElementById("map_div"), _map_options);

// Map event listener. Important we know the map is ready to obtain projection.
google.maps.event.addListener(_map, 'idle', function() {

  if (document.querySelector('.new_div')) {
    document.querySelector('.new_div').remove();
  }

  // Projection variables.
  var _projection = _map.getProjection();
  var _topRight = _projection.fromLatLngToPoint(_map.getBounds().getNorthEast());
  var _bottomLeft = _projection.fromLatLngToPoint(_map.getBounds().getSouthWest());
  var _scale = Math.pow(2, _map.getZoom());

  // Create our point.
  var _point = _projection.fromLatLngToPoint(
    new google.maps.LatLng(_lat, _lng)
  );

  // Get the x/y based on the scale.
  var _posLeft = (_point.x - _bottomLeft.x) * _scale;
  var _posTop = (_point.y - _topRight.y) * _scale;

  // If our custom div marker doesn't exist build it. Else re-position it.
  if (!document.getElementById("new_div")) {
    var _div = document.createElement("div");
    _div.className = "new_div";
    _div.innerHTML = "Hi!";
  } else {
    _div = document.getElementById("new_div");
  }

  // Set the x/y properties on the DIV
  _div.style.top = _posTop + "px";
  _div.style.left = _posLeft + "px";

  // Append the div to the map div.
  // You'll want to use an google maps overlay here, but for succinctness I'm not.
  _map.getDiv().appendChild(_div);

});