Using Google Maps from a Windows Client application


The other day I blogged about mashing up $g(Google Maps) and VCL in a Delphi Win32 application with support for bi-directional VCL-> JavaScript and JavaScript-> VCL allowing for rich interaction with the map. The first part of this “conversation” is actually very easy to accomplish. Here is what you need to do if you want to give it a try. I’ll talk about this from the Delphi perspective though the same logic will work from C# or any other language that can host the $g(Microsoft WebBrowser control).

  1. Start a new VCL application
  2. Drop a TWebBrowser control
  3. Create a Form1.OnCreate event handler
  4. Add the following line of code:
    WebBrowser1.Navigate(
      'http://www.stevetrefethen.com/files/googlemap.htm');
  5. Add a TButton to the form and an OnClick event handler and add the following code:
procedure TForm1.Button1Click(Sender: TObject);
var
  Doc2: IHTMLDocument2;
begin
  with WebBrowser1.Document as IHTMLDocument2 do
    with parentWindow do
      execScript('createMapMarker("31.05173494",
        "-122.03160858", "test")', 'JavaScript');
end;

This will create a new marker on the map in Scotts Valley, CA. In fact, you can execute any method of the Google Map object by replacing the first parameter in execScript (above) with something like this:

map.panTo(new GLatLng(37.05173492, -122.031608568));

Hopefully, you can see the possibilities this creates. To get it working on your own domain you’ll need to do the following:

  1. Get yourself $g(GMail account) if you don’t already have one
  2. Get a $g(Google Maps API key) you’ll need a domain where you can upload files to
  3. Right click and save this file to disk
  4. Edit the file you just download and change the API to use your key (mine won’t work on your domain)
  5. Change the .Navigate call to use your URL

That’s it, you can now interact with Google maps from a Windows client application (VCL in this case). As you can see mashups aren’t strictly the domain of web only applications. In a subsequent post I’ll talk about how to interact with the hosting application from the JavaScript on the page for true two way interaction.

[UPDATE: April 2, 2008] Related posts:

|||
|

20 thoughts on “Using Google Maps from a Windows Client application

  1. Hey Steve,
    Thanks for the tutorial.
    In Portugal we say:

    "Give a fish and the person will always come back, give a fishing cane and the person never will bother you again"

    (roughly translated). That’s the kind of tutorial I like, you gave me the fishing cane !!
    This concludes we all asking for the code on your mashup post doesn’t it ?
    Cheers,
    Gustavo Carreno

  2. Hi Gustavo,
    Thanks for the kind words I’m glad you found this useful. The part I haven’t discussed is calling back into the VCL code from Javascript. That’s pretty significant because it means you can put markup in the browser (links, buttons etc.) and have them execute VCL code. It’s more involved to do in a generic fashion but very useful I think.

  3. Hey Steve,
    I’ve seen some of the callback code embedded on the FeedDemon html Newspaper and I really wanted to replicate that !!
    I’ll be, eagerly, waiting to read your next post about the callbacks !!
    Cheers,
    Gustavo Carreno

  4. Idioma = Português
    Olá
    Estou utilizando o delphi7 e está dando a seguinte mensagem de erro:
    Undeclared Identifier ‘IHTMLDocument2’
    var
    Doc2: IHTMLDocument2;
    Qual o prblema ?

  5. Jose Ricardo:
    adicione nos seus USES: MSHTML
    😉
    ah e comigo tb nao aparece nenhum marcador 🙁
    (translation: i get no map marker either 🙁 )

  6. PT and others,
    My first suggestion would be to ensure that you have the latest version of MSHTML. For more information about importing that type library refer to <a href="PT and others,
    My first suggestion would be to ensure that you have the latest version of MSHTML. For more information about importing that type library refer to this post." title="Importing mshtml type library>this post</a>.
    My second point would be that this post was written using the shipping build of Delphi at the time not Delphi 7 as is mentioned here. Delphi 7 is now many, many years old and lots has changed WRT the RTL, compiler and VCL. I did not attempt to test this code with earlier versions of Delphi.

  7. Hi Steven,
    Congratulations!
    I never thought I could do this, even more using Delphi 5.
    I only had to change "external.Caption = ‘Hello from Javascript’;" from CreateMapMarker function to "marker.openInfoWindow(html);".
    The only thing is when I tried to put and use "googlemap.ashx" from my page it didn’t load.
    Know nothing about "ashx". My page is a free domain from googlepages.
    http://sorocabaemmapas.googlepages.com
    Can I do anything?
    Thanks.

  8. Furlani,
    Congrats! I’m glad you got it working. The issue with the .ashx file is that that’s ASP.NET which is not supported on googlepages.com. You need to either change that page accordingly or host it from a provider that supports ASP.NET.

  9. Hey Steve,
    Thank you for your reply.
    I’ll think later about another way to load map without using .ashx as for now I’m focused on implementing some new functions on googlemap.htm file. As soon as I have something consistent I’ll tell you.
    Now I want to invite you to visit the page, using Google Maps API, I created for the city, Sorocaba, I was born and live. As my language is portuguese (Brazil) I’ll try to help you understand.
    The site presents several thematic maps (as for public state schools, university schools, public sports buildings, hospitals and healthy care, government places, etc). If you go to the first link called "Meu Local" ("My Place") on main page, you can define and "Gravar" ("Save") a place that will be used as the Start point for a "Trajeto" ("route") on all thematic maps.
    The cool thing is that all thematic maps are loaded from the same HTML. Map title, theme field and legend items are obtained, together with data for the markers, from a XML passe as parameter.
    The last link on main page is my last work, a moving marker that I used to ilustrate the 4 different circuits stablished for a bike meeting that occurred last sunday (03/02) here in Sorocaba.
    Click Here for my page
    Cheers
    Furlani

  10. Hey Steve,
    this tutorial is extremely interesting!!
    i am trying to do a similar thing in C++: basically i’ve created a 3D reproduction of my college and i would like to show the position of the user on an external map (google maps would be brilliant!!!!).
    the only problem is that i don’t have a clue how to do it!
    any chance i can use your tutorial in C++? would the code and the procedure be different?
    any help would be more than appreciated! 🙂
    Francesco

  11. Hi Steve,
    I’m back!
    I implemented several functions on google.htm code and successfully got rid of .ashx.
    I’ve created a Delphi project too and you can download it’s source HERE to try the new functions.
    Bye.

  12. Olá…
    Alguém já fez o caminho inverso, ou seja, o usuário clicar num marcador no mapa e o mapa enviar alguma informaçao para a aplicação que o abriu (feita em Delphi, no meu caso) ou essa aplicação ‘capturar’ alguma informação do mapa e localizar um registro num Dataset???
    Abraços
    Jair

  13. Olá Furlani eu vi que você desenvolveu uma pequena aplicação em Delhi para a API do Google Maps, estou tenando fazer a mesma coisa você pode me disponibilizar o código fonte dela para ler e aprender como faz?
    Desde já agradeço, se puder envie para o meu e-mail: alexandre@brim.com.br
    Obrigado.

  14. Hi Alexandre,
    There isn’t any additional source code involved here other than the D2007 RTL/VCL and what you see in the single ButtonClick event above. If you’re using a version prior to D2007 it’s possible you may have problems. As I’m no longer working in Delphi I won’t be revisiting these examples. I’d suggest looking at Marco Cantu’s blog as well as he has done some similar things.
    Good luck.

  15. Hello Steve this is swapnil from india.
    actually I have use Google Maps in my asp.net application in which I used to create the map using the following code.
    map=new GMap2(document.getElementById (‘mymap’));
    geocoder = new GClientGeocoder();
    var zoomlevel = document.all.MapZoom.value;
    map.setCenter(new GLatLng(document.all.MapLat.value,document.all.MapLong.value),parseInt(zoomlevel));
    map.addControl(new GSmallMapControl());
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    GEvent.addListener(map, "click",onMapClick);
    map.enableScrollWheelZoom();
    Now the requirement is changed I have to give the user a Windows desktop application in which he is able to see the map on some Button click. And Moreover I have get the latitude and longitude from the map point where he will click .And I am searching for it But found nothing till now. After this article I think theres a possibility that this would work. Can you please tell me wht are the necessary steps I have to follow.One thing is I am using .net 2005 and C# is the language I am using.Thanks IN ADV. Takecare 🙂

  16. wrote the very same code in delphi 6 pro :
    I can direct the browser to lots of web sites but not to your page ???
    very frustrated 😉
    Any idea ?
    thanks anyway for the quality of your work!!
    JPaul

Comments are closed.