Generating static map images using Google Map API

If you are using static map images on your website and have a lot of different addresses to be displayed, you can easily automate the process of creating them. The code below will request Google map API and download static images. The address list is stored in .csv file but can also be pulled directly from database. Once map images are created, you can recreate them with different params again.

There is a limit for generating static images without api key, so make sure you wait a bit when getting forbidden error from Google request.

SW1A-0AA


public static string rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        public static string csvPath = rootPath + "\\Addresses.csv";
        public static Random rnd = new Random();
 
        public static void Main()
        {
            using (var sr = new StreamReader(csvPath))
            {
                while (!sr.EndOfStream)
                {
                    var data = sr.ReadLine().Split('|');
                    var address = data[0];
                    var postCode = data[1];
 
                    SaveFile(address, postCode);
                }
            }
 
            Console.WriteLine("done!");
            Console.ReadLine();
        }
 
        public static void SaveFile(string address, string postCode)
        {
            try
            {
                var filePath = new DirectoryInfo(rootPath).Parent.Parent.Parent.FullName + @"\output\" + postCode + ".jpg";
                if (File.Exists(filePath))
                {
                    Console.WriteLine("skipped " + address + " " + postCode + " (image exists in output directory)"); return;
                }
 
                Console.WriteLine("processing " + address + " " + postCode);
 
                using (var wc = new WebClient())
                {
                    var url = "https://maps.google.com/maps/api/staticmap?address=" + address + "&center=" + postCode + "&size=275x275&format=jpg&maptype=roadmap&zoom=15.5&markers=color:0xE21A9B|label:T|" + postCode + "&sensor=false";
                    wc.DownloadFile(url, new DirectoryInfo(rootPath).Parent.Parent.Parent.FullName + @"\output\" + postCode + ".jpg");
                }
 
                Thread.Sleep(rnd.Next(300, 2300)); //wait a bit
            }
            catch (Exception ex)
            {
                Console.WriteLine("error for: " + address + " | " + postCode + Environment.NewLine + ex.Message);
            }
        }
    }

Download project: googleImageApi

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...