Give Your Applications Mapping Capabilities, Part 3

Give Your Applications Mapping Capabilities, Part 3

oogle Maps (GM) provides a powerful online environment that you can use to provide your web application with rich interactive 2D mapping features. You can render points, lines, or areas located at any point on Earth; you need only attach your specific application data to the page.

Understanding Google Maps Technology
GM works within a JavaScript framework that interacts with Google’s web services from the user’s browser. You can insert GM’s framework in your web pages, and you can display maps by calling functions that the framework exposes. So your applications have no server-side requirements, and require adding only some “plain” JavaScript (JS) code to your HTML.

To access GM’s framework, the “Google Maps API,” you must obtain an API key—a free license key that you use to gain access to GM APIs from your pages.

One tough challenge when developing rich interactive web applications that make heavy use of JavaScript (as GM-centric applications do), is maintaining browser compatibility. The GM API simplifies this problem, because Google maintains and tests all the core JS for full compatibility with all the latest browsers. You need only take browser compatibility into account in your own JS code, the code you write that calls the GM APIs and interacts with the page’s controls.

The starting point for every Geographic Information System (GIS) application is defining and managing geographical coordinates. GM uses the standard absolute latitude/longitude coordinates system (see Parts 1 and 2 of this article series). That system defines every coordinate as a pair of decimal values: latitude and longitude. GM uses a fully object-oriented approach, so it defines a pair of location coordinates using a class named “GLatLng.” For example, to define a variable and create a new instance that defines a pair of coordinates:

   var coord = new GLatLng(myLatitude, myLongitude)
Authors Note: please note that Google Earth and Google Maps work with different notations. GE works with the convention, but GM works with the reverse () convention. I think this is related to Keynote’s standard used by Google Earth, which was originally a Keynote product before Google bought it.

Whenever you need to reference a geographical position (for example to render a placemark, define a line, a polygon, and so on) you will need to create one or more GLatLng instances and pass them as parameters. The GLatLng class exposes methods you can call; the two most important are “lat()” and “lng(),” which return the latitude and longitude of that coordinate, respectively. So, using the variable defined in the previous code example, you can access the individual values using:

   Var lat1 =;   Var lng1 = coord.lng();

Two other interesting methods are distanceFrom(other) and toUrlValue(precision). DistanceFrom(other) requires you to provide a second GLatLng object, and returns the distance (in meters) between the two points (with an average error of 0.3 percent). ToUrlValue(precision)returns a string that represents the point in a format you can use as a URL parameter value. You use this method when you want to create a URL to redirect users to a page that needs to receive a coordinate as a parameter.

Getting Starting with GM
GM is a JS framework, so you need to write some JS code, but you can link your web page to Google’s JS core code using the following script:

Author’s Note: You must obtain your own key parameter value, substituting that for the key=abcdefg value in the code below and wherever it appears in the rest of this article.

After referencing the GM framework, you add your own JS code to create a map. GM requires a reference to a page DOM object in which to insert the map. The simplest and most common method is to define a named

tag (you can place it wherever you want) and tell GM to use that

as the visual container. You’re free to define a style attribute to render the map; for example, you can define a border, or set the div’s width and height:


Next, you create an instance of the GMap2 class, which is the basic GM object that defines a map, and you bind it to the

you defined:

   var map = new GMap2(document.getElementById("myMap"));

Table 1 lists the most common and important GMap2 methods and properties; you can find a complete list in the GM API documentation. Argument names followed by a question mark are optional.

enableDragging() and disableDragging()These methods enable or disable the ability for users to drag the displayed map.
enableScrollWheelZoom() and disableScrollWheelZoom()These two methods enable or prevent users from zooming in and out on the map using the mouse scroll wheel (an interesting feature that is disabled by default).
addControl(control, position?) and removeControl(control)Call these methods to add or remove a control (for example a placemark) to a map.
setCenter(center, zoom?, type?)This method sets the map view to a given center point, zoom level, and map type.
zoomIn() and zoomOut()These methods change the map viewpoint, zooming the view closer or further away, respectively. Note that you can call these independently of the user scrolling capability applied by the two “ScrollWheelZoom” methods listed earlier.
point, node, opts?)

point, html, opts?)

point, tabs, opts?)

point, tabs, opts?)

These four methods let you control the informational popup windows that can appear when users hover over or click a point on the map (you can handle events and then call these methods to open an info windows).

After creating a GMap2 instance, you use it to show your data and create an interactive online application based on a map. The first thing you’ll probably want to do is call the setCenter method, to center the map view where you want it on Earth.

Authors note: To prevent memory leaks, Google recommends that you call the GUnload() function in the body onunload event in your pages, using the code: .

Working with Markers
The most-used feature of GM is its ability to show markers on a map. For example, you might show a marker to indicate a point of sale, a company address, or a location related to your business or application. You can refer to Parts 1 and 2 of this article to see other scenarios.

You create a marker using the GMarker object. The constructor requires a coordinate (a GLatLng instance); you can add the new GMarker object to your map object as an overlay. In fact, every object you add to a map is an overlay. To extend the previous example:

   map.addOverlay(new GMarker(new GLatLng(myLatitude, myLongitude)));   

The preceding code does several things. Reading from the inside parentheses outward, it first creates a GLatLng coordinate object using two decimal variables (myLatitude and myLongitude—the input parameter values were declared earlier), then it creates a new GMarker positioned at this coordinate, and finally adds the marker as an overlay to the previously created map.

You can repeat this operation as many times as you wish to create additional markers on your map.

By default, markers are relatively plain, but you can define your own marker icon if you don’t want to use the standard GM one. To do that, you create a GIcon object, and then create a marker using that object:

   var myIcon = new GIcon();   myIcon.shadow =       "";   myIcon.iconSize = new GSize(20, 34);   myIcon.shadowSize = new GSize(37, 34);   myIcon.iconAnchor = new GPoint(9, 34);   myIcon.infoWindowAnchor = new GPoint(9, 2);   myIcon.infoShadowAnchor = new GPoint(18, 25);   myIcon.image =       "";      markerOptions = { icon:myIcon };   map.addOverlay(new GMarker(      point, markerOptions));

In the preceding code, iconAnchor, shadowSize, and so on, are attributes that control how GM shows visual effects related to your icon. This can get quite complex, so I suggest you start from this simple example and make changes as needed, or refer to the complete GM API documentation.

Working with Lines
To show a line, you simply use an array of points defined with GLatLng objects. The points define a connected set of line segments. GM will connect every pair of points with a direct line segment, so anything except a straight line will always require a sequence of linear segments. GM has no concept of curves—in other words, GM (like Google Earth) doesn’t provide a way to draw a “real” curved line, but you can approximate curved lines with close-set points. The more points you provide, the better the approximation to a true curve.

Here’s an example showing the JS code required to draw a line (termed a “PolyLine” in GM parlance):

var map = new GMap2(      document.getElementById("myMap"));   map.enableDragging;   map.enableScrollWheelZoom() ;   map.setCenter(new GLatLng(      45.629865, 9.576918333333341), 13);
Figure 1. Drawing Polylines: Using an array of GLatLng objects, you can draw lines to outline or overlay an area.
      var polyline = new GPolyline([   new GLatLng(45.629865, 9.576918333333341),   new GLatLng(45.6320033333333,       9.581189999999999)], "#ff0000", 10);      map.addOverlay(polyline);

In the preceding code, the PolyLine constructor takes an array of GLatLng objects, and draws a set of line segments connecting those coordinates. The PolyLine constructor also requires a line color and width (in pixels).

The code example above creates the map shown in Figure 1.

The PolyLine object exposes its own set of properties and methods. The most important are getLength(), which returns the length (in meters) of the line along the Earth’s surface, and the hide() and show() methods that hide or show the line.

Working with Polygons
Defining a polygon is similar to defining a line, except that you use the GPolygon object. In GM polygons in fact are filled GPolyLines. For example, here’s the JS code required to create a simple polygon around a center point as shown in Figure 2:

Figure 2. Drawing Polygons: A polygon consists of a set of GLatLng objects that define its vertices relative to a center point, drawn with a specified stroke width, fill color, and opacity.
   var map = new GMap2(      document.getElementById("myMap"));   map.enableDragging;   map.enableScrollWheelZoom() ;      center = new GLatLng(      45.6320033333333, 9.581189999999999);      map.setCenter(center, 13);      var latOffset = 0.01;   var lonOffset = 0.01;      var polygon = new GPolygon([     new GLatLng(,          center.lng() - lonOffset),     new GLatLng( +          latOffset, center.lng()),     new GLatLng(,          center.lng() + lonOffset),     new GLatLng( -          latOffset, center.lng()),     new GLatLng(,          center.lng() - lonOffset)   ], "#f33f00", 5, 1, "#ff0000", 0.2);      map.addOverlay(polygon);

The parameters to the GPolygon constructor method shown in the preceding code are points, strokeColor, strokeWeight, strokeOpacity, fillColor, fillOpacity, opts, and—except for the points themselves—all are optional.

Editor’s Note: Part 2 of this article discusses differences between GM and the more powerful Google Earth environment, which offers more features for drawing polygons.

Creating GM Files Programmatically
Although the simplest way to create a JS application that works with your server application and data is to render JS or parameters from a server-side technology, such as ASP.NET, I suggest you create your GM application by placing all your JS code in separate and static JS files, as functions. By doing that you can emit only the required values in your main HTML code, such as positioning data and so on. You’ll find that—while it’s harder to begin with—you’ll end up with cleaner and more reusable code. You can also create your own server-side framework to use GM in your application without having to write a lot of JS in every page. Again, this requires a serious commitment up front, but you’ll have a powerful resource when you want to create other GM applications.

One of GM’s most interesting features is Geocoding. Geocoding a point involves using a description of that point (which could be anything from a full address to just a city name) to retrieve that point’s coordinates on Earth. You can use this powerful feature whenever you need the latitude and longitude for a known location.

Author’s Note: Geocoding is not magic; it relies on a huge Google database that contains everything from city names to full address details. Unfortunately, geocoded data can be inaccurate, or may not exist. For accuracy in “real” GIS applications you should instead get positional data “on the road,” as explained in Part 1.

You can geocode a point either by calling the GM API from JS or by calling a Google web service. The web service takes the address as an input parameter, and returns an XML document containing all available geocoded information of that address. This means that you can work from a server-side application and use the returned data however you like, from any language. The web page environment is not involved. Here’s an example that creates a map and then shows a specific point on the map, using data it retrieves from the web service:


You need to define form fields to display the data and interact with JS:

Figure 3. Geocoding in Action: This simple form lets you search for and display a map given a city or specific address.

The preceding code creates a web page with a form and a map, as in Figure 3. You can enter a location into the text box, then click the Go button, and the map will find and display that place.

The most interesting part of that code is the GClientGeocoder class. This class exposes a GetLatLng (address) method that retrieves coordinates from a Google web service. The web service requires a string value—in this case the address (full or partial)—that you want to geocode. It also requires a second parameter—a callback function pointer. The callback function is necessary because geocoding requires a round trip to a Google web service, which can take a long time. Making the request synchronously would block the browser interface until the operation completes, thus freezing the application for the user. With the asynchronous implementation, you start the request, which the browser executes on a secondary thread, and the main thread remains free to handle the UI. When the Google web service has responded, the browser calls the callback function. You place the code that manages the retrieved coordinates and reports them to the user in the callback function body. For example, the preceding code defines a function that checks whether the geocoding request returned a value, and if so, creates a marker to pinpoint the returned location on the map.

Google Maps is a powerful and customizable interactive, 2D, online framework for rendering maps. Using its JavaScript API, you can create exciting web applications that show maps, locations, and other geographical views. Your users can interact with these maps and get useful information from your application in a powerful and intuitive way.

See also  Exploring the Convenience of a Cloud-Based PDF Editor

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist