File Exchange

image thumbnail


version (12.6 KB) by Zohar Bar-Yehuda
Plot a google map on the background of the current figure using the Static Google Maps API.


Updated 22 Apr 2020

From GitHub

View Version History

View license on GitHub

Editor's Note: This file was selected as MATLAB Central Pick of the Week

plot_google_map.m uses the Google Maps API to plot a map in the background of the current figure.
It assumes the coordinates of the current figure are in the WGS84 datum, and uses a conversion code to convert and project the image from the coordinate system used by Google into WGS84 coordinates.
The zoom level of the map is automatically determined to cover the entire area of the figure. Additionally, it has the option to auto-refresh the map upon zooming in the figure, revealing more details as one zooms in.
The following code produces the screenshot:
plot_google_map('apiKey', '<Your_API_Key>') % You only need to run this once, which will store the API key in a mat file for all future usages
lat = [48.8708 51.5188 41.9260 40.4312 52.523 37.982];
lon = [2.4131 -0.1300 12.4951 -3.6788 13.415 23.715];
plot(lon, lat, '.r', 'MarkerSize', 20)
plot_google_map('MapScale', 1)

Due to changes to the Google Maps billing model, you now must set your own Google Maps API key and enable billing for your project. You're getting an automatic credit of 200$/month, which will be enough for 100,000 static maps calls without actually being billed.

Note that this does pose some challenges if you want to deploy your code, as your API key will need to be deployed with the code / as a mat file and hence may be exposed to users.

Known Issues:
1) Saving the map with an image/matrix overlay drawn on top of it (especially a semi-transparent one) can sometimes cause unexpected results (map not showing etc.). If you're encountering such problems, it's recommended to use the export_fig submission:
The combination that seems to work best:

Cite As

Zohar Bar-Yehuda (2021). zoharby/plot_google_map (, GitHub. Retrieved .

Comments and Ratings (275)

sandeep singh

how can I get API key, I was using this function for mapping purpose but now cant use it, how to get it back to track?
Warning: Unable to download map form Google Servers.
Matlab error was: Error using urlreadwrite (line 94)
Error downloading URL. Your network connection may be down or your proxy settings
improperly configured.

Possible reasons: missing write permissions, no network connection, quota exceeded, or
some other error.
Consider using an API key if quota problems persist.

d n

Di Ao

Where should we place the downloaded package? Toolbox of Matlab?

jj rice


is there a way around the API key? or can you only plot the google map with an API key?

Julio Castro

Hello, I am an oceanographer and I use your program a lot. I consider it to be an excellent program and it is very versatile. However, I need an option to center the map on specific basins, for example the Pacific Ocean, so when graphing there are no graphs on each side of the map.

Bill Kulp

Tongtong Xu

Sebastien Belin

Great job !

WANG Jason

Really useful for autonomous driving simulation.


Hi. Do you know if this code can be used for a heatmap? I mean, for each node you provide not only the coordinates, but also one extra "weight" that gives the color of the node.

arci biyo

arci biyo

Hi everyone, I got this command(below) in the matlab command window.I really need this function. How can solve my problem? If it is releated with API Key , how can integrate my api or another api to matlab??

Warning: Unable to download map form Google Servers.
Matlab error was: Error using urlreadwrite (line 98)
Error downloading URL. Your network connection may be down or your proxy settings improperly configured.,0&zoom=1&scale=2&size=640x640&maptype=roadmap&format=png&markers=&sensor=false&key=<AIzaSyDL-b5d_HX_sljOdujz0N0oy8FWUcA_8ic>

Ilya Shipachev


Very useful script, works perfectly for my purpose.
I only have one request. I would need the map to be updated (callback @update_google_map) when axis limits change. Currently Refresh only listens to zoom and pan actions from user.
I tried adding an addlistener on xlim and ylim in the Refresh section, but I only got the plot process to freeze.
Any idea ?

Many thanks in advance


John McDowell

Naveed Ahmed

It is partially working for me. The maps are loaded by the API Key that i generated. However, I get the following warning and the map does not show and only points are plotted. For security reasons the API Key is obscured.

Warning: Unable to download map form Google Servers.
Matlab error was: Error using urlreadwrite (line 98)
Error downloading URL. Your network connection may be down or your proxy settings improperly configured.

Possible reasons: missing write permissions, no network connection, quota exceeded, or some other error.
Consider using an API key if quota problems persist.

To debug, try pasting the following URL in your browser, which may result in a more informative error:,0&zoom=1&scale=2&size=640x640&maptype=roadmap&format=png&markers=&sensor=false&key=AIzaSyBrkjekrjekljrlqk-rowqrljtzEk
> In plot_google_map (line 451)

When I check the link it says, this site cannot load the Google maps correctly.

Please help..

@Shraddha singh , do you also get the same warning?


shraddha singh

how to connect api key to matlab project ?

Josh Hwa

Hi, I am using version R2018a and I faced the problem that mentioned at here before which is
Warning: Axis limits are not reasonable for WGS1984, ignoring. Please make sure your plotted data in WGS1984 coordinates,

Is there any valid xlim/ylim example can be shown about how to set the zoom level manually and then call plot_google_map again?

you yi

when i run this code, i find it is better to use websave instead of urlwrite.

Evan Bates

Hello Zohar,

Amazing function. Could you please explain how to use it within App Designer? It throws an error when defining the axes handle:

Error using uistack (line 53)
Functionality not supported with figures created with the uifigure function. For more information, see Graphics Support in App

Vojtech Simak

200$... too expensive...

Prasunika khare

did billing deduct amount ..??? It is free of cost or not. ????.. when I used API key from without billing account after running 5 time it is not giving graph . Please help

Prasunika khare

Habiba Halilu

I got the same error as @Anuj Sinha and I solved it by doing two things
1) Enabling billing for the user account
2)Enabling the "Maps Static API" for the project that was used to generate the API key used in the code, this option can be found in the "API & SERVICES" section

Anuj Sinha

When I run, it shows the error:

error was: Error using urlreadwrite (line 98)
Error downloading URL. Your network connection may be down or your proxy settings improperly configured.

Possible reasons: missing write permissions, no network connection, quota exceeded, or some other error.
Consider using an API key if quota problems persist.

To debug, try pasting the following URL in your browser, which may result in a more informative error:,0&zoom=1&scale=2&size=640x640&maptype=roadmap&format=png&markers=&sensor=false
> In plot_google_map (line 451)

ans =


Please suggest.


@Delong Tao, I've met the same problem with you. Have you solved it?
So it means that enabling billing is mandatory or not?

Osama Asghar

Hey Zoharby you have done a fantastic work but i am facing a problem that when i am zooming the figure or panning it gives me error:
Warning: An error occurred during the mode callback.
> In uitools.uimode.fireActionPostCallback at 14
In C:\Program Files\MATLAB\R2014a\toolbox\matlab\graph2d\zoom.p>localApplyZoomFactor at 1751
In C:\Program Files\MATLAB\R2014a\toolbox\matlab\graph2d\zoom.p>local2DButtonUpFcn at 1231
In hgfeval at 62
In uitools.uimode.modeWindowButtonUpFcn at 53
In uitools.uimode.setCallbackFcn>localModeWindowButtonUpFcn at 54

Warning: An error occurred during the mode callback.
> In uitools.uimode.fireActionPostCallback at 14
In pan>locWindowButtonUpFcn at 505
In hgfeval at 62
In uitools.uimode.modeWindowButtonUpFcn at 53
In uitools.uimode.modeControl>localModeWindowButtonUpFcn at 164

please help me


Works perfectly, but I'm not able to use this within app designer. Could you explain how to plot this with a app (e.g. plot in UIAxes)


it seems that Googe doesn't allow the API use without key anymore. I got a key and with this it works.
Means to set "APIKey" seems to be mandatory...

Delong Tao

Hi, Zoharby,I met the same problem when I used the 'plot_google_map', a unexpected results (map not showing). I past the URL in my browser ,and it can display the map which i need. But I can't download map into the Figure in matlab.
(PS: I have billed on my project to use this API )

Warning: Unable to download map form Google Servers.
Matlab error was: Error using urlreadwrite (line 98)
Error downloading URL. Your network connection may be down or your proxy settings improperly configured.

Possible reasons: missing write permissions, no network connection, quota exceeded, or some other error.
Consider using an API key if quota problems persist.

To debug, try pasting the following URL in your browser, which may result in a more informative error:,100.7196225&zoom=9&scale=2&size=640x640&maptype=satellite&format=jpg&markers=&sensor=false&key=XXXXXXXXX

Ismail Bes


since some weeks the tool doesn't work anymore without key on my PC.
Using an valid API key still gives me an error for urlreadwrite.

Anyone similar experience?

Simran Sandhu

Once I get my Google API key, how to use it in my MATLAB code?

Simran Sandhu

how can I get API key, I was using this function for mapping purpose but now cant use it, how to get it back to track?
Warning: Unable to download map form Google Servers.
Matlab error was: Error using urlreadwrite (line 94)
Error downloading URL. Your network connection may be down or your proxy settings
improperly configured.

Possible reasons: missing write permissions, no network connection, quota exceeded, or
some other error.
Consider using an API key if quota problems persist.

Naty Shemer


The moment I enabled billing on my Google Project, the function started to work again.


Goole:The Google Maps Platform server rejected your request. This API project is not authorized to use this API.
I change a computer and use the same key, and it's working!
But I don't know what happend?


@anastasia soledad
Desafortunadamente, no puedo ayudarte porque no he resuelto este problema.

anastasia soledad

tengo el mismo problema de CK Chen hay alguna forma de arreglarlo???


Does the api key have to be bound to a credit card to use?
I have api key, I posted the key to line 139 of the code, but I still can't draw successfully.
line 139 of the code:apiKey = '******************';

Zohar Bar-Yehuda

To all people facing issues with access -
Enabling billing on your Google Project from which you generated the API Key might solve the issues. Free quotas are very high, so you're unlikely to face any charges.


@Thomas Powers
$300 ? Oh no! This is too expensive!

Thomas Powers

I had the same issue with the maps not working. I was able to sign up for the google maps api and they gave $300 free credit to start off. That may be sufficient for your needs; it was for mine!

Seb Biass

There have been some changes in the policies of access to Google Map with the API. It has always been an option to use an API in this script, but it seems that it is not free anymore.


How to do?About the "api keys" problems? Help me plz!!

Leandro Elias

me too


idem as Federico and cyhero


I met the same problem with API key as Fedrico.


Is it just for me or is it not working anymore? I tested in on two machines with and without an API key and it seems to be unable to download maps from the servers. Did google sliced off another good tool with a policy change?

Milad Jalali

Great Tool. worked as advertised. Thanks!

Adil Ahsan

Excellent tool... Such a great and useful tool... Made my life (or at least the next few weeks) so much easier... Great work... :)

Very easy to use, some nice examples are available and works better than a charm.. cause charms don't actually work... this does... :)


Christopher Chin

Shyamal Rao

This is a great application. Works awesome. I have one question .. If I want to input the Latitude & Longitude values in Feet then how should I do it ??

Salma Habbachi

Tis is very useful, Thank you !!!

Aaron Wells

April Warnock

Ryan Thorpe

Himanshu Mathur

hey I am getting only a white background with points in red ?


Dianne Deauna

Life changing

Dianne Deauna


shubham gupta


Shoaib Ehsan


Works extremely well; bravo!

Steve Cowper

A great tool!

Zohar Bar-Yehuda

@Dmitry Aleynik - this can be achieved using custom styling:

Dmitry Aleynik

Excellent tool, I've used it for publication with the references to the source -
btw, is it possible to colour the sea in the white or make it completely transparent ?
Thanks, Dima

Yohei Shibata


I use it in a subplot. It works fine. However I have now encountered a small issue. After finishing my subplots I usually do some small adjustments to make the figure ready for publication.

When I use: set(findobj(gcf,'type','axes'),'FontName','Arial','FontSize',10,'FontWeight','Bold', 'LineWidth', 1.5); all the subplots will be adjusted, however on the subplot with the map in the background only the font gets adjusted, so the linewidth of the 'box / axis' surrounding the figure are much thinner than the other subplots. How can I solve this?

Yongqiang Zhou

Rhianna Cardamone

Would it be possible for this function to plot into an AppDesigner UI axis?

Zohar Bar-Yehuda

@Jesse de Vroet - It works fine here... Send me the details to my email:
Code sample, any errors messages you're seeing, etc. Also maybe try to put a breakpoint on line 413 and send me the content of the "url" variable. Try to open it in your browser and see if it loads an image of the map.

Jesse de Vroet

@Zohar Bar-Yehuda Thank you for your reply. I tried the latest code with plot_google_map('language','nl','showLabels',0,'style','feature:water|element:geometry.fill|visibility:off'). The map won't plot using this arguments. Can you please provide help with setting up the arguments?


Zohar Bar-Yehuda

@Jesse de Vroet - this was indeed a bug. showLabels=0 simply appends an extra custom style, and this was done incorrectly in the case when a style was already passed. Use the last code version, it should fix it.

Jesse de Vroet

This is a great tool for plotting data on a map. It is really easy to use.

Unfortunately I encounter this problem: when using this query:
the labels disappear but the fill of the water doesn't. When only using
the labels are there obviously but the fill isn't. I would like to combine these two but I can't get it to work...

Am I doing something wrong or is this a bug?


Great tool! Small bug with the varargout's the indexing on lines 535, 536, 637 is off by one. uniImag should be put into index 4 etc.


Zohar Bar-Yehuda

@Patrick Monsere - Thanks! That indeed seems to solve the problem. Pushing a fix.

Patrick Monsere

Thanks, this works great!
I was having trouble with the colorbar axes being scaled improperly like a few others. I seemed to have corrected it by adding 'CDataMapping','scaled' to the end of line 498, h_tmp = image(lon...
Now the colorbar retains the correct scaling after plotting the map over my data.

Cale Brownstead

Jack Chuang

jayapradeep challa

Hi Zoharby, thanks for this amazing tool can u please help in providing solution to this,
I'm trying to add "Information window with some custom text into it" to the markers, i know that i can add custom window with google static api's but could you help how can i do that using your tool in the matlab - plot and could u help how can i get the zoom-level information....


Muhammad Usman Saleem

I want to plot specific area which is more than my line plot. I do not want to fix axis of my line plot to be the range of my google map. Please tell me how can I adjust region range which I want to show as background in plot?

koray beyaz

Young Ro Lee


I tried to use it with 2011b 32bit and it doens't work. The figure opens and my four gps koordinates are shown, but the map isn't visible. I get the message: 'Matlab error urlwrite (line 140)' and a message that the image can't be downloaded. I tried the same with the 2016 version and it worked perfectly. The problem is, that the system on which i need to use it only has 2011b. Can you help?.

ori barak

Alberto de la Fuente

Philipp Glira

Fan Wang

Tom Magowan

Nikola Markovic


Roger Llaurado

Khanifakhon Rasulova

Zohar Bar-Yehuda

@R C - in which MATLAB version? Did you try it on a new figure, or in one with other data already plotted on?
This warning it thrown if the zoom of the current axis doesn't make sense for plotting the map.


Your example code is throwing this

Warning: Axis limits are not reasonable for WGS1984, ignoring. Please make sure your plotted data in WGS1984 coordinates,
> In plot_google_map (line 234)

David Lehman

Kais Suleiman

Sanghai Guan


Samuel Kekuewa

Overall it is great and very convenient. However I have ran into a few problems recently that other have brought up before. Whenever I plot_google_map it changes my caxis([min max]), my contours are still the appropriate color, but not the caxis displays the incorrect numerical value associated with each contour. Any solution?


A really nice app!
I really like the idea of automatic update the figure while keeping the detail image resolution.
Thank you!

Ugur Keskin

Nice! And also zooming works pretty good. Overall better than expected!


Thank you so much

Yu-Lin Tsai


Mo Ba

Great job!
Any idea how to switch to satelite view?

Carina Sauter

Amazing, so easy to use :) Thank you!

Ayush Choubey

I wanted to add the scale to the map as we get in google maps(not static).
Is there a way to add a scale?

Joseph Ahamioje

AM sorry. this was the code i eventually used but the png file did not come up. only the google map location came up.

lat = (29.581226);
lon = (-98.617149);
export_fig Capture1.PNG

Joseph Ahamioje

i am trying to upload a PV PLANT Circuit and have it draw on google map. i have the coordinates of the place i want to circuit to upload on. i tried this but it only brings out the google map of the location but not the circuit. any tips please?

lat = (29.581226);
lon = (-98.617149);


Thanks Zohar!

Cory Johnson


I really like the function...and used it for creating maps which I now want to use in a student thesis.
Is there anyone who has an idea how to correctly cite the plots?
In wanted to mention it in the text by typing '.....(Google Maps, 2016).'
But what do I have to write in my 'Reference' list?
Something like:

Google Maps (2016). New York - Paris - London. (Created using plot_google_map, Zohar Bar-Yehuda).

- do I have to find out/ mention any URL which might be used in the background?
- do I have to mention Static Google Map API?
- is there any 'location'/ (where and how) do I have to mention that the function is from MATLAB fileExchange?

I hope that someone comes up with a good solution...
Thanks in advance,

I also see taht plot_google_map.m alters my colorbar range .. Pleasecould you suggest why ?

Hi..thats Wonderful. But please could you help me with a small problem.. I need to plot air pollution data (as coloured circles) on top of the map.the colour of the circles should vary based on the concentration and also have a colorbar. Is there some easy way to do this..Many thanks.SSR


great tool! thanks!

adnan ali awan

I keep on getting this error!!!!
>> plot_google_map
Out of memory. The likely cause is an infinite recursion within the program.

Error in newplot>ObserveAxesNextPlot (line 124)
cla(ax, 'reset',hsave);

Shibing Liu



Great work.


muy bueno

Cory Johnson

Evan Kalina

Fahad Furniturewala

I am getting this error and it sets all my points on a fixed axis (like a straight line) and the map doesnt show up.
Error using ==> set
Bad property value found.
Object Name : axes
Property Name : 'YLim'
Values must be increasing and non-NaN.

Can somebody help please?


Good work sir
If user wants to move from one country to other by dragging, it takes time to load.
How to decrease the time delay in loading?
What changes can be done such that the location of countries can be viewed in world map at once?

I am Waiting Sir

Kanishke Gamagedara

Brian Sutton

Peter Mills

Great mapping tool. I would really like to plot a wind rose on the Google map at the location of the recording station. How can I do this?

Shelley Hung


Great tool. I'm using this to plot a trajectory... I am having an issues with grabbing points using the selectdata function on file exchange. Specifically, it will detect several points besides the trajectory plotted onto the google map. Any suggestions on how to get rid of these hidden data points? Thanks

Zohar Bar-Yehuda

@lostreet - can you send me a code sample that illustrates your colors problem?
As far as I know this shouldn't happen.


I am trying to plot a semitransparent contourf on top of the google map. Unfortunately the colors of the contourf plot are changing when added to the google map. Do you have a solution for this problem?

Tuan Nguyen

Seyedfarid Ghahari

How can I see the map in tilted view?

Zohar Bar-Yehuda

@DHRUPAL SHAH - issued a fix for this (in case there are no permissions to temp folder, use the current folder instead). Should solve your problem


Great Use.
Faced a very unethical error for 4 hours of windows user not having access to "Temp" folder.
Solution: Randomly figured our to use matlab as "Run as Admin".

Zohar Bar-Yehuda

@lostreet - pushed a fix for this warning. Download the current version.


I have one more question.

When executing the code I always get this warning:

Warning: Struct field assignment overwrites a value with class "double". See MATLAB R14SP2 Release Notes,
Assigning Nonstructure Variables As Structures Displays Warning, for details.
> In plot_google_map at 180

How do I have to change the code to avoid it?


I found the solution to my problem in the previous answers.

"The easiest way would be to set the zoom level you want manually (using xlim/ylim or the axis command), and then call plot_google_map again to force it to refresh to the current zoom."


Really good tool.

I have the same question as Rezka: Is it possible to zoom automatically in a required area? Thank you for your help


Jasmin McInerney

Hi, having trouble working with contour and contourf, the colours of my contour are being overwritten with blue. In the code below I have tried to move "plot_google_map(...)" down to the end with the same results. Note red x from plot command are staying red. Has anyone worked out how to fix this?

plot(Xs, Ys, 'xr')
plot_google_map('MapType', 'satellite','Alpha', 1)
hold on
contourf(xq, yq, Things)

Kelly Kyriakou

Precious tool!!!!


Really helps. Thanks Zohar.
I want to know which code that i have to modified to zooming the map automatically without tools from the figure options.
Thanks, best regards

Bruno Dias

I think this project is quite interesting.
I've worked on something similar in Google Earth so I would like to clarify some doubts.

Could you tell me what do you do when you "project the data into a uniform WGS1984 grid" and use myTurboInterp2() function?

The resolution varies with the latitude. Could you explain how you make image adjustment to correct this problem?

You use the resolution measured at Equator. Many documentation refers to multiply cos(lat * pi/180) when you determine curResolution.

Thanks, Bruno Dias

Zohar Bar-Yehuda

Pete - update to the latest version of the code. It solves this issue.

Pete sherer

I think it has an issue with v2015a
inputParams.(['ax' num2str(axHandle*1e6,'%.0f')]). It returns error.

Zohar Bar-Yehuda

Marc - thanks for the tip. I'll add it in the next update.

Tim Kaufmann


Hi Zohar,

I have made a very small change that improved speed quiet a bit. I replace data=urlwrite(filename,url) by M=webread(url), using webread that was introduced in R2014b. This avoid the TMP image to be saved in the current folder and therefore to write to the disk. It might be a good idea to update the actual version with it.



Hi Zohar,

The toolbox is awesome and it has helped me a lot. I now would like to use it for another purpose, 3D plotting. Is it possible to plot the map in the xOy plane for example?

The goal is to do a 3D bar plot, with the bars over specific locations.


Zohar Bar-Yehuda

Carine - use:
point = ginput(1);
a click on the map will then return the longitude and latitude of the point.


Hi Zohar,

Thank you for this great toolbox.
I am very new in mapping so I hope my question does make sense: I would need, from the google map, a user to click on a place and receive the coordinates of this place. Is this possible?

Hector Usach

Regarding my last comment, I'm sorry, I didn't realised that the problem I mention (text not clear in the figure) just happens when using a tex interpreter, so it seems more a matlab bug than a problem of this function.

Hector Usach

Zohar Bar-Yehuda

Ron - scale is still there, default is scale=2.

Hector - Not sure I understand your problem. Send me more details and an example to and I'll try to help.

Hector Usach

Works great, but when there is text on the figure, it appears blurred. Actually the ylabel is cut. Any solutions? (Matlab 2012b)

Ron Abileah

Would give it 10 stars if I could. Thank you very much for sharing. An earlier version had the Scale=2 option. This seems to have gone away in the 2014 update. Is there a reason?


Hey thanks for this. Very useful. However when the plot is rotated with the rotate 3D tool, the map disappears. Is there a way to keep it in its position?


Is it possible to have a higher image quality of the map?

Zohar Bar-Yehuda

Wyfi Mcfly - fixed in latest version (used a more elegant solution using 'UserData' field in handle. Please update to latest version.

Wyfi Mcfly

R2014 broken on line 109
fix by casting ax handle to double

inputParams.(['ax' num2str(double(axHandle)*1e6,'%.0f')]) = varargin;


I love you!! (just kidding)

Your script is very, very useful.


Hi this is a great tool and works well for me when I run it normally. I am having issues when trying to run the code through MATLAB publisher. MATLAB hangs and does not publish the plot. Has anyone else encountered this?



Fantastic tool!

Does it work for 3D plots? I tried to use it on a plot generated by plot3 function, but it did not work. Any suggestions?




Great tool!
Starting with Matlab 2014b I got big problems with scattered plots and color-bars. The color-bar stopped fitting to the scattered plot after plot_google_map was executed.
I had to change line 415 to solve the problem:
h = image(lonVect,latVect,uniImag, 'Parent', axHandle,'cdatamapping','scaled');


Jeff Jackson

Ilya Shipachev

Great reinforsment to work with GPS data.


Update from previous rating -- the code was modified to work with 2014b, so I'm changing my previous 4* rating to 5*!


Hello Zohar,
I was wondering if it's possible to download Google Maps and have it on computer and plot the coordinates without having internet?
also is it possible to have the initial plot with a desired zoom level.


Hi Zonar and thank you for you nice submission.
As already users have previously noted, there is an issue when running the code with R2014b, which originates from the fact the every handle is an object and not a double.

You have nicely included a ResizeFcn, which is invoked when the figure is resized.
In the ResizeFcn you use break in the for loop. Can you explain me the reason of doing that?
Because if you have two axes with google maps
subplot(1,2,1); plot_google_map; subplot(1,2,2); plot_google_map;

the ResizeFcn function does not re-plot both maps and you turn up with a bad resolution in one of the two.


This is a helpful piece of code.

Unfortunately, as mentioned below, it breaks with 2014b. I'm having an issue at line 109 (inputParams.(['ax' num2str(axHandle*1e6,'%.0f')]) = varargin;). The error message that I'm getting is: "Undefined function 'mtimes' for input arguments of type ''."


Sunil Dowray

Thanks a lot for your response Zohar.. As you said, for loop is creating the issue in zooming speed.

Zohar Bar-Yehuda

Larry - thanks for the heads up. I'm very busy in the coming weeks, will fix and release a new version as soon as I have some free time.

Sunil Dowray

Sunil Dowray

Hi Zohar, thanks for sharing this wonderful piece of code. I have a query, I'm trying to plot data points which are mapped on to corresponding co-ordinates. The problem is, the number of data points are large (around 15000 - 35000 points). I'm able to plot these data points on the map, but facing issues in zooming/panning speed. The map reaction becomes too slow whenever I try to zoom in or out with the data points on the map. Is there any limitations in the number of points on the map or should I check for any other parameter to overcome this issue.. Thanks


plot_google_map() has broken with R2014b. (No sure about R2014a)

Line 108 gca returns now returns an axes object instead of a double as previously.


Zohar Bar-Yehuda

Pietro - such a feature can be added quite easily.

In the meantime, if you have the mapping toolbox, you can use a few lines of code to achieve this:

load toolbox\map\mapdisp\private\regions.mat worldRegions
axis([worldRegions(pos).lonlim worldRegions(pos).latlim])


Is it possible to provide a string to the function like "Turkey" and getting a map of Turkey?


Zohar Bar-Yehuda

wiwi - there seem to be random errors with some computer IPs.
Try obtaining an API key from Google and setting it, it would probably solve your problem.

If you need more help, feel free to contact me:


Hi Zohar, this code does not work for me. It displays only the lat and long nodes. I have an error "Warning: Unable to download map form Google Servers.\nPossible reasons: no network connection, or quota exceeded (1000
map requests per day).
> In plot_google_map at 186"

I'm using Matlab2014a. Please help me!!! thanks


Interesting - worked just fine on a different computer. Sorry of for the false alarm.

Zohar Bar-Yehuda

Gary - works fine here without a key. Maybe it depends on your IP which is treated differently by Google for some reason.
Anyway, obtaining an API key and setting it is a matter of minutes, and would probably solve your problem.


Did Google just change something that broke this? The code-generated URL states that a API key is required, but the link you provided in get_google_map for obtaining a key says that keys aren't needed anymore.


Great work Zohar. I've one question:
If you use this code:

lat = [48.8708 51.5188 41.9260 40.4312 52.523 37.982];
lon = [2.4131 -0.1300 12.4951 -3.6788 13.415 23.715];

How do the plot_google_map know to use the variables lat and lon?
I've tried with 4 variables:

latR= [1 2 3 4]
lonR = [1 2 3 4]
latG =[1 2 3 4]
long = [1 2 3 4]
hold on, plot(lonR,latR,'.r','MarkerSize',20)
hold on, plot(lonG,latG,'.g','MarkerSize',10)

It works perfectly!! BUT, how do the function plot_google_map know it to take that 4 variables?

Great work, thank you


Hey Nice Work.

If you can add a script save map tiles on the computer it will reduce the requirement of API key. API key will be used only to to download additional maps or when required to update.

Oriol C

GREAT script. What is the relation between the image I see in the figure and the image output of the script? I need to relate latVec and lonVec with the image I obtain from saveas.




Is it possible to get from google maps the position of commercial spots(e.g. restaurants, hotels, etc) in the map?

Zohar Bar-Yehuda

Shatrughan - awesome tip. I will try to integrate it into the script soon.


hello Zohar,

Hope you remember as I pointed out the need to put 'map scale' on the google plots. You said that you will work on it later when you get time. It seems this is still a persistent issue with all users using your anyway 'GREAT' script. However, I have come across another submission on FEX for making scale and very simply I have been using these two scripts for my purpose since long time. Just thought that this might help others and also to you as it might save a bit of your time. :)

Here the link is:

After using plot_google_map
just use makescale

and you are done !!

Happy Matlabbing !!!


Hi Zohar, thanks for your reply. I found this function that it is quite useful, unfortunately I can't control the scale, like 1:20000, but I can get only the distance.

Zohar Bar-Yehuda

pietro - that would be quite tricky, as it also depends on your screen size etc.
I wanted to add a scale indicator at the bottom of the map, but never got to it. Hope to add it sometime...


Great job. Is it possible to control the map scale? By istance generating plots with a map scale of 1:20,000. Thanks


Zohar, I assumed that you knew about OSM tiles since you've displayed an impressibly awesome work with this function! My comment was more of an open thought directed at other members =)

Zohar Bar-Yehuda

Jorge - working with tiles has its upsides (you can choose the resolution you want, possibility for local caching etc.), but will make the code much more complicated and slower to run since it will require several images to be downloaded for every map you want to display.
I don't have plans to get to it in the near future...
I don't plan


Amazing! My only comment is, would it make sense to pull the tiles from OpenStreetMap? For example, OSM tiles stored by MapQuest could be accessed even at 4000 tiles/second!

And are pulled simply like where x and y are easily calculated from the desired coordinates:

This way Google limits could be avoided, given OSM is now a very mature project. I would gladly implement this if I had the time, but I thought that maybe anyone else here is annoyed by Google and could use the idea =)

Zohar Bar-Yehuda

Hi David,

The easiest way would be to set the zoom level you want manually (using xlim/ylim or the axis command), and then call plot_google_map again to force it to refresh to the current zoom.


Great code! I can't figure out how to zoom in to a specific location. Using the comand zoom(15) will not zoom on my GPS point.

Is there any way to set the ylim and xlim of the graph (using those commands the map does not refresh)? I'm trying to use it in a loop to visualize my bicycle ride (needs to be pretty zoomed in)

David Radin

Update to my comment below:

Realized the error was due to a bad coordinate reference - if coordinates do not fit on global plane, well, errors happen.

David Radin

Zohar -
First of all, great function, great utility.

Wondering if you could comment on an error that suddenly appeared. The script was running perfectly but today I started it up and now it is not. I receive the following error:

Error using set
Bad property value found.
Object Name : axes
Property Name : 'YLim'
Values must be increasing and non-NaN.

Error in axis>LocSetLimits (line 206)

Error in axis (line 94)

Error in plot_google_map (line 250)
axis(curAxis) % update axis as quickly as possible, before downloading new image

Error in test (line 11)
plot_google_map('APIKey','**key hidden**')

Appreciate your time!


Thanks for your quick feedback. In the meantime, I found a solution, I had "'PaperPositionMode','auto'" to the figure properties in addition of "'visible','off'" and it works pretty well and this allow to gain a lot f computing time.

Zohar Bar-Yehuda

OK, turns out the previous comment didn't get through...
Anyway, Xavier - the problem is caused because plot_google_map set a custom figure resize callback to change the zoom if the figure is resized and changes its aspect ratio.
You can disable it by commenting out line 434 which sets the figure resize callback:
set(figHandle, 'ResizeFcn', @update_google_map_fig);

Zohar Bar-Yehuda

Hey, sorry my mistake, that flag was only in some local version I had here.
To resolve your problem comment out line 434:
set(figHandle, 'ResizeFcn', @update_google_map_fig);


First thanks a lot for this script which is very useful.
I got a question where I did not find a solution myself. I use this script into a loop where each iteration represents a trip. I save the figure into png file. I would like to the figure does not appear. I used figure('Visible','off') but figures appear at the saveas command (found out though debug mode) but not if plot_google_map command is removed. I looked at line 379 and so on but without finding a solution. Do you have an idea?


Zohar Bar-Yehuda

Hi Jason,

From you error, it seems you are using a very old version of MATLAB, in which the syntax of the zoom command is different.
You can make it work by disabling all the functionality involving the auto refresh feature. Comment out lines 421-429.
This should make it work for you, but you'll need to call plot_google_map again if you want the map to refresh after you zoom in or out.

Jason Oh

This is my error message below ;

??? Output argument "out" (and maybe others) not assigned during call to "C:\Program Files (x86)\MATLAB71\toolbox\matlab\graph2d\zoom.m (zoom)".

Error in ==> zoom at 81
if nargin==2 && ...

Error in ==> plot_google_map at 421
zoomHandle = zoom;

Do you know why I got this message?


Thank you for developing this Zohar. I can use it for a project I am working on. Is it possible to add area measurements tool to this map? If yes, how?
Thank You!!


Just figured out: After rendering with set(gcf,'renderer','opengl'), even saveas(gcf, 'out.jpg') works.


Hi Zohar,

thank you a lot for your support! I tried your suggestion and with the rendering setting of set(gcf,'renderer','zbuffer'), the background (map) + transparent settings vanished again.

set(gcf,'renderer','opengl') and exporting with export_fig.m though works for me :)

Best Regards

Zohar Bar-Yehuda

Hi Clemens,

I've updated the Known Issues section, hopefully addressing your problem. Hope this helps:

2) Saving the map with an image/matrix overlay drawn on top of it (especially a semi-transparent one) can sometimes cause unexpected results (map not showing etc.). If you're encountering such problems, it's recommended to use the export_fig submission:
The combination that seems to work best:


Works perfectly for me. I have only the issue already raised by Larry, that if I export my figure to a picture, the map is missing. Do others also have troubles with that or any workaround except screenshots?


Hi Zohar,

I've the same message as Larry. When I post URL given in example in a Web browser (Firefox with no proxy configured), I can see the staticmap of Google Maps.
I've not problems with my quotas and I've really loaded the last version.
Can you give me some help on what it happens ?

Thanks. Regards.


Kudos to you, Its really nice, working fine for me...I tried it with two points.
I really wanted to ask one thing, How can we extract the latitude longitude points between two points as in between the source and the destination, Do we have to enter it manually or do we require some coding for the same.

Zohar Bar-Yehuda

Larry, are you sure you're using the latest version?
If yes, you can try putting a breakpoint at line 316 - urlwrite(url,filename);
copy the url to your browser and see if it works there.
Anyway, if you need more help feel free to contact me:


For couple of days plot_google_map can't be used, in both my computer and my colleague's. It kept showing:

Warning: Unable to download map form Google Servers.
Possible reasons: no network connection, or quota exceeded.
Consider using an API key if quota problems persist.
> In plot_google_map at 318

My quota is not a problem. I also have tried to use the API key but to no avail. Any idea?



Great script. It shows little error for me showing:zoom error. It shows red marker first, then only the map not the red makers.One or more output arguments not assigned during call to 'D:\MATLAB7\toolbox\matlab\graph2d\zoom.m (zoom)'.
Error in ==> plot_google_map at 402
zoomHandle = zoom;
Error in ==> test at 16
Please help how to make it run?

Zohar Bar-Yehuda

Naveed - v3 is only for the javascript API. This code uses the Static Maps API which still uses v2.

If you already have the heatmap data as a matrix, you can simply plot it with IMAGE and give an AlphaData matrix with values <1 to make it semi transperent.
If you have point data, you'll first need to convert it to a heatmap matrix. I need to do it myself for a project in the coming weeks. If I don't find an existing solution I'll probably create one and hopefully submit it to the FEX.


Hey, thanks for this great code! Just what I needed. Quick question: are you planning on upgrading this to the v3 of google maps API? Also, could you recommend how to add a heat map layer to the rendered map?

Zohar Bar-Yehuda

Gabriel - there shouldn't be any recursion in this code. Please send me an example how to reproduce the error.


I was able to do a plot once or twice, but now I am reaching max. recursion limit all the time. Any help?

Zohar Bar-Yehuda

Konstantinos - Simply call plot_google_map after plotting the route. It should display the map in the background of the route.


Great job, and really helpful. I' m trying to plot a certain route on the map which is in a gpx file, which i created from google maps. I use the gpxread function to read the file , I can display the route on a seperate window, but i don't know how to display the route on the map. Does anyone have any idea?


Hello Zohar!
With your new code and after cheking mine It seems that the map isn't stretched (also when you remove "axis equal" ....). Many Thanks

Zohar Bar-Yehuda

Alexandre - I think what you mean is that the map is stretched in one axis, which shouldn't happen with the new version.
If you're having the same problem with the new version, please send me an example code to reproduce the problem.


Nice job, very useful, many thanks. But I exactly have the same question as Chad Greene (Mar 2012). Does anyone know how to get the image in overhead view instead of 60° inclinaison? Thanks

Preetham Manjunatha

Really good one! I was planning to make a GPS tracker for my project, I found exactly what I am looking for. But needs quite a bit of work to make this for realtime tracking or for post-processing.

me sale este error a que se debe : Output argument "varargout" (and maybe others) not assigned during call to "E:\plot_google_map.m>plot_google_map".

Giacomo Alessandroni


Thanks, Seb. It is a wonderful tool.

Seb Biass

My mistake, had an old version, updated one works like a charm!


It seems to be incompatible with pcolor. Matlab can plot with both pcolor and plot_google_map, but when the plot is saved as an image (as any format such as png), the background google map is gone.

Seb Biass

Hi there,
Does anyone has any problem with that script recently? It was running smoothly until today.
??? Error using ==> imread at 387
Unable to determine the file format.

Error in ==> plot_google_map at 189
[M Mcolor] = imread(filename);


Zohar Bar-Yehuda

Amit, with the new scale=2 param which is used by default, you actually get a 1280x1280 image, which gives a much nicer rendering (though responds somewhat slower...)



Hi Amit,

the 640*640 limit is set by the google API. see for more information


Good work there Zohar Bar-Yehuda. And very helpful for my work, thank you.
Though I wonder why is the image size limited to 640X640. It would be very helpful to have this limitation removed. Perhaps a good idea to have the image sized in proportion to screen size. Screen size can be obtained from

Thanks again.

Sebastian Holmqvist

From what I've gathered, Google switched from counting usage per domain to per user instead. So basically if you use Static Maps on your website, a single user using up all of the quota won't affect any other users, only that particular user.

Other than that, great piece of software! It was easy to get compatible with older Matlab (2003) and works like a charm under Matlab R2008b.

As for future requests, caching (i.e renaming and not removing) tiles would be awesome! I realize that storing tiles might violate Google's terms, but temporary would certainly do the trick!

Zohar Bar-Yehuda

Kart - I think there is a problem with the API key mode. It seems like Google ignores it since the requests have no referrer field in the HTTP header. Will try investigating it for a solution.



I tried it with my own API key

but Iam getting the warning quota exceeded. what should i do?

Zohar Bar-Yehuda

Scale is a great idea, and quite easy to implement. I'll try adding it when I have some time.


Great script !! simple and easy to use..however, I have a question, how to put map scale on the plot? also if you could add direction symbol (North/South) would be great..any response will be appreciated..

Zohar Bar-Yehuda

Just noticed they changed the API and introduced the API key again.
It doesn't say what's the limit if you don't use any key, but from a quick test it looks like it's 400 per day (per IP I guess).

If you do get your own key, you can use up to 25,000 requests per day. I'll try to upload a new version soon with an easy way to put your own key.

Zohar Bar-Yehuda

Hi Marco,

This function uses Google's Static Maps API, and is therefore perfectly legal. It's also limited to 1000 map requests per day as specified in the API. See:


Have anyone considered possible legal issues in this application?
As far as i know, it's forbidden the access to the maps through the direct creation of the url.
The access is legal only through the api's google offers (such as javascript).

In case you have different informations please let us know!


Mint Sauce



Very nice.


Hey, great function!

I was wondering one thing. I have to plot a wind map over the ocean, close to the coast. Therefore I would like to get the coastline on the top, and the land just represented as a grey or black surface on top of my contour plot. Is it possible to get the land of the googlemap background on top of my countour plot?

Chad Greene

Ah, there's an easy fix: simply add "axis equal" after the plotting command.

Chad Greene

This is unbelievably easy to install and use!

Only one question: it seems to be plotting the 45° angle view, whether I choose roadmap, terrain, or satellite. Any ideas of how to get the overhead image?

Erdal Bizkevelci


Great work. This works a treat, Thanks!


Hi there zohar,

Hope you are fine,
actually i have a power plot of an antenna radiation level at ground level which spread over some 300 meters. now what i want to do is placing the power plot on a specific region on google earth so that i can see how the power plot is in the region where the antenna is, can you help me?

Michael Wengler

Outstanding, easy to use, elegant!

Zohar Bar-Yehuda

Seb - I am converting the PNG map downloaded (when using roadmap) to a truecolor image to prevent problems with conflicting colormaps, so I don't really know why you're having problems.

Maybe you can send me an example code you use, and I will check it out.

Seb Biass

Wow, that is cool, thanks!
Question: I am using a contourf plot and adding the map behind. So I set the colormap and the transparency for the contourf, but all colors change when I plot the background map. Any idea where that could come from?


Aaron Holtzman

danish zubairi

made my life easier


Jan Vidar

MATLAB Release Compatibility
Created with R2009b
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!