Static map from Google with no API key required [updated]
You must be a member of Google APIs Console and obtain a valid API to embed Google Maps into your website or web application. That’s a well known fact.
Not everyone knows that this is required only, if you want to embed a fully-featured Google Maps, i.e. with ability to scroll, zoom, use markers, calculate routes etc. For embedding a static image of Google Maps showing requested location you don’t need API and required Javascript code is nearly a one-liner.
Actually, it is a one-liner. I split it into several lines and variables only for clarity of reading it.
Raw example
First, get the image URL:
var
mapUrl = '',
mapZoom = 17,
mapLatitude = 78.0399665,
mapLongitude = 27.1750151,
mapWidth = 730,
mapHeight = 730,
mapOptions = '&maptype=roadmap&markers=color:green%7C';
/**
* Mini-map update
*
* Debug (Taj Mahal): 27.1750151, 78.0399665
* https://maps.google.pl/maps?q=27.1750151,78.0399665&z=17
*/
mapUrl = "http://maps.googleapis.com/maps/api/staticmap?center="
+ mapLatitude + "," + mapLongitude +
"&zoom=" + mapZoom + "&size=" + mapWidth + "x" + mapHeight + mapOptions +
mapLatitude + "," + mapLongitude + "&sensor=false";
The above code will generate a string (in mapUrl
variable) like that:
http://maps.googleapis.com/maps/api/staticmap?center=78.0399665,27.1750151&zoom=17&size=730x730&maptype=roadmap&markers=color:green%7C78.0399665,27.1750151&sensor=false
Now, you can set it (by any mean — Javascript, jQuery, Zepto, directly etc.) to your img
HTML element:
$('#map').attr('src', mapUrl);
And… enjoy! :>
A rather simple tweak up
If you’re using jQuery, Zepeto or something similar, you can change these two lines:
var ... mapWidth = 730, mapHeight = 730, ...
Into something like this:
var ... mapWidth = parseInt($('#map').css("width"), 10), mapHeight = parseInt($('#map').css("height"), 10), ...
To make sure that your map-like image will be matching your <img />
element’s dimensions.
You can achieve exactly the same in pure JavaScript, without jQuery / Zepeto, or even in pure HTML. But… for what reason? :]
January 2022 Update
I have accidentally came across this post and wanted to check, how things are going seven and a half year later. As we can expect, this is not working any longer. Right know, even for such a simply request, you are enforced to provide your own Google API key.