Add Interactive Map to your website using Google Maps API

Interactive maps has become an inevitable part of modern web applications and introduction of Google Map API has made it even easier to integrate an interactive map to your website. Areas on which interactive maps have proved itself are tourism related websites and service oriented websites. In this blog we will see how we can add an interactive map to your website using Google Map API and AJAX to process the response from the server.

The first step in integrating a map in your website is to request  a Google map API key. You can request  a Google Maps API key here. If you have URL for your website, you need to specify the URL while requesting key. If you are playing around with the API, you can very well request for http://localhost. If you are using a port number , you need to specify the port number also. For example http://localhost:8080. Once you get the key you can use the key for all subfolders of http://localhost.

This is Source of an HTML page that displays map of 1415 Elbridge Payne Rd,Chesterfield,MO 63017. You need to know the latitude and longitude of the address to display map in your web page. If you don’t know the latitude and longitude , there are many online services that provide services to get latitude and longitude of an address . Another way of implementing this is to use geoCoder provided by Google Map API to get the latitude and longitude by providing an address. We will come to this in a while.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
<html xmlns=”“>
    <meta http-equiv=”content-type” content=”text/html;
    <title>Google Maps JavaScript API Example</title>
    <script  src=”
         ABQIAAAAR7yXyXxWnmYNsvbV6JWv5hT2yXp_ZAY8_ufC3CFXhHIE1NvwkxTvGi-   GhomVbgkbC6tv2C8JocyNEg”
    <script type=”text/javascript”>
    function load() {
      if (GBrowserIsCompatible()) {
     var map = new GMap2(document.getElementById(“map”));
     map.setCenter(new GLatLng(38.65, -90.56), 8);
     map.addControl(new GSmallMapControl());
     map.addControl(new GOverviewMapControl());
     var point = new GLatLng(38.65, -90.56);
     marker = new GMarker(point);
     GEvent.addListener(marker, “click”, function() {
     marker.openInfoWindowHtml(“<p>Unidev: Custom Software and Applicaton Development</p>”});

  <body onload=”load()”>
    <div id=”map” style=”width: 800px; height: 600px”></div>

Map of Unidev

Class GMap2 represents a map instance and you can create as many instances as you want. addcontrol() method can be used to add controls to your map.GSmallMapControl() enables Zoom functionality. Event handling is implemented using GEvent.addListener() method. GMarker class marks a point of interest in your map.OpenInfoWindowHtml() method opens an informational window on ‘OnClick’ event. Place holder for map in this example is a <div> tag with id ‘map’.
Adding an Interactive Map to your web application:
This example shows how to add a user driven map in your web application. First step in creating an interactive map is to have a form in your web page where users can enter the address and description of their point of interest.
Given below is the bean and DAO implementation class.
public class GMarker
    private Long id;
    private String address;
    private String description;
// Need to have setters , getters and a costructor that takes all the varaibales)

We have another Location object that stores data entered by users. We read data from the Location table(which is populated by the data submitted by users) and create Gmarker object. This DAO implementation is not Table  driven , we read hardcoded data from a Map. In realworld DAO Implmentation would be Table driven.

DAO implementation:
public class PickDAOImpl implements PickDAO
private static final Map myPicks = new HashMap();
    static {
    myPicks.put(“1″,new GMarker(new Long(1),”1415 Elbridge Payne  Rd,Chesterfield,MO,63017″,”Unidev: Custom Software and Application Development”));
    myPicks.put(“2″,new GMarker(new Long(2),”1400 Douglas Street,Omaha,NE”,”Union Pacific Railroad”));
 public List findAllAsMarkers() {
        List results = new ArrayList();
        Collection allLocations = myPicks.values();
        Iterator locIt = allLocations.iterator();
        GMarker location = null;
            location = (GMarker);
            results.add(new GMarker(location.getId(),
   return results;

Heart of Ajax is XMLHttpRequest object and however in this example we are using Google’s version of XMLHttpRequest object, that is GXmlHttp class. Ajax makes the request to the servlet, which would be processed by the servlet  and Servlet returned XML Document object can be processed by Javascript DOM functions. We are using Xsteam implementation provided by to generate XML document from Java object. Other open source libraries like Apache and Castor can also be used to generate XML document from Java objects.

XML document generated by the servlet for the request to get all user submitted addresses in the database would look like this.
    <address>1400 Douglas Street,Omaha,NE</address>
    <description>Union Pacific Railroad</description>
    <address>1415 Elbridge Payne Rd,Chesterfield,MO,63017</address>
    <description>Unidev: Custom Software and Application Development</description>

Given below is the Servlet that generated the above XML document.

public class MyPickServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet
    private PickDAO pickDAO;
    public PickDAO getPickDAO()
        if (pickDAO == null) {pickDAO = new PickDAOImpl();
       return pickDAO;

    public void setPickDAO(PickDAO pickDAO)
        this.pickDAO = pickDAO;
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws  ServletException, IOException {
        String method=request.getParameter(“method”);
        XStream xstream = new XStream();
        xstream.alias(“marker”, GMarker.class);
 if (method.equals(“findAll”)) {
            List locations = getPickDAO().findAllAsMarkers();
            String xml = xstream.toXML(locations);

The response generated by the Servlet is processed by javascript DOM functions. Given below is the HML page, that makes AJAX request to Server and process the response from the Server. The Javascript code has comments added to explain the important points.

 <meta http-equiv=”content-type” content=”text/html; charset=utf-8″ />
  <title>Google Maps JavaScript API Example</title>
  <script type=”text/javascript”>
     var map = null;
         var gmarkers = [];
         var i =0;
         var address = null;
         var geocoder = null;
        var id = null;
      // method called on onLoad event
    function loadUserPicks() {
   map = new GMap2(document.getElementById(“map”));
         var request = GXmlHttp.create();“GET”, “myPick?method=findAll”, true);
         request.onreadystatechange = getCallbackFunction(request, processGmapData);
    function getCallbackFunction(req, processData) {
          // Return an function that listens to the
          // XMLHttpRequest instance
              return function () {
         // If the request status is “complete”
           if (req.readyState == 4) {
             if (req.status == 200) {
                  // Got a response
                  // Pass the XML payload of the response to the
                  // handler function
 } else {
          // An HTTP problem has occurred
          alert(“HTTP error: “+req.status);
  var locMarkers = null;

function processGmapData(xmlDoc){
             // obtain the array of markers and loop through it
             locMarkers = xmlDoc.documentElement.getElementsByTagName(“marker”);

    function displayPicks() {
            for (var i = 0; i < locMarkers.length; i++) {
              // obtain the attribues of each marker
              var label = locMarkers[i].getElementsByTagName(“address”)[0].firstChild.nodeValue;
              address = label;
              map = new GMap2(document.getElementById(“map”));

            // Create new geocoding client object
          geocoder = new GClientGeocoder();

           // Retrieve location information for the address, pass it to addToMap()
           geocoder.getLocations(address, addToMap); }
    function addToMap(response)
            // Retrieve the object
           var place = response.Placemark[0];
           // Retrieve the latitude and longitude
           var point = new GLatLng(place.Point.coordinates[1],
          // Center the map on this point
          map.setCenter(new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]),4);
          map.addControl(new GSmallMapControl());
          map.addControl(new GOverviewMapControl());
         var marker = new GMarker(point);
        GEvent.addListener(marker,”mouseover”, function() {
              marker.openInfoWindowHtml(place.address + ‘<br>’+'<b>Country:</b>’

           gmarkers[i] = marker;
  <form name=”mypickform” action=”/myPick” method=”get”>
  <body onload=”loadUserPicks()”>
  <div id=”map” style=”width: 800px; height: 600px”></div>



3 Responses to “Add Interactive Map to your website using Google Maps API”

  • seo:

    this site is good

  • i am not able to show more than ten markers to my gmap

    please advice
    i used same as urs

  • Hi,

    I work in a hospital in Dublin, Ireland and I am trying to design an Interactive Google Map for patients who want to visit the hospital

    I have signed up for an API key…

    I am just wondering what is the best steps to go about designing this map and would you have any map samples or code samples…

    Basically I would want the map to load, and to have an extra button added to the already “Map”, “Satellite” and “Hybrid”, the extra button being my map called SJH.

    I would need a search function and then on the left, names of locations that users can select, and when they select the location they want, the marker would appear on the map of where that place is located.

    I also have images for each location..

    Any help would be greatly appreciated..

Leave a Reply