Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Drawing a Google Map using pixel space

Example: drawing on a Google Map using pixel space

This example shows you how to draw on a Google Map, without having to explicitly know any latitude or longitude. This makes it really easy to draw on a map that has been adjusted as required by a user, and can then be annotated using only the pixel size of the map as reference points.

<!DOCTYPE html>
<meta chartset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="author" content="Scott Mebberson">
<title> example</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="" type="text/css" media="screen">
#mapcanvas {
width: 100%;
height: 240px;
<script src=""></script>
<script src=""></script>
<div class="content">
<h1>Drawing on a Google Map using pixel space</h1>
<script type="text/javascript">
(function() {
var convertPixels, initialiseGoogleMap,
_this = this;
initialiseGoogleMap = function() {
var mapOptions;
mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}; = new google.maps.Map(document.getElementById('mapcanvas'), mapOptions);
this.overlay = new google.maps.OverlayView();
this.overlay.draw = function() {};
return setTimeout(getCenter, 100);
this.lineSymbol = {
path: 'M 0,-1 0, 1',
strokeOpacity: 1,
strokeWeight: 1,
scale: 3
this.getCenter = function() {
var bottom, center, middle, polyline;
center = map.getCenter();
middle = $('#mapcanvas').width() / 2;
bottom = $('#mapcanvas').height();
_this.aLines = [convertPixels(middle, 0), convertPixels(middle, bottom)];
return polyline = new google.maps.Polyline({
path: aLines,
strokeOpacity: 0,
icons: [
icon: lineSymbol,
offset: '0',
repeat: '10px'
map: map
convertPixels = function(x, y) {
return overlay.getProjection().fromDivPixelToLatLng(new google.maps.Point(x, y));
window.addEventListener('load', initialiseGoogleMap);
<div id="mapcanvas"></div>
<p>This example draws on a Google Map using pixel space, rather than specific knowledge of lat/lng or map zoom and center. You should see a vertical dashed line straight through the center of the map above.</p>
<p class="highlight">To make this example work, you'll need to add your Google Maps API key to this example.</p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.