Each of the following examples shows only the relevant JavaScript code, not the full HTML file. You can plug the JS code into the skeleton HTML file shown earlier, or you can download the full HTML file for each example by clicking the link after the example.
The following example creates a map and centers it on Prague.
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(50.1, 14.4), 12);
GUnload() will remove most of the circular references that cause memory leaks. You should call GUnload() in the unload event of your page to reduce the potential that your application leaks memory:
<body onunload="GUnload()">
The following example displays a map, waits two seconds, and then pans to a new center point.
The panTo method centers the map at a given point. If the specified point is in the visible part of the map, then the map pans smoothly to the point; if not, the map jumps to the point.
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(50.1, 14.4), 12);
window.setTimeout(function() {
map.panTo(new GLatLng(50.1, 14.5));
}, 2000);
>> API reference
You can add controls to the map with the addControl method.
Zoom In
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(50.1, 14.4), 12);
function zooms() {
map.zoomIn();
}
>> API referenceTo register an event listener, call the GEvent.addListener method. Pass it a map, an event to listen for, and a function to call when the specified event occurs. In the following example code, we display the latitude and longitude of the center of the map after the user drags the map.
var map = new GMap2(document.getElementById("map"));
GEvent.addListener(map, "moveend", function() {
var center = map.getCenter();
document.getElementById("message").innerHTML = center.toString();
});
map.setCenter(new GLatLng(50.1, 14.4), 12);
>> API referenceTo create an info window, call the openInfoWindow method, passing it a location and a DOM element to display. The following example code displays an info window anchored to the center of the map with a simple "Hello, world" message.
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(50.1, 14.4), 12);
map.openInfoWindow(map.getCenter(), "Hello World");
This example uses GMarker to create 3 markers, then addOverlay to display them
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(50.1, 14.4), 12);
map.addOverlay(new GMarker(new GLatLng(50.105, 14.405)));
map.addOverlay(new GMarker(new GLatLng(50.100, 14.395)));
map.addOverlay(new GMarker(new GLatLng(50.095, 14.400)));
To trigger an action when a user clicks the map, register a listener for the "click" event on your GMap2 instance. When the event is triggered, the event handler will receive two arguments: the marker that was clicked (if any), and the GLatLng of the clicked point. If no marker was clicked, the first argument will be null.
"click" event. Other types of overlays, like GPolyline, are not clickable.In the following example, when the visitor clicks a point on the map without a marker, we create a new marker at that point. When the visitor clicks a marker, we remove it from the map.
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(50.1, 14.4), 12);
GEvent.addListener(map, "click", function(marker, point) {
if (marker) {
map.removeOverlay(marker);
} else {
map.addOverlay(new GMarker(point));
}
});
For more information about events, see the Events Overview. For a complete list of GMap2 events and the arguments they generate, see GMap2.Events.
In this example, we show a custom info window above each marker by listening to the click event for each marker. We take advantage of JavaScript function closures to customize the info window content for each marker.
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(50.1, 14.4), 12);
// Creates a marker at the given point with the given number label
function createMarker(point, number) {
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml("Marker #<b>" + number + "</b>");
});
return marker;
}
// Add 3 markers to the map.
var p; // temp value to hold point info.
p = new GLatLng(50.105, 14.405);
map.addOverlay(createMarker(p, 1));
p = new GLatLng(50.100, 14.395);
map.addOverlay(createMarker(p, 2));
p = new GLatLng(50.095, 14.400);
map.addOverlay(createMarker(p, 3));
For more information about events, see the Events Overview. For a complete list of GMap2 events and the arguments they generate, see GMap2.Events.
Version 2 of the API introduces openInfoWindowTabs() and the GInfoWindowTab class to support info windows with multiple, named tabs. The example below displays a simple tabbed info window above a single marker.
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(50.1, 14.4), 12);
// Our info window content
var infoTabs = [
new GInfoWindowTab("Tab #1", "This is tab #1 content"),
new GInfoWindowTab("Tab #2", "This is tab #2 content")
];
// Place a marker in the center of the map and open the info window
// automatically
var marker = new GMarker(map.getCenter());
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowTabsHtml(infoTabs);
});
map.addOverlay(marker);
marker.openInfoWindowTabsHtml(infoTabs);
This example creates a new type of icon, using the Google Ride Finder "mini" markers as an example. We have to specify the foreground image, the shadow image, and the points at which we anchor the icon to the map and anchor the info window to the icon.
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(50.1, 14.4), 12);
// Create our "tiny" marker icon
var icon = new GIcon();
icon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
icon.iconSize = new GSize(12, 20);
icon.shadowSize = new GSize(22, 20);
icon.iconAnchor = new GPoint(6, 20);
icon.infoWindowAnchor = new GPoint(5, 1);
// Add 10 markers to the map at random locations
var bounds = map.getBounds();
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();
var lngSpan = northEast.lng() - southWest.lng();
var latSpan = northEast.lat() - southWest.lat();
for (var i = 0; i < 10; i++) {
var point = new GLatLng(southWest.lat() + latSpan * Math.random(),
southWest.lng() + lngSpan * Math.random());
map.addOverlay(new GMarker(point, icon));
}
The geocoder can be accessed from within the JavaScript using the GClientGeocoder object. The getLatLng method can be used to convert an address into a GLatLng. Because geocoding involves sending a request to Google's servers, it can take some time. To avoid making your script wait, you need to pass in a function to call after the response comes back. In this example, we geocode an address, add a marker at that point, and open an info window displaying the address.
var map = new GMap2(document.getElementById("map"));
var geocoder = new GClientGeocoder();
function showAddress(address) {
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert(address + " not found");
} else {
map.setCenter(point, 15);
var marker = new GMarker(point);
map.addOverlay(marker);
marker.openInfoWindowHtml(address);
}
}
);
}
If you would like to access structured information about an address, GClientGeocoder also provides a getLocations method that returns a JSON object consisting of the following information.
Statusrequest -- The request type. In this case, it is always geocode.code -- A response code (similar to HTTP status codes) indicating whether the geocode request was successful or not. See the full list of status codes.Placemark -- Multiple placemarks may be returned if the geocoder finds multiple matches.address -- A nicely formatted and properly capitalized version of the address.AddressDetails -- The address formatted as xAL, or eXtensible Address Language, an international standard for address formatting.Point -- A point in 3D space.coordinates -- The longitude, latitude, and altitude of the address. In this case, the altitude is always set to 0.Here we show the JSON object returned by the geocoder for the address of Google's headquarters.
{
name: "1600 Amphitheatre Parkway, Mountain View, CA, USA",
Status: {
code: 200,
request: "geocode"
},
Placemark: [
{
address: "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
AddressDetails: {
Country: {
CountryNameCode: "US",
AdministrativeArea: {
AdministrativeAreaName: "CA",
SubAdministrativeArea: {
SubAdministrativeAreaName: "Santa Clara",
Locality: {
LocalityName: "Mountain View",
Thoroughfare: {
ThoroughfareName: "1600 Amphitheatre Pkwy"
},
PostalCode: {
PostalCodeNumber: "94043"
}
}
}
}
}
},
Point: {
coordinates: [-122.083739, 37.423021, 0]
}
}
]
}
In this example, we use the getLocations method to geocode addresses, and extract the nicely formatted version of the address and the two-letter country from the JSON and display it in the info window.
var map;
var geocoder;
map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(34, 0), 1);
geocoder = new GClientGeocoder();
function addAddressToMap(response) {
map.clearOverlays();
if (!response || response.Status.code != 200) {
alert("\"" + input.value + "\" not found");
} else {
place = response.Placemark[0];
point = new GLatLng(place.Point.coordinates[1],
place.Point.coordinates[0]);
marker = new GMarker(point);
map.addOverlay(marker);
marker.openInfoWindowHtml(place.address + '<br>' +
'<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);
map.panTo(point);
}
}
var input = document.getElementById('in16');
// showLocation() is called when you click on the Search button
// in the form. It geocodes the address entered into the form
// and adds a marker to the map at that location.
function showLocation() {
var address = input.value;
geocoder.getLocations(address, addAddressToMap);
}
// findLocation() is used to enter the sample addresses into the form.
function findLocation(address) {
input.value = address;
showLocation();
}
Try these:
Slovansky Dum, Prague, Czech Republic
1600
amphitheatre mtn view ca
1
Telegraph Hill Blvd, San Francisco, CA, USA
4144
Avenue Pierre-De-Coubertin, Montréal, Canada
Champ
de Mars 75007 Paris, France
Piazza
del Colosseo, Roma, Italia
Domkloster
3, 50667 Köln, Deutschland
Plaza
de la Virgen de los Reyes, 41920, Sevilla, España
東京タワー (Tokyo Tower, Tokyo Japan)
123 Main St, Googleville
GClientGeocoder is equipped with a client-side cache by default. The cache stores geocoder responses, so that if the same address is geocoded again, the response will be returned from the cache rather than from Google's geocoder. To turn off caching, pass null to the setCache method of GClientGeocoder. However, we recommend that you leave caching on because it improves performance. To change the cache being used by GClientGeocoder, use the setCache method and pass in the new cache. To empty the contents of the current cache, use the reset method on the geocoder or on the cache directly.
Developers are encouraged to build their own client-side caches. In this example, we construct a cache that contains pre-computed geocoder responses to six capital cities in countries covered by geocoding API. First, we build an array of geocode responses. Next, we create a custom cache that extends a standard GeocodeCache. Once the cache is defined, we call the setCache method. There is no strict checking of objects stored in the cache, so you may store other information (such as population size) in the cache as well.
// Builds an array of geocode responses for the 6 capitals
var city = [
{
name: "Washington, DC",
Status: {
code: 200,
request: "geocode"
},
Placemark: [
{
address: "Washington, DC, USA",
population: "0.563M",
AddressDetails: {
Country: {
CountryNameCode: "US",
AdministrativeArea: {
AdministrativeAreaName: "DC",
Locality: {
LocalityName: "Washington"
}
}
}
},
Point: {
coordinates: [-77.036667, 38.895000, 0]
}
}
]
},
// ... etc., and so on for other cities
];
var map;
var geocoder;
// CapitalCitiesCache is a custom cache that extends the standard GeocodeCache.
// We call apply(this) to invoke the parent's class constructor.
function CapitalCitiesCache() {
GGeocodeCache.apply(this);
}
// Assigns an instance of the parent class as a prototype of the
// child class, to make sure that all methods defined on the parent
// class can be directly invoked on the child class.
CapitalCitiesCache.prototype = new GGeocodeCache();
// Override the reset method to populate the empty cache with
// information from our array of geocode responses for capitals.
CapitalCitiesCache.prototype.reset = function() {
GGeocodeCache.prototype.reset.call(this);
for (var i in city) {
this.put(city[i].name, city[i]);
}
}
function addAddressToMap(response) {
map.clearOverlays();
if (response && response.Status.code != 200) {
alert("Unable to locate " + decodeURIComponent(response.name));
} else {
var place = response.Placemark[0];
var point = new GLatLng(place.Point.coordinates[1],
place.Point.coordinates[0]);
map.setCenter(point, 6);
map.openInfoWindowHtml(point, "City: " + place.address
+ "
Population: " + place.population);
}
}
function findCity(which) {
if (which != 0) {
geocoder.getLocations(city[which - 1].name, addAddressToMap);
}
}
map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(50.144, 14.144), 6);
// Here we set the cache to use the UsCitiesCache custom cache.
geocoder = new GClientGeocoder();
geocoder.setCache(new CapitalCitiesCache());
Go to:
It is possible to access the Maps API Geocoder using HTTP. However, for any web application
involving users making geocoding requests, this is a phenomenally bad idea, because it will
use your Geocoding quota, and will burn quickly. Please use the GClientGeocoder
for all client-side geocoding.
To access the Maps API geocoder directly using server-side scripting, send a request to http://maps.google.com/maps/geo?
with the following parameters in the URI:
q -- The address that you want to geocode.key -- Your API key.output -- The format in which the output should be generated. The options are xml, kml or json.In this example, we request the geographic coordinates of Google's headquarters.
http://maps.google.com/maps/geo?q=1600+Amphitheatre+Parkway,+Mountain+View,+CA&output=xml&key=abcdefgIf you specify json as the output, the response is formatted as a JSON object, as shown in the example above. If you specify xml or kml, the response is returned in XML or KML. The XML and KML outputs are identical except for the MIME types.
For example, this is the response that the geocoder returns for "1600 amphitheatre mtn view ca".
<kml>
<Response>
<name>1600 amphitheatre mtn view ca</name>
<Status>
<code>200</code>
<request>geocode</request>
</Status>
<Placemark>
<address>
1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA
</address>
<AddressDetails>
<Country>
<CountryNameCode>US</CountryNameCode>
<AdministrativeArea>
<AdministrativeAreaName>CA</AdministrativeAreaName>
<SubAdministrativeArea>
<SubAdministrativeAreaName>Santa Clara</SubAdministrativeAreaName>
<Locality>
<LocalityName>Mountain View</LocalityName>
<Thoroughfare>
<ThoroughfareName>1600 Amphitheatre Pkwy</ThoroughfareName>
</Thoroughfare>
<PostalCode>
<PostalCodeNumber>94043</PostalCodeNumber>
</PostalCode>
</Locality>
</SubAdministrativeArea>
</AdministrativeArea>
</Country>
</AddressDetails>
<Point>
<coordinates>-122.083739,37.423021,0</coordinates>
</Point>
</Placemark>
</Response>
</kml>
If you have a car or motorbike, driving is awesome. If you do not, then it's not so much fun. If you would like your application to display driving directions, then here's how to do it.
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(50.1, 14.4), 12);
var directionsPanel;
var directions;
directionsPanel = document.getElementById("ddirections");
directions = new GDirections(map, directionsPanel);
directions.load("from: Prague, Czech Republic to: London, UK");
KML stands for Keyhole Markup Language. You can learn much more about it at
http://earth.google.com/kml/.
As a very quick overview, it's an industry standard XML variation, used to describe geographic locations. It's
also the common language spoken by the Google Maps API, Google Earth and Google Maps for Mobile.
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.2">
<Placemark>
<name>Simple placemark</name>
<description>Attached to the ground. Intelligently places itself
at the height of the underlying terrain.</description>
<Point>
<coordinates>-122.0822035425683,37.42228990140251,0</coordinates>
</Point>
</Placemark>
</kml>
Google Maps can import external files in a number of ways. The easiest is to import
GeoRSS or KML natively, using GGeoXML
var map = new GMap2(document.getElementById("map"));
var geoXml = new GGeoXml("http://mapgadgets.googlepages.com/cta.kml");
map.addControl(new GLargeMapControl());
map.setCenter(new GLatLng(41.875696,-87.624207), 11);
map.addControl(new GLargeMapControl());
map.addOverlay(geoXml);
>> API guideStreet View is pretty new (it's still only available in the development version of Google Maps at time of writing).
However, it's also pretty cool. Here's a very quick overview.
var myPano = new GStreetviewPanorama(document.getElementById("map"));
var bridge = new GLatLng(37.792639,-122.391049);
var myPOV = {yaw:105.0,pitch:-120};
myPano.setLocationAndPOV(bridge, myPOV);
>> API guideImage Cutter allows you to very easily make custom google maps from any image.
You can download it
from the UCL Centre of Spatial Analysis site.
If your code doesn't seem to be working, here are some approaches that might help you solve your problems:
Here are some additional resources. Note that these sites are not owned or supported by Google.