|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Services
Chapters
Feature Zones
|
Note: This is an unedited contribution. If this article is inappropriate,
needs attention or copies someone else's work without reference then please
Report This Article
IntroductionThis article will guide you with a bit of knowledge about use of javascript, and more precisely will enable you to use Google Maps to your webpage with ease. Google brought web services that anyone can connect to and use their services without any cost. Well, there is some restriction to the use of gmap. They have two versions of maps, one for standard purpose which will come for free, and another one is Google map Enterprise Solution. Well Simply if you want to add a google map to your website and which can be seen from anywhere outside, means can be accessible to just using a link, you dont need to pay google for using their API. But if you want to restrict access to maps behind a valid login, then you need to pay google. I am using simple HTML page for adding up gmap. And later on I will use others also to make the gmap look very lively. The only thing that you need in case of using gmap to your application is an google acount. You can sign up for an account for free. Just go here. You could signup for an account for free, and then you can use google maps to your website by clicking on "Create an account now". After you create an account just use your userid and password to login when required. BackgroundFor using Google Maps in your website the thing you need is a bit of knowledge of javascript, means how to call a function from web controls. I will describe everything, but you need to catch up all those. Using the CodeI am creating an HTML page for implementing this project. You can use any projects to implement maps dynamically using any server side languages. EXAMPLE 1://Use of Gmap in your web page // <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "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"/> <title>My Locations</title> <script src="http://maps.google.com/maps?file=api&v=2& key=ABQIAAAAcl" type="text/javascript"></script> <script type="text/javascript"> function load() { if (GBrowserIsCompatible()) { var point; var map=new GMap2(document.getElementById("map")); map.addControl(new GOverviewMapControl()); map.enableDoubleClickZoom(); map.enableScrollWheelZoom(); map.addControl(new GMapTypeControl()); map.addControl(new GSmallMapControl()); var address='<img src="myimage.gif" width=150 height=40/><br/>' + <font size="2" face="Arial"><b>INDIA</b><br/><br/>Home.<br/>' + New York City<br/><br/>America<br/>Ph.: 23743823</font>'; var marker = new GMarker(point); map.setCenter(point,17); map.addOverlay(marker); map.setMapType(G_HYBRID_MAP); GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(address);}); marker.openInfoWindowHtml(address); } } </script> <body onload="load();" onunload="GUnload()" style=" background-color:Transparent"> <div id="map" style="width: 900px; height: 500px"></div> </body> </html> Coming to the code, first in your webpage you need to add one <div id="map" style="width: 900px; height: 500px"></div> Now I have called a javascript function when body loads, thus, in my sample application, as soon as the page comes to your browser, you will see a gmap loaded. So I have created a javascript load function which will be called as soon as I open the webpage. Now during the page load, we have added a dynamic javascript file which will be dependent on webhost. The line... <script src="http://maps.google.com/maps?file=api&v=2& key=ABQIAAAAcl" type="text/javascript"></script> ...adds up a file from Google. This is essential, because that file will create the entire map for you. Just one thing that you need is to generate an API KEY for your web host. Be it local host, use http://localhost to it. Just click below and get the key. You will get a key from here, just replace the key in the key attribute of the javascript line. After you do that, I have used GBrowserIsCompatible(), its a function which will return true only if your browser is compatible with gmap. The next line will load the gmap control to the div control. GMap2 function takes the control to load and returns a map object which can be referenced later on. Next map.addControl(new GOverviewMapControl()); will add a new control to the map, called GOverviewMapControl
it will be an overview of the map just in the right hand bottom corner to the map. I can add more controls through addControl Function. I have used GSmallMapControl()
The enableDoubleClickZoom and enableScrollWheelZoom will enable those features simply to your map. After that, I have placed a marker to my application. Markers are images that can be placed over the map to point a location. To place a marker you need a latitude and longitude which should be passed throught GLatLng() function to get a valid point. I have also made an html that could be shown to the map. I have let a var address to store the html. Later on I have created a marker into the map using those latitude and longitude. The GMarker will create one marker and addOverlay() will add the marker in the form. The GEvent.addListener will add one listener to the map through which the map respond. I have added a click event listener to my map, so that when one clicks on the map, it will show the InfoWindow of the marker. openInfoWindowHtml() will open the info window html for me. Thats all. You have created a simple map and added to your html page. Take a look at the snapshot: EXAMPLE 2:Now let us make it more advanced adding polylines to it. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "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> <title>Untitled Page</title> <script src="http://maps.google.com/maps?file=api&v=2& key=ABQIA" type="text/javascript"></script> <script type="text/javascript"> function loadEarth(mapdiv) { if (GBrowserIsCompatible()) { var point; if(!mapdiv)return true; var map=new GMap2(document.getElementById("map")); map.addControl(new GOverviewMapControl()); map.enableDoubleClickZoom(); map.enableScrollWheelZoom(); map.addControl(new GMapTypeControl()); map.addControl(new GSmallMapControl()); var marker = new GMarker(new GLatLng(37.4419,-122.1419)); map.setCenter(new GLatLng(37.4419,-122.1419),17); GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml("hii");}); map.addOverlay(marker); map.setCenter(new GLatLng(37.4419, -122.1419), 16); map.setMapType(G_SATELLITE_MAP); var polyline = new GPolyline([new GLatLng(37.4419, -122.1419), new GLatLng(37.4519, -122.1519), new GLatLng( 37.4619, -122.1819)], "#3333cc", 10); } map.addOverlay(polyline); } </script> </head> <body onload="loadEarth('map')" onunload="GUnload()" style=" background-color:Transparent"> <div id="map" style="width: 500px; height: 300px"></div> </body> </html> In the above example I have taken 3 points just after creation of markers and drawn polyline over those points. GPolyline() will create a polyline object using an array of points, with a specific color, here I have taken the color using hexadecimal code and the width, which is 10 here. After that I have used addOverlay function to add the polyline to our actual map. Remember to add the vml namespace in case of using polylines. DTD will be similar to what shown above. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "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"> Otherwise the polyline will not be shown to your map. Take a look at the snapshot: EXAMPLE 3:In my next example I would use Geocoder functionality to my map, so that you could search any address from a search textbox, and the geocoder will search those address for you. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "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"/> <title>Coder Page</title> <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAA" type="text/javascript"></script> <script language="'Javascript'" type='text/javascript'> var map = null; var geocoder = null; function load() { if (GBrowserIsCompatible()) { map = new GMap2(document.getElementById("map")); map.setCenter(new GLatLng(37.4419, -122.1419), 13); geocoder = new GClientGeocoder(); } } function showAddress(address) { if (geocoder) { geocoder.getLatLng( address, function(point) { if (!point) { alert(address + " not found"); } else { map.setCenter(point, 17); var marker = new GMarker(point); map.addOverlay(marker); marker.openInfoWindowHtml(address); } } ); } } </script> </head> <body onload="load()" onunload="GUnload()"> <input type="text" size="60" name="address" id="addr" value="India" /> <input type="button" value="Go!" onclick="showAddress(document.getElementById("addr").value); return false"/> </p> <div id="map" style="width: 500px; height: 300px"></div> </body> </html> In the above example I have added another function that will enable us to call any address and the address will be replaced with a point in terms of latitude and longitude. The GClientGeocoder() will return a geocode object to the client browser which could be later used to get a point from any text address. Google have approximated this search will take 1.73 seconds for each geocode call. So its not that much slow. Now for searching an address I have created a button and a textbox, which will be used to get address from the user. The showaddress function will take one address from the user and create a marker just into that location, and open the infowindow of that marker. If no points are found, it returns an alert. So on clicking the button it will call the showaddress function, and it will show the location. Look at the SnapShot of what we built so far: Example 3Well, In my next Updation, I am adding an example that can demonstrate the use of gmap in a better way. I am adding context menu. See the code first: var map = null;
var geocoder = null;
var contextmenu;
function load(loc) {
if (GBrowserIsCompatible()) {
var point;
map=new GMap2(document.getElementById("map"));
map.addControl(new GOverviewMapControl());
map.enableDoubleClickZoom();
map.enableScrollWheelZoom();
map.addControl(new GMapTypeControl());
map.addControl(new GLargeMapControl());
createContextMenu(map);
var address='<font size="2" face="Arial"><b>INDIA</b><br/>
<br/>XYZ Inc.<br/>New York City <br/>
America<br/>Ph.: 343254543</font>';
point = new GLatLng(22.592057,88.421815);
var marker = new GMarker(point);
map.setCenter(point,17);
map.addOverlay(marker);
map.setMapType(G_HYBRID_MAP);
GEvent.addListener(marker,
"click", function() {marker.openInfoWindowHtml(address);});
marker.openInfoWindowHtml(address);
}
}
function createContextMenu(map)
{
contextmenu = document.createElement("div");
contextmenu.style.visibility="hidden";
contextmenu.style.background="#ffffff";
contextmenu.style.border="1px solid #8888FF";
contextmenu.innerHTML = '<a href="javascript:zoomIn()">
<div class="context"> Zoom in </div></a>'
+ '<a href="javascript:zoomOut()">
<div class="context"> Zoom out </div></a>'
+ '<a href="javascript:zoomInHere()">
<div class="context"> Zoom in here </div></a>'
+ '<a href="javascript:zoomOutHere()">
<div class="context"> Zoom out here </div></a>'
+ '<a href="javascript:centreMapHere()">
<div class="context"> Centre map here </div></a>';
map.getContainer().appendChild(contextmenu);
GEvent.addListener(map,"singlerightclick",function(pixel,tile)
{
clickedPixel = pixel;
var x=pixel.x;
var y=pixel.y;
if (x > map.getSize().width - 120)
{
x = map.getSize().width - 120
}
if (y > map.getSize().height - 100)
{
y = map.getSize().height - 100
}
var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));
pos.apply(contextmenu);
contextmenu.style.visibility = "visible";
});
GEvent.addListener(map, "click", function()
{
contextmenu.style.visibility="hidden";
});
}
function zoomIn()
{
map.zoomIn();
contextmenu.style.visibility="hidden";
}
function zoomOut()
{
map.zoomOut();
contextmenu.style.visibility="hidden";
}
function zoomInHere()
{
var point = map.fromContainerPixelToLatLng(clickedPixel)
map.zoomIn(point,true);
contextmenu.style.visibility="hidden";
}
function zoomOutHere()
{
var point = map.fromContainerPixelToLatLng(clickedPixel)
map.setCenter(point,map.getZoom()-1);
contextmenu.style.visibility="hidden";
}
function centreMapHere()
{
var point = map.fromContainerPixelToLatLng(clickedPixel)
map.setCenter(point);
contextmenu.style.visibility="hidden";
}
In this example I have added a custom div control when the user right clicks anywhere in the map. The event that should be registered when user right clicks the map is Check the snapshot: Example 4Well in this example I will give you idea about how to create tabbed info window and also an option to maximize the infowindow so that you can show a webpage within it. Just take a look at the code below: var map = null;
var geocoder = null;
function load(loc) {
if (GBrowserIsCompatible()) {
var point;
var map=new GMap2(document.getElementById("map"));
map.addControl(new GOverviewMapControl());
map.enableDoubleClickZoom();
map.enableScrollWheelZoom();
map.addControl(new GMapTypeControl());
map.addControl(new GSmallMapControl());
var address='<font size="2" face="Arial"><b>INDIA</b><br/><br/>
XYZ Inc.<br/>New York City <br/>America<br/>Ph.: 343254543</font>';
point = new GLatLng(22.592057,88.421815);
var marker = new GMarker(point);
map.setCenter(point,17);
map.addOverlay(marker);
map.setMapType(G_HYBRID_MAP);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowTabsHtml(
[new GInfoWindowTab("BASIC",address),
new GInfoWindowTab("Advanced","<b>Dont forget to click on
<br/>Maximize button on this window with + sign</b>")],
{maxUrl:"http://abhishek.sur.googlepages.com"});
});
}
}
Well, you can see the line GEvent.addListener where instead of calling openInfoWindow we are calling openInfoWindowTabsHtml. This function will enable us to create a tabbed window. The arguments are array of Tabs that could be found from GInfoWindowTab, which takes two arguments, first one is header, and the second is the content in html. The second argument of openInfoWindowTabsHtml is options, where I have used maxUrl option, which will create a maximize button on the window. I can use this option in normal markers too. Now lets look at the snapshots: This window is showing the tabbed window with two tabs,1. Basic and 2. Advanced. When You click on the + button just beside the Close button, It will open an html window within the gmap. See the snapshot: Example 5In this demo I will be using a new event handler called Dragend and moveend handler. Take a look at the simple code : <script type="text/javascript"> function load() { if (GBrowserIsCompatible()) { var map = new GMap2(document.getElementById("map")); map.addControl (new GSmallMapControl()); map.addControl(new GMapTypeControl()); var center = new GLatLng(-22.98699983834975, -43.210344314575195); map.setCenter(center, 11); map.setMapType(G_SATELLITE_MAP); geocoder = new GClientGeocoder(); var marker = new GMarker(center, {draggable: true}); map.addOverlay(marker); document.getElementById("lat").value = center.lat(); document.getElementById("lng").value = center.lng (); geocoder = new GClientGeocoder(); GEvent.addListener(marker, "dragend", function() { var point =marker.getPoint(); map.panTo(point); document.getElementById("lat").value = point.lat(); document.getElementById("lng").value = point.lng(); }); GEvent.addListener(map, "moveend", function() { map.clearOverlays(); var center = map.getCenter(); var marker = new GMarker(center, {draggable: true}); map.addOverlay(marker); document.getElementById ("lat").value = center.lat(); document.getElementById("lng").value = center.lng(); GEvent.addListener(marker, "dragend", function() { var point =marker.getPoint(); map.panTo(point); document.getElementById("lat").value = point.lat(); document.getElementById("lng").value = point.lng(); }); }); } } function showAddress(address) { var map = new GMap2(document.getElementById("map")); map.addControl(new GSmallMapControl()); map.addControl(new GMapTypeControl()); if (geocoder) { geocoder.getLatLng ( address, function(point) { if (!point) { alert(address + " city not found !"); } else { document.getElementById("lat").value = point.lat(); document.getElementById("lng").value = point.lng(); map.clearOverlays() map.setCenter(point, 14); var marker = new GMarker(point, {draggable: true}); map.addOverlay(marker); GEvent.addListener(marker, "dragend", function() { var pt =marker.getPoint(); map.panTo(pt); document.getElementById("lat").value = pt.lat(); document.getElementById("lng").value = pt.lng(); }); GEvent.addListener(map, "moveend", function() { map.clearOverlays(); var center = map.getCenter(); var marker = new GMarker(center, {draggable: true}); map.addOverlay(marker); document.getElementById ("lat").value = center.lat(); document.getElementById("lng").value = center.lng(); GEvent.addListener(marker, "dragend", function() { var pt =marker.getPoint(); map.panTo(pt); document.getElementById("lat").value = pt.lat(); document.getElementById("lng").value = pt.lng(); }); }); }} ); }} </script> In this example when the use drags the map, it will automatically place coordinates to the form text boxes called lat and lng. To do this, I have made an overlay marker, and then retrieved the point using getPoint() function. This is a simple example .. Just a demo. I have also included the geocoder, so that one can also search for a location. EXAMPLE 6In this example you will be using MarkerManager and Sidebar to display marker links. The Marker Manager of Google is used to manage large number of markers. See the example below. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Google Maps</title> <script src="http://maps.google.com/maps?file=api&v=2& key=ABQIAAAAclK0B2lXQwV5lPy1rLiTFBSN1aiKepvDswXjKa4j2DDWdYvOjh QMO1tywqS8ObgP5dtO70AyyArhzA" type="text/javascript"></script> </head> <body onunload="GUnload()"> <!-- you can use tables or divs for the overall layout --> <table border=1> <tr> <td> <div id="map" style="width: 550px; height: 450px"></div> </td> <td width = 150 valign="top" style="text-decoration: underline; color: #4444ff;"> <div id="side_bar"></div> </td> </tr> </table> <script type="text/javascript"> //<![CDATA[ if (GBrowserIsCompatible()) { // this variable will collect the html which will eventually be placed // in the side_bar var side_bar_html = ""; // arrays to hold copies of the markers and html used by the side_bar // because the function closure trick doesnt work there var gmarkers = []; var i = 0; var lastlinkid; // A function to create the marker and set up the event window function createMarker(point,name,html) { var marker = new GMarker(point); var linkid = "link"+i; GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(html); document.getElementById(linkid).style.background="#ffff00"; lastlinkid=linkid; }); // save the info we need to use later for the side_bar gmarkers[i] = marker; // add a line to the side_bar html side_bar_html += '<div id="'+linkid+'"><a href="javascript:Linkclicked(' + i + ')">' + name + '</a><br></div>'; i++; return marker; } // This function picks up the click and opens the corresponding info window function Linkclicked(i) { GEvent.trigger(gmarkers[i], "click"); } // create the map var map = new GMap2(document.getElementById("map")); map.addControl(new GLargeMapControl()); map.addControl(new GMapTypeControl()); map.setCenter(new GLatLng( 43.907787,-79.359741), 8); var mm = new GMarkerManager(map); // add the points var point = new GLatLng(43.65654,-79.90138); var marker = createMarker(point,"This place","This is The First Info") var point = new GLatLng(43.91892,-78.89231); var marker = createMarker(point,"That place","This is The Second Info") var point = new GLatLng(43.82589,-78.89231); var marker = createMarker(point,"The other place","This is The Third Info") GEvent.addListener(map,"infowindowclose", function() { document.getElementById(lastlinkid).style.background="#ffffff"; }); mm.addMarkers(gmarkers,0,17); mm.refresh(); // put the assembled side_bar_html contents into the side_bar div document.getElementById("side_bar").innerHTML = side_bar_html; } else { alert("Sorry, the Google Maps API is not compatible with this browser"); } //]]> </script> </body> </html> Here I have placed one marker manager and an array. I have put all the markers to the markermanager so that it can be refreshed deleted or added later. The links are created using the array and is properly mapped with correct marker. Check out the link EXAMPLE 7It is a common problem of making background color of a info window to be changed to a custom color. General sense, you can make the background of one div to a color, but it will not change the extreme boundaries of the info window. So I have extended Tom Morgans Marker to create a marker that looks entirely different from the markers in common. Take a look at the example: To use Tom Morgans Marker just download this javascript from here : Click here Here is the code below: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "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"/> <title>Google Maps</title> <script src="http://maps.google.com/maps?file=api&v=2& key=ABQIAAAAclK0B2lXQwV5lPy1rLiTFBSN1aiKepvDswXjKa4j2DDWdYvOjhQMO1tywqS 8ObgP5dtO70AyyArhzA" type="text/javascript"></script> <script src="tlabel.2.05.js" type="text/javascript"></script> </head> <body onunload="GUnload()"> <div id="map" style="width: 550px; height: 450px"></div> <script type="text/javascript"> //<![CDATA[ if (GBrowserIsCompatible()) { var openbubble=true; var agent = navigator.userAgent.toLowerCase(); // For IE We need to Do this if ((agent.indexOf("msie") > -1) && (agent.indexOf("opera") < 1)){ var loader = "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader( src='gmarker.png', sizingMethod='crop');"; icon = '<div style="height:34px; width:20px; ' +loader+ '" ></div>' } var n=0; function createTLabel(point,html) { var label = new TLabel(); label.id = 'Label '+n; label.anchorLatLng = point; label.anchorPoint = 'bottomCenter'; label.content = html; label.markerOffset = new GSize(-1,-5); map.addTLabel(label); var obj=document.getElementById(label.id); GEvent.addDomListener(obj, "click", function() { //map.openInfoWindowHtml(point, html, {pixelOffset: new GSize(0,-34)} ); }); n++; } var map = new GMap2(document.getElementById("map")); map.addControl(new GLargeMapControl()); map.addControl(new GMapTypeControl()); map.setCenter(new GLatLng(43.907787,-79.359741),8); // Creating the HTML to show markers var hContent = '<div style="padding: 0px 0px 13px 0px; background: url( images/pt_bot_ctr_ora.png) no-repeat bottom center;"> <div style="text-align: center; background-color: #f2c30c; padding: 2px; font-size: 0.75em; font-weight: bold;" onclick="openInfo(\'hInfo\')">MyInfo </div>'; hContent+='<div id="hInfo" style="position: absolute; display: none;">'; hContent+='<div style="width: 81px; background-color: #000; padding: 3px; font-size: 0.75em; color: #fff; text-align: left; border: 1px solid #f2c30c;"> This is my content</div>'; hContent+='</div></div>'; createTLabel(new GLatLng(43.65654,-79.90138),hContent); } else { alert("Sorry, the Google Maps API is not compatible with this browser"); } function openInfo(d) { var obj = document.getElementById(d); if(openbubble==true) { obj.style.display="block"; openbubble=false; } else { obj.style.display="none"; openbubble=true; } } //]]> </script> </body> </html> You can use Gmarker array to store the lebels for future reference, and also you can add one event to the map so that each open marker hides through a loop. Example 8:In this example I am giving you a brief Idea of XML http Request and Drawing GPolygons. First of all look at the example and Code Below. I am explaining them after that. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "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" /> <title>Polygon Demo</title> <script src="http://maps.google.com/maps?file=api&v=2& key=ABQIAAAAclK0B2lXQwV5lPy1rL" type="text/javascript"></script> <script type="text/javascript"> var map = null; var polys = []; var labels = []; var xmlDoc=null; function load() { if (GBrowserIsCompatible()) { var point; map = new GMap2(document.getElementById("map")); map.addControl(new GLargeMapControl()); map.addControl(new GMapTypeControl()); map.setCenter(new GLatLng(42.16,-100.72),4); // Read the data from states.xml var request = GXmlHttp.create(); request.open("GET", "states.xml", true); request.onreadystatechange = function() { if (request.readyState == 4) { xmlDoc = GXml.parse(request.responseText); var states = xmlDoc.documentElement.getElementsByTagName("state"); // read each line for (var a = 0; a < states.length; a++) { // get any state attributes var label = states[a].getAttribute("name"); var colour = states[a].getAttribute("colour"); // read each point on that line var points = states[a].getElementsByTagName("point"); var stateoptions = document.getElementById("xmlStates"); var optn = document.createElement("OPTION"); optn.text = states[a].getAttribute("name"); optn.value = states[a].getAttribute("name"); stateoptions.options.add(optn); } } } request.send(null); } else { alert("Sorry, the Google Maps API is not compatible with this browser"); } } function loadselectedpoint() { if(xmlDoc==null){alert('null');return;} var state = document.getElementById("xmlStates").value; var states = xmlDoc.documentElement.getElementsByTagName("state"); for (var a = 0; a < states.length; a++) { var label = states[a].getAttribute("name"); var colour = states[a].getAttribute("colour"); var points = states[a].getElementsByTagName("point"); if(states[a].getAttribute("name")==state) { var pts = []; for (var i = 0; i < points.length; i++) { pts[i] = new GLatLng(parseFloat(points[i].getAttribute("lat")), parseFloat(points[i].getAttribute("lng"))); } var poly = new GPolygon(pts,"#000000",1,1,colour,0.5,{clickable:true}); GEvent.addListener(poly,'click',function(point) { map.openInfoWindowHtml(point, "Polygon is clicked!!") }); polys.push(poly); map.clearOverlays(); map.addOverlay(poly); } } } //]]> </script> </head> <body onload="load();" onunload="GUnload()" style="background-color: Transparent"> States : <select id="xmlStates" onchange="loadselectedpoint()"> </select> <br /><br /> <div id="map" style="width: 900px; height: 500px"> </div> </body> </html> In the above code, I have made one Select box, where all the States loads, upon selecting one state, it will display the entire boundary of the state. Please take a look at the demo below: In the example above,I have used two new classes: 1. GXmlHttp : This class is the primary AJAX calling Class which creates an XMLHttpRequest Object and places Asynchronous server calls. I have used this class to load the points from an external Xml File which is asynchronously called and downloaded from the server. I have used this file to load the markings and also to load the Select Control. The OnReadyStateChanged is an event for any XMLHttpRequest object that is triggered when state is changed to the object. The Readystate evaluates to 4 when the last call made is successful, and the response is transmitted to the responseText property. 2. GXml : Its a class provided by Google that enables you to parse XML in your application. I have used this class to manage the XML data that comes through AJAX calls. 3. GPolygon : This class is used to make an overlay to the map. The constructor takes 7 arguments. The first argument is for an array of points, which are the GLatlng combinations. The second argument is the Color for Boundaries, 3rd for weight of border, 4th is color of border, 5th is the opacity of the border, 6th is fill color, and 7 th is the opacity of the fill color. You can also produce click event for the Polygon. Points to RememberThe points that you should always remember:
HistoryI have created lots more. Just shared the basics with you all. If you need any further help, contact me at abhi2434@yahoo.com. I dont have gave you any download link for the codes used in the article, its simply because, codes will not run on your browser unless you create a valid api key. Just copy and place code to a notepad, generate your api key, replace it in your javascript,and get your application run. Also you need to run the files from any web hosts, because api keys will validate your host. So place your html client inside IIS or any web server, and use localhost to run it. In my this updated I have added another feature to show custom context menu. Just check the last example for that. Thank you for reading about my application.
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||