Java Script – Picking up coordinates of point in Google Maps

Three weeks ago I have started to read an outstanding book for the Google API. So far I have finished it and this is the third review of code I have done, based on the book. The previous two concern Maps Synchronization and Animation of a line. Thus, this is the third one and probably the last one. This is the book:

8825OT_Google Maps API Cookbook

In the current article I will show a simple piece of code, enabling you to click on a google map and be able to get information about the point you have clicked. Pretty much, it looks like this:

coordinates


Here, you may find how the code works 🙂

So, let’s start exploring it – what do we need to make “the magic” working?

First we need to define some variables – map and infowindow. The infowindow variable is set to null:

Then we create the function initMap(), where we actually do the magic. The function is called at the end of the script with the following lines:

What do we do in the fuction? Mainly four things.

  • We set the starting options of the map – in my case it is somewhere in Bulgaria, with a zoom of 6 and roadmap type. (line 22 to 26 from the code)
  • The at line 29 we set the mapElement to get element by ID ‘mapDiv’ and mapDiv is the one in the <body> of the HTML.
  • At line 32 we set the variable map – it creates a map object, getting as variables MapElement and MapOtpions.
  • The last thing is the part, helping us to build the window upon the click. Lines 34 to 43 take care of this. We can easily see the condition in the statement, asking the window to close, if it is already open. Then we see the usage of the pre-built InfoWindow from the Google API.

Pretty much this is how the script works. Four points where you should be careful. Last, but not least, if you are using Google Maps API, you should make your own account in code.google.com to get your own API Key. This is needed, because there are limits for the free usage of google. The limits are quite high (something like 20 K), but still, it is better to use your own! The API key is put in the place of the code, where I write PUT_YOUR_OWN_KEY_HERE.

Here is the code:

Enjoy the code and use it responsibly! 🙂

Tagged with: , , , ,