Developing Web Application with Google Map API
Image by Telendro via Flickr
Setup API Key
In order to be able to utilize Google Map API for our web application, we need to get the API Key. It can be obtained for free from Google website. This Key will be valid for one URL only, so each time we move the application to another server, we need to obtain a new key for that server URL.
The Key can be obtained from this URL:
http://www.google.com/apis/maps/signup.html
Then, a page similar to the following will appear:
Next, to get a key for your URL:
- Enter your URL website, the URL your web application using Google Map API will reside, at the My web site URL column, for example http://localhost/gmaptest. Note: You need to get an API key for each URL for your application.
- Click the Generate API Key button. Save the key which will be in the form berupa XXX encrypted character. This Key will be used at the initialization step of the Google Map at your application which will be valid for the URL you register.
Start Creating Application with Google Map
Create a new HTML file, say test-01.html. Type the following code on that file:
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script src="http://maps.google.com/maps?file=api&amp;amp;v=2&amp;amp;key=abc"
type="text/javascript"></script>
<script type="text/javascript">
//CDATA[
var map = null;
function load()
{
if (GBrowserIsCompatible())
{
map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(-6.8790, 107.63520), 12);
}
}
//]]>
</script>
</head>
<body onload="load()" onunload="GUnload()">
<div id="map" style="width: 400px; height: 200px">Loading</div>
</body>
</html>
The above code was actually just a standard HTML code with Javascript.
All function that is needed to access and manipulate Google Map is stored online at Google server and can only be retrieved when we already have the key for the URL where the file is located. This is done at line 6. You need to modify the key=abc code, change abc to be you key obtained at the registration step at Google Map. If the key is not correct the the access to the Google Map functions will failed.
There is a Javascript function called load() which will be invoked at the time the HTML page was completely downloaded by the browser.
This load() function is used to initialize the Google Map:
- At line 15, checking whether the browser can display Google Map or not. If it does then contunui to the next initialization process. The Function GbrowserIsCompatible() is used for this purpose, and is a part of the Google Map API.
- At line 17, we define an object variable called map which will represent the Google Map class, the GMap2(). This Object was initialized to use a DIV element that later will contain the map provided by Google Map. This is done with the parameter used at the javascript function document.getElementById(”map”). That means that we should have a DIV element called map later.
At line 18 setCenter() method of the map object variable is invoked. This Method is used to determine the center point for the map display. It’s parameter are the coordinate of the center point and the zoom level. The center point coordinate was previously defined using the GLatLon() object that have two parameter latitude and longitude of the coordinate. The zoom level is an integer value that determine how deep the zoom level is for the map display. In this case we use level 12.
At line 25 we can see the definition of the HTML BODY tag that will call the javascript function load() that has already defined before.
At line 26 there is the definition of HTML DIV tag called map which will be used by the Google Map object to display the map. We can modify the size by changing the width and height of the style attribute. The most important thing here is that the id attribute must be the same as the one called at the initialization of the Google Map object at line 17 above.
When everything was correct, then you will see something like this when the above file is opened in a browser window.
Centering a map at a coordinate
To move the center point of the Google Map we can call the method setCenter(). The parameter for the method are the new coordinate we want as the new center point and the new zoom level.
The center point coordinate must be an object of type GLatLng that can be created easily using the GLatLng() object. As in the previous example, the parameter for this GLatLng() object are the coordinate in lattitude and longitude. The return value of this object can be stored in a variable of type GLatLng. The Object variable of this type can be used directly as the parameter for the setCenter() method.
The next parameter of setCenter() method is the integer value of zoom level . This parameter determined how deep the map will be displayed. The bigger the value the the deeper the map will be displayed. This value starts from 0 (display the earth) to 19 (detailed road map level).
For example:
[js]
var point = new GLatLng(-6.8790, 107.63520);
map = new GMap2(document.getElementById(”map”));
map.setCenter(point, 12);
[/js]
Adding Marker
Marker is a symbol or icon that can be placed on top of Google Map. An external image file or a deafult icon provided by Google Map can be used for the icon.
To put a marker on top of Google Map, we need to create an object variable of type GMarker.
The Parameter for that GMarker() function was the coordinate where the marker will be plotted. This Parameter must be in type of GLatLng that can be created by GLatLng() as we have done before.
After the Marker object was successfully created, the the object is used as a parameter of the map Google Map addOverlay() method. This Method will show a marker icon at the coordinate specified.
As an example, create a new file called test-02.html like the following.
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=abc">
</script>
<script type="text/javascript">
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(-6.8790, 107.63520), 13);
var point = new GLatLng(-6.8790, 107.63520);
map.addOverlay(new GMarker(point));
}
}
</script>
</head>
<body onload="load()" onunload="GUnload()" style="font-family: Arial;border: 0 none;">
<div id="map" style="width: 500px; height: 300px"></div>
</body>
</html>
When everything was correct, then you will see something like this when the above file is opened in a browser window.
Adding Marker with Information Box
A Marker can be displayed with an information box that usually contains the detailed information about the marker. This can be done by calling the openInfoWindowHtml() method of the map object when defined.
The Paremeter for this method is the description to be displayed at the box in HTML code.
As an example, create a new file called test-03.html like the following.
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script src=http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=abc>
</script>
<script type="text/javascript">
function load() {
if (GBrowserIsCompatible())
{
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(-6.8790, 107.63520), 13);
var point = new GLatLng(-6.8790, 107.63520);
map.addOverlay(new GMarker(point));
map.openInfoWindow(map.getCenter(),
document.createTextNode("halo aku disini"));
}
}
</script>
</head>
<body onload="load()" onunload="GUnload()" style="font-family: Arial;border: 0 none;">
<div id="map" style="width: 500px; height: 300px"></div>
</body>
</html>
When everything was correct, then you will see something like this when the above file is opened in a browser window.
Memilih Jenis Map
Google Map has several type of map defined by calling the setMapType() method:
- G_NORMAL_MAP This map type (which is the default) displays a normal street map.
- G_SATELLITE_MAP This map type displays satellite images. All places in this earth has been captured by satellite and can be accessed through Google Map. But several places are still in low resolution while other places are already in high resolution.
- G_HYBRID_MAP This map type displays a transparent layer of major streets on satellite images.
- G_DEFAULT_MAP_TYPES An array of the first three predefined map types described above (G_NORMAL_MAP, G_SATELLITE_MAP, and G_HYBRID_MAP).
- G_PHYSICAL_MAP This map type displays maps with physical features such as terrain and vegetation. This map type is not displayed within map type controls by default.
One thing that we must consider is that the calling of thus method must be done after the calling of setCenter() or zoom() method.
As an examlpe, create a new file calles test-05.html with the following source code.
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=abc">
</script>
<script type="text/javascript">
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(-6.8790, 107.63520), 13);
map.setMapType(G_SATELLITE_MAP);
}
}
</script>
</head>
<body onload="load()" onunload="GUnload()" style="font-family: Arial;border: 0 none;">
<div id="map" style="width: 500px; height: 300px"></div>
</body>
</html>
We can change the line 19 change it to the type of G_NORMAL_MAP, G_SATELITTE_TYPE_MAP or G_HYBRID_MAP. For the type of G_NORMAL_MAP, for some places if we zoom too deep we will not see any information. This is because Google Map still does not have the requested map for that area.
Below is an example of map with hybrid type.
Adding Markers from Data
Marker can be added to Google Map dinamically from a data source, for example in case we have a data file containing coordinate of markers to be displayed on top of Google Map.
For that purpose we need to call the GDownloadUrl() function used to download the data from an URL of a file containing XML data. The XML data received will be parsed by Google Map GXml object. This Object has a method parse() that can be used to do the XML data parsing.
After the parsing, we will get the XML data ready to be processed further.
For example, create a new file called test-06.html with the following source code.
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=abc"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var map = null;
function load()
{
if (GBrowserIsCompatible())
{
map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(-6.8790, 107.63520), 9);
map.setMapType(G_HYBRID_TYPE);
GDownloadUrl("data.xml", function(data, responseCode) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var point = new GLatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
map.addOverlay(new GMarker(point));
}
});
}
}
//]]>
</script>
</head>
<body onload="load()" onunload="GUnload()">
<div id="map" style="width: 400px; height: 200px">Loading</div>
</body>
</html>
At line 21, we run GDownloadUrl() function. This function has two parameter, the URL of the file to be downloaded, in this case data.xml and the function to handle the data and the responseCode received after downloading the data. Both of the data are already defined and can be consumed as the parameter of that handler function so they can be processed inside the function.
At line 22 we call the parse() method of the GXml object. The result of the parsing of the XML is stored in the xml variable which is an object that has an XML data structure and is ready to be read by other process. This process is, for example, easily searching for a key and value of an element.
At line 23, we read an XML element called marker. This Element must be exists on the XML data downloaded before, which was the data.xml. The result of the reading is stored on an array called markers. This is a simple javascript array in which the elements can be easily counted with the length property, or accessed by index, for example to access the first element we will use the notation markers[0].
At line 24, we do a loop beginning from 0 to the size of the element of markers array. For each iteration of the loop, we create an object called point of type GLatLng with the coordinate of lattitude and longitude taken from the XML data. That information is obtained from markers array element by calling the getAttribute() method. The Attribute we read for each element are lat and lng attribut. The parseFloat() function us used to convert string data to float data needed to create an object of type GLatLng.
At line 28, after the point object is created, then it is used as a parameter for creating a new object of GMarker. This GMarker object is then used as a parameter for addOverlay() method of the Google Map’s map object. This will cause Google Map displays a new marker at the coordinate specified by point object.
After the iteration is done (the size of the markers array elements count), the at line 30 we call setCenter() method of map object to set the center point of out Google Map display.
Below is the example of the above data.xml used for the process:
<marker lat="-6.20" lng="107.40" />
<marker lat="-6.32" lng="107.51" />
<marker lat="-6.25" lng="107.60" />
<marker lat="-6.36" lng="107.66" />
</markers>
When everything was correct, then you will see something like this when the above file is opened in a browser window.
Moving the Markers
Sometimes we need to move the position of an existing marker. By the time of this writing, Google Map does not provide this facility yet for example marker.move() or map.moveMarker().
For this purpose, we need to do the following step:
- deleting all existing markers by using clearOverlays() method of Google Map map object.
- creating new markers that replace the previously deleted markers so we will get an effect of markers movement from one coordinate to another
Below is an example source code of markers movement.
var marker = new GMarker(map.getCenter());
map.addOverlay(marker);
We have discussed the basics of programming web application using Google Map API. See you on the next article about creating GPS tracking application using Google Map API.
Refferences:
- Google Map API Documentation: http://code.google.com/apis/maps/documentation/introduction.html
- Google Map API Playground: http://code.google.com/apis/ajax/playground
Akhmad Daniel Sembiring
vITraining.com – Qualified IT Products, Outsourcing, and Services
Ligarwangi.com – Linux, E-book, Coffee, Gift, etc
![Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_e.png?x-id=bfbe0adf-c3a6-460a-b09f-729ed3a7bf39)




Recent Comments