Skip to content

Instantly share code, notes, and snippets.

@iamjpg
Last active September 19, 2018 10:23
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save iamjpg/6301054 to your computer and use it in GitHub Desktop.
Google Maps v3 – Translate Physical Latitude/Longitude into Screen Pixel X/Y
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>google_maps_custom_point</title>
<style>
body {
margin: 0;
padding: 0;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.9&key=AIzaSyDciDh5LCPwyxG8tml6998d80mlukEj8Q4&sensor=false"></script>
<script>
// jQuery makes DOM ready simple.
$(document).ready(function() {
// 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() {
// 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.id = "new_div";
_div.style.position = "absolute";
_div.style.padding = "10px";
_div.style.background = "#000000";
_div.style.color = "#FFFFFF";
_div.style.zIndex = "20000";
_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.
document.getElementById("map_div").appendChild(_div);
});
});
</script>
</head>
<body>
<div id="map_div" style="position: absolute; width: 100%; height: 100%;"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment