Sign In/My Account | View Cart  
advertisement


Listen Print Discuss

Hacking Maps with the Google Maps API
by Hari Gottipati | Pages: 1, 2, 3

4. Display Custom Icons for Map Overlays

Based on the requirements, you can decide what icon to show at each location. In our example, you can show a different icon for each park, or a different icon for parks that have pool facilities, or you can display the default icon for all locations. To display the default icon, there is nothing to do. The statement var marker = new GMarker(point) will create the marker with a default icon. If you decide to use the default icon for all locations, you can skip this step and directly go to the next step.

Again, add icon information in the same XML file and you can loop through the icon information to add different icons for different parks.
Let's rewrite our parks.xml file with icon information:

<parks>
    <park>
       <point lng="-96.936574" lat="32.822129"/> 
       <icon image="green.png" class="local"/>
    </park>
    <park>
       <point lng="-96.9330679" lat="32.871815"/> 
       <icon image="yellow.png" class="local"/>
    </park>
</parks>

Add the logic of parsing the icon information to the same section where you parsed the point information:

var iconImage = xmlDoc.documentElement.getElementsByTagName("icon");

Create the base icon with GIcon class and add the size, shadow, and shadow size:

var baseIcon = new GIcon();
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);

Now create the Icon with base icon:

var icon = new GIcon(baseIcon);

Set the custom image you wanted to display to this icon:

Icon.image = iconImage[i].getAttribute("src");

In the previous step we created the marker with a default icon. Now we have a customized icon, so pass the icon to the marker constructor, along with a point:

var marker = new GMarker(point, icon);
Map.addOverlay(marker);
(

For complete source code for this step, see Listing 3.

)

5. Displaying Icon Information on Click

The last step is to display the content once a user clicks on the marker. In our example, if a user clicks on the marker, we'll show the park name, address, photo, and URL for more info.

The API provides several options for displaying content in an info window:

  • openInfoWindow(htmlElem): opens an info window with the given HTML content over this marker. htmlElem should be an HTML DOM element.
  • openInfoWindowHtml(htmlStr): takes an HTML string rather than an HTML DOM element
  • openInfoWindowXslt(xmlElem, xsltUri): takes an XML element and the URI of an XSLT document to produce the content of the info window. The first time a URI is given, it is retrieved with GXmlHttp and subsequently cached.

The API also provides support for different events: click, which is triggered when the user clicks on this marker; infowindowopen, which is triggered when the info window is opened above this marker; and infowindowclose, which is triggered when the info window above this marker is closed.

You can add dynamic elements to your application using event listeners. An object exports several named events, and your application can listen to those events using the static methods GEvent.addListener or GEvent.bind. The former takes a marker as its first argument, the event as the second argument, and a function as the third argument. In the function you can call one of the marker's info window methods.

This will display a blowup of the map over this marker. You can specify the zoom level, otherwise it uses a default zoom level of 1.

GEvent.addListener(marker, "click", function() {
          marker.showMapBlowup();
    });

These add plain text or, alternately, HTML:

GEvent.addListener(marker, "click", function() {
          marker.openInfoWindow("Park");
    });
GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowHtml("<b>Park</b>");
    });

Let's add the final information about each park to our parks file:

<parks>
  <park><point lng="-96.936574" lat="32.822129"/> 
    <icon image="green.png" class="local" /> 
    <info>
      <FullName>Austin Recreation Center</FullName> 
      <url>http://www.ci.irving.tx.us/parks_and_recreation/
	     facilities/austin_recreation_center/index.asp</url>
      <address>825 East Union Bower Road</address> 
      <address2>Irving, Texas 75061</address2> 
      <phone>(972)721-2659</phone>
      <img>http://www.ci.irving.tx.us/parks_and_recreation/
	     facilities/austin_recreation_center/images/image7.gif</img>
    </info>
  </park>
  <park><point lng="-96.9330679" lat="32.871815"/> 
    <icon image="yellow.png" class="local" /> 
    <info>
      <FullName>Birds Fort Trail Park</FullName> 
      <url>http://www.ci.irving.tx.us/parks_and_recreation/
	     facilities/birds_fort_trail/index.asp</url>
      <address>5756 N. O'Connor Blvd</address> 
      <address2>Irving, Texas 75039</address2> 
      <phone>(972)721-2659</phone>
      <img>http://www.ci.irving.tx.us/parks_and_recreation/
	     facilities/birds_fort_trail/images/index2.jpg</img>
    </info>
  </park>
</parks>

Listing 4 contains the source of the XSLT we use to display the park information taken from the XML above.

Again, we parse the XML file for info elements inside the loop and add the event listener with an info element and parks.xsl file.

var info = xmlDoc.documentElement.getElementsByTagName("info");
GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowXslt(info[i], "parks.xsl");
    });

(See Listing 5 for complete source code for this step.)

Now you've seen all steps involved in the process of developing a mapping application with Google Maps API. Happy map hacking!


Comment on this articleShare your experience in our forums.
(* You must be a
member of XML.com to use this feature.)
Comment on this Article


Titles Only Titles Only Newest First
  • Geocoding
    2007-08-15 07:48:49 navyjax2 [Reply]

    Actually, Google maps does include a geocoding ability (see the area just above where this link will take you -http://www.google.com/apis/maps/documentation/#Geocoding_Examples). Only thing is, I've found that it doesn't seem to play nicely with XML. I could plot points from XML addresses fine, but because it pulls the points asynchrously, I'm finding it hard to match XML data (name, description) to a point when the marker gets displayed in order to accurately and reliably display its information on an infoWindow. I can do it fine for lat/lng, but not for addresses. Was hoping someone had messed around with this...


    Here are the applicable snippets of code:


    function onload() {
    GDownloadUrl("dataptsaddr.xml", function(data) {
    var xml = GXml.parse(data);
    var addresses = xml.documentElement.getElementsByTagName("wpt");


    // loop through the XML addresses
    for (var i = 0; i < (addresses.length); i++) {
    var xmlAddress = addresses[i].getAttribute("addr");
    geocoder.getLatLng(
    xmlAddress,
    new Function("point", "writeMarker(point, '" + xmlAddress + "');")
    );
    }
    });
    }


    function writeMarker(point, xmlAddress) {
    if (GBrowserIsCompatible()) {
    var map = new GMap2(document.getElementById("map"));
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.addControl(new GScaleControl());
    map.enableScrollWheelZoom();


    thepointbox.value = point;
    theaddrbox.value = xmlAddress;



    GDownloadUrl("dataptsaddr.xml", function(data) {


    var xml = GXml.parse(data);
    var addresses = xml.documentElement.getElementsByTagName("wpt");
    var point = thepointbox.value;
    var address = theaddrbox.value;
    var j = theindexbox.value;
    var name = xml.documentElement.getElementsByTagName("name")[j].childNodes(0).nodeValue;
    var desc = xml.documentElement.getElementsByTagName("desc")[j].childNodes(0).nodeValue;
    // alert(j + ' ' + point + ' ' + address + ' ' + name + ' ' + desc);
    // var marker = createMarker(point,address,"<div id=\"gmapmarker\">" + name + "
    " + desc + "</div>", 2);
    var marker = new GMarker(point);
    map.addOverlay(marker);
    marker.openInfoWindowHtml('' + name + '
    ' + desc + '
    ' + point + '' );
    if (theindexbox.value < addresses.length) {theindexbox.value++;}
    alert(j);
    });
    } else {alert("Sorry, the Google Maps API is not compatible with this browser.");}
    }


    "Wpt" is my leading node's tag, and "Addr" is the tag for the address in each "wpt" section. I left the "alert(j)" to demonstrate that, using textboxes to feed in revised values into Google's XML parsing function (GDownloadUrl), I can increase the index effectively to get the next XML data as new points and xmlAddresses are fed from the geocoder, but still no marker ever gets displayed. I had to pass values between the functions using textboxes (thepointbox, theindexbox, etc.) because global variables don't seem to work for callback functions - would always show as undefined without doing it this way. When I use the same writeMarker function with purely GPS points, it works perfectly. I've done an alert on point, xmlAddress coming into writeMarker from the geocoder and my index, name, and description fields from the XML and all are correct, they just won't display using var marker = GMarker(point) and map.addOverlay(marker), (where var map = new GMap2(document.getElementById("map"));) even though I used this with lat/lng points and it's worked fine.... Just thought I'd put all this out there in case someone wanted to play with it.

    • Geocoding
      2007-08-15 07:53:52 navyjax2 [Reply]

      Here's some sample XML data, btw:


      <?xml version="1.0" standalone="yes"?>
      <gpx version="1.0" creator="GPS Visualizer http://www.gpsvisualizer.com/" xmlns="http://www.topografix.com/GPX/1/0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd">
      <wpt addr="39.15497, -77.51940">
      <name>White's Ferry</name>
      <desc>24801 White's Ferry Rd, Dickerson, MD 20842</desc>
      <state>MD</state>
      </wpt>
      </gpx>


      -Tom

      • Geocoding
        2007-08-15 08:06:50 navyjax2 [Reply]

        Actually, I shouldn't have used that section of XML - I meant to post something that had a normal address that worked on a Google map, instead of one that included the coordinate points already. I had that other section in there because I wanted the code able to do both (it doesn't matter to Geocoder whether it's getting a GPS point or an address - it still spits back a GPS point to plot). Here's a better example section:


        <wpt addr="150 Malin Dr, Wytheville, VA, 24382">
        <name>Days Inn</name>
        <desc>150 Malin Dr, Wytheville, VA 24382</desc>
        <state>VA</state>
        </wpt>

  • Nice article here is my 2 cent www.mapmyevent.com
    2006-11-30 06:58:55 mapmyevent.com [Reply]

    recently I bulit a beta site mashing events list with hotels information. the link is http://www.mapmyevent.com


    MapMyEvent is a portal that delivers free map information for any Event along with information about Hotels and Landmarks around it. You can use Mapmyevent to generate customized link for your own Events and share it with your friends or use it for your making own travel plans. Hope you enjoy the service.

  • Example does not work in Firefox 1.0.7
    2006-03-10 16:25:18 SEA [Reply]

    This works great in IE 6 but in Firefox the marker icons don't show. It seems like Firefox is not parsing the xml file. Any ideas why?

    • Example does not work in Firefox 1.0.7
      2006-11-15 02:06:21 EmZilla [Reply]

      The info windows aren't appearing in ie6 either.




      • Example does not work in Firefox 1.0.7
        2006-12-04 09:17:11 doncicio [Reply]

        It's impossible to display the information when the user click on the marker with safari and mozilla (i didn't try with IE).
        the problem seems to happends when we call : marker.openInfoWindowXslt();


        I tried with marker.openInfoWindow("some text") , and there is no problem.


        Someone get the solution ?

        • Example does not work in Firefox 1.0.7
          2006-12-07 10:25:09 SDT2000USA [Reply]

          I'm having the same problem in IE and would be interested if anyone has found the solution.


          I had the maps working fine for my company's web site. The info windows worked fine for several months, and then suddenly stopped working a few weeks ago. (Even though I made no changes to the html file.)


          Here's the page with all my maps, in case it helps give anyone any ideas as to what is wrong:


          http://www.coffeenews-wct.com/html/bfnm.html


          If I figure it out, I will post the solution here.


          Thanks to anyone who can help!


          Scott Tunmer
          Coffee News of Western Connecticut

  • Geo Coder Service
    2006-02-14 09:44:17 phongleland [Reply]

    A problem I found with Geo Coder services is that the are slow. You can build your own using the instructions I posted here http://lelandusa.blogspot.com/

  • Hotels booking Tool
    2005-10-22 09:15:58 Mate77 [Reply]

    Just to let you know my Hotels booking search tool with Google Map :
    http://www.hotels-finder.org


    • Hotels booking Tool
      2006-03-03 16:05:20 jazzgeek [Reply]

      Very nice!


      I need someone to develop something like this plus an input form for web visitors to input information and picture - to go database - results displayed on list and google map.


      Can you recommend someone?


      Thanks!

      • Hotels booking Tool
        2006-05-06 19:39:06 Mate77 [Reply]

        Hi jazzgeek
        I can do it for you
        contact me on MSN at mdemeillat[at]hotmail[dot]com
        see you

  • Google Maps fitness facility locator
    2005-09-18 16:56:45 remacg [Reply]

    This Google Maps fitness facility locator at http://www.gympost.com/gymsearch/map.php lets users find gyms, health clubs, etc. in the U.S. It uses AJAX, XML, and some advanced search features. Geocoding is provided by http://www.geocoder.us as a paid service (well worth the minimal cost).

  • geocoding tools
    2005-08-18 21:55:33 menglis3 [Reply]

    http://www.maporama.com/ works, for resolution down to 200metres, for Australia (based on very spotty testing - perth, Sydney, Broken hill and South coast of NSW)

  • Lovely Google Maps building tool
    2005-08-11 20:56:36 DevDev [Reply]

    I would like to recommend http://www.mapbuilder.net - an excellent tool to build your own map without any knowledge of Google API and JavaScript.

  • Phoogle Maps
    2005-08-11 04:59:09 system7designs [Reply]

    I've created a php class that ties in to a geocoding service so that you can type in an address and get its longitude & latitude and display it on a google map. It's still under development, but I do have a beta release out that works quite well.


    http://dev.system7designs.com

  • Which geocoding tools to use?
    2005-08-10 21:21:56 angryn00b [Reply]

    Hari, you said that some tools will provide lat. and long. for a zip code. Which tools?


    And do you or anyone else have any other good recommendations for a free or cheap geocoding service? I've got a free account at geocoder.us, and I appreciate them providing it for free, but it's not very quick and it doesn't locate a large portion of street addresses + zips that I feed it.


    I've done a fair amount of hacking on both APIs discussed, and if someone comes out with a service combining Yahoo's API with Google's user interface, I'd be pretty happy.

    • Which geocoding tools to use?
      2005-10-05 15:16:38 dnstevenson [Reply]

      We've got a low-cost (lower than geocoder.us) and quick geocoding service at http://www.geocodeamerica.com. If you do a zipcode only search, it will return the zipcode centroid.


      Dave
      http://www.geocodeamerica.com
      http://www.favoriterun.com

    • Which geocoding tools to use?
      2005-08-11 10:52:13 emad1b [Reply]

      Have you seen this (http://emad.fano.us/blog/?p=277) . Basically, it allows you to geocode without any knowledge of geocoding. Javascript knowledge required.

    • Which geocoding tools to use?
      2005-08-11 09:03:17 EventFinder [Reply]

      For the US - I think the USPS provides a city * zip list file?


      Adding my site - an event listing mashup:
      http://www.globaleventfinder.com