Powered by Blogger.

Tuesday, August 17, 2010

Adding Markers to a Map Using the Google Maps API and jQuery

The Google Maps API provides a sophisticated way for developers and webmasters to add custom interactive maps to their websites. Version 3 of the API, released in May of 2009, represents a complete overhaul of the API in response to several years worth of user feedback on the previous version.
In this tutorial we’ll cover a few of the API’s simpler features by showing you how to add a map with a set of location markers to a website. Each marker will have an associated info bubble with the name and address of the location. What’s more, we’ll be loading the location data via Ajax, so this can be used as the first step towards developing a more sophisticated map-based application.

For example, if your site’s contact page shows the position of all your retail locations on a map, you could filter them dynamically (say, based on which ones offered certain features or were open on a given day) by sending those parameters to the server and displaying markers on the map based on the returned XML.
Before we start, you should have at least a basic understanding of jQuery. To learn more about any of the classes and methods we’ll be using, you can consult the Google Maps API reference.
In this tutorial we’re going to create:
  • an HTML file called markers.html, which will be used to display the map and markers
  • an XML file called markers.xml, which contains data enclosed in name, address, lat, and lng tags
  • a JavaScript file called markers.js, where we’ll put the code to load in the data and create the map
You can download the complete source code here to follow along.

Data Format

Before we start writing code, it’s best to examine the format of the XML data we’ll be using to load our location data.
The coordinates and information for each marker we want to place on our map will be contained in an XML file. This makes it easy to change it, or have it generated automatically by a server-side script pulling the information from a database. The XML is formatted as follows:
<?xml version="1.0"?>
<markers>
  <marker>
    <name>VODAFONE</name>
    <address>near Ghumaghumalu Restaurant, Marripalem, Visakhapatnam</address>
    <lat>17.74033553</lat>
    <lng>83.25067267</lng>
  </marker>
  <marker>
  <name>VODAFONE</name>
    <address>near Viswa Teja School, Thatichetlapalem, Visakhapatnam</address>
    <lat>17.73254774</lat>
    <lng>83.29195094</lng>
  </marker>
  &#8942;
</markers>
The root element is markers, and it contains a series of marker elements, each containing a text address, latitude, and longitude.
Before we can load this XML and use it to place markers on our map, we first need to include the Google Maps JavaScript and the jQuery library in our HTML page.

jQuery and the Maps API

The two libraries we’ll be relying on for our functionality are, unsurprisingly, jQuery and the Google Maps API library itself. As far as jQuery is concerned, you can simply download the latest version from the jQuery home page and include it in your HTML page as follows:
<script type="text/javascript" src="js/jquery-1.4.1.min.js"></script>
For the Google Maps code, we can link directly to the Google servers:
The sensor=false parameter specifies that we don’t want to use a sensor (like a GPS locator) to determine the user’s location.
Now that we have our basic libraries, we can start building our functionality.

Outlining the Script

Let’s start with the skeleton of our map code:
var MYMAP = {
  bounds: null,
  map: null
}
MYMAP.init = function(latLng, selector) {
  ⋮
}
MYMAP.placeMarkers = function(filename) {
  ⋮
}
We’re packaging all our map functionality inside a JavaScript object called MYMAP, which will help to avoid potential conflicts with other scripts on the page. The object contains two variables and two functions. The map variable will store a reference to the Google Map object we’ll create, and the bounds variable will store a bounding box that contains all our markers. This will be useful after we’ve added all the markers, when we want to zoom the map in such a way that they’re all visible at the same time.
Now for the methods: init will find an element on the page and initialize it as a new Google map with a given center and zoom level. placeMarkers, meanwhile, takes the name of an XML file and will load in coordinate data from that file to place a series of markers on the map.

Loading the Map

Now that we have the basic structure in place, let’s write our init function:
MYMAP.init = function(selector, latLng, zoom) {
  var myOptions = {
    zoom:zoom,
    center: latLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  this.map = new google.maps.Map($(selector)[0], myOptions);
  this.bounds = new google.maps.LatLngBounds();
}
We create an object literal to contain a set of options, using the parameters passed in to the method. Then we initialize two objects defined in the Google Maps API—a Map and a LatLngBounds—and assign them to the properties of our MYMAP object that we set up earlier for this purpose.
The Map constructor is passed a DOM element to use as the map on the page, as well as a set of options. The options we’ve prepared already, but to retrieve the DOM element we need to take the selector string passed in, and use the jQuery $ function to find the item on the page. Because $ returns a jQuery object rather than a raw DOM node, we need to drill down using [0]: this allows us to access the “naked” DOM node.
So once this function has run, we’ll have our map displayed on the page, and have an empty bounding box, ready to be expanded as we add our markers.

Adding the Markers

Speaking of which, let’s have a look at the placeMarkers function:
MYMAP.placeMarkers = function(filename) {
  $.get(filename, function(xml){
    $(xml).find("marker").each(function(){
      var name = $(this).find('name').text();
      var address = $(this).find('address').text();
      
      // create a new LatLng point for the marker
      var lat = $(this).find('lat').text();
      var lng = $(this).find('lng').text();
      var point = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
      
      // extend the bounds to include the new point
      MYMAP.bounds.extend(point);

      // add the marker itself
      var marker = new google.maps.Marker({
        position: point,
        map: MYMAP.map
      });

      // create the tooltip and its text
      var infoWindow = new google.maps.InfoWindow();
      var html=''+name+'
'+address;

      // add a listener to open the tooltip when a user clicks on one of the markers
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(MYMAP.map, marker);
      });
    });
    
    // Fit the map around the markers we added:
    MYMAP.map.fitBounds(MYMAP.bounds);
  });
}
This function is a little more complicated, but it’s easy to make sense of. First we call jQuery’s $.get method to execute an Ajax GET request. The method takes two parameters: the URL to request (in this case, our local XML file), and a callback function to execute when the request concludes. That function, in turn, will be passed the response to the request, which in this case will be our XML.
jQuery treats XML exactly the same as HTML, so we can use $(xml).find('marker’).each( … ) to loop over each marker element in the response XML and create a marker on the map for each one.

We grab the name and address of the markers, then we create a new LatLng object for each one, which we assign to a point variable. We extend the bounding box to include that point, and then create a marker at that location on the map.
We want a tooltip bubble to appear whenever a user clicks on those markers, and we want it to contain the name and address of our location. Therefore, we need to add an event listener to each marker using the Maps API event.addListener method. Before we do that, though, we’ll create the tooltip itself. In the Google Maps API, this type of tooltip is called an InfoWindow. So we create a new InfoWindow, and also set up some HTML to fill it with the necessary information. Then we add our event listener. The listener will fire whenever one of the markers is clicked, and both set the content of the InfoWindow and open it so it’s visible on the map.
Finally, after adding all the markers and their associated event handlers and InfoWindows, we fit the map to the markers by using the Maps API’s fitBounds method. All we need to pass it is the bounds object we’ve been extending to include each marker. This way, no matter where the map has been zoomed or panned, it will always snap back to an ideal zoom level that includes all our markers.

Tying It All Together

Now that our code is ready, let’s put it into action. We’ll use jQuery’s $('document').ready to wait until the page is loaded, then initialize the map, pointing it to the page element with an id of map using the #map selector string:
$(document).ready(function() {
  $("#map").css({
    height: 500,
    width: 600
  });
  var myLatLng = new google.maps.LatLng(17.74033553, 83.25067267);
  MYMAP.init('#map', myLatLng, 11);
  
  $("#showmarkers").click(function(e){
    MYMAP.placeMarkers('markers.xml');
  });
});
We also attach a click event listener to the #showmarkers button. When that button is clicked, we call our placeMarkers function with the URL to our XML file. Give it a spin and you’ll see a set of custom markers show up on the map.

Summary

You’ve probably guessed that there’s a lot more to the Google Maps API than what we’ve covered here, so be sure to check out the documentation to get a feel for everything that’s possible.

By Madhuri & Mona

No comments:

Post a Comment

  ©Template by Dicas Blogger.

TOPO