Interactive by Nature

Dynamic Google Map Width


I’m building a skatepark finder mobile web app. I’m using Google Distance Matrix API to get the distance between the user’s location and the location of the nearest skatepark. Because of this little disclaimer “Use of the service in an application that doesn’t display a Google map is prohibited.“, I need to show a map in the app.

Since this is for mobile web, I didn’t want to display an interactive map because reducing HTTP requests and especially requests to 3rd party services is a mobile development best practice. Also, I can just create a button that links to Google maps and let the user use an interactive map however they see fit.

To minimize the service requests for the map, I decided to go with a static map. The problem with this is the limitations in the request URL. The request URL looks something like this:,-104.9847034&zoom=14&size=320x180&sensor=true

Notice that the size parameter is a static number and it’s required, so you have to put something in there. I don’t know if the user is using a smartphone, tablet or desktop, so I want the map to stretch the width of the application. Otherwise, you get something looking like this in landscape view on an iPhone:

Bad Map


Thankfully we can use jQuery’s .width() method which returns the width of an element. So, to get the width of the browser viewport, we use it like this:

var mapWidth = $(window).width();

Once you have that number in a variable, you can inject it right into your URL string by replacing the width section of the parameter like this:

var mapImageURL = 'https://...size='+mapWidth+'x180...';

Because there are two dynamic variables to this, I used jQuery’s .html() method function to assemble and inject the img tag into an empty div with the id location-map.

$('#location-map').html(function() {

    var mapImageURL = ',-104.9847034&zoom=14&size='+mapWidth+'x180&sensor=true';

    return '<img decoding="async" src="'+mapImageURL+'" alt="Location Map">';

This technique won’t change the map image size on orientation change. That would require a new request to Google maps and I want to avoid making another HTTP request.

If you know of a different or better way of doing this, please share in the comments below.


  1. Thank you very much!!!
    This is exactly what I’ve been looking for all day!!
    You’re awesome!!!

    Monica on December, 17th, 2013 at 7:36 am

Leave a Comment