During the last years, online maps have evolved so much that they hold valuable information and capabilities. The most well known maps are Google’s Maps. Google Maps are powered by a powerful engine and also have a large community offering support.
Google allows web masters to add and customize maps on their sites with the Google Maps API. To use the Google Maps API, you have to get an API key from Google. Each API key is valid for a certain domain but you get generate as many keys as you want.
Creating our first simple map
Implementing Google Maps in your site is plain easy. You just have to add:
- A link to a JavaScript file provided by Google
- Some lines of JavaScript with some parameters
- A layer where our map will be displayed.
The link to the JavaScript file:
<script charset="UTF-8" src="https://maps.google.com/maps?file=api&v=2&hl=en&oe=utf-8&key=API_KEY" type="text/javascript"></script>
Note: We can change the language used in our map implementation by changing the “hl=en” part and use our preferred language, for example “hl=el” for Greek language or “hl=fr” for French language. We also change the “API_KEY” part with the key we got from Google.
Caution: Google Maps work better when loaded in UTF-8 encoded pages.
JavaScript code with parameters:
This is where some magic can happen with Google Maps. We can add some parameters in the JavaScript and change the way our maps look, react to user feedback and more. For example we can set the map to load and display a particular coordinate in the center of our view. The code to center the map to a specific location is:
function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(37.97918, 23.71665), 13);
map.setUIToDefault();
}
}
This part of the code is where we set the coordinates we want the map to focus:
map.setCenter(new GLatLng(37.97918, 23.71665), 13);
The option “13” is the zoom level of our map. We can set a number from 1 to 17.
To get the Latitude and Longitude of a specified location you can use this tool. It is very easy to use. You just move the map around and place the location of your interest in the center of the map.
Placing markers
You can mark a place of interest in the map by using markers. The code to place a marker on a spot is:
var point = new GLatLng(37.97110, 23.72601);
map.addOverlay(new GMarker(point));
So, our code after we place a marker, looks like this:
function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(37.97918, 23.71665), 13);
var point = new GLatLng(37.97110, 23.72601);
map.addOverlay(new GMarker(point));
map.setUIToDefault();
}
}
The example above centers our map on Athens Greece, and adds a marker on Acropolis.
Balloons:
Balloons are a kind of tool-tips that you can use to provide additional info for the place marked. For example the code bellow will add a balloon on the Acropolis Hill and display some information:
function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(37.97110, 23.72601), 13);
var html = "Parthenon, Address: Acropolis Hill";
map.openInfoWindow(map.getCenter(),
document.createTextNode(html));
map.setUIToDefault();
}
}
Active Markers
We can combine markers and balloons to create an active marker that will display the balloon only when a user clicks on the marker. The code to do this is:
function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(37.97918, 23.71665), 13);
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
function createMarker(point, index) {
var redIcon = new GIcon(baseIcon);
redIcon.image = "http://www.google.com/mapfiles/marker.png";
markerOptions = { icon:redIcon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml("Parthenon, Address: Acropolis Hill");
});
return marker;
}
var latlng = new GLatLng(37.97110, 23.72601);
map.addOverlay(createMarker(latlng));
}
}
Lets go over the code again. This part adds a shadow bellow our marker:
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
We set the action of the marker here:
function createMarker(point, index) {
var redIcon = new GIcon(baseIcon);
redIcon.image = "http://www.google.com/mapfiles/marker.png";
markerOptions = { icon:redIcon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml("Parthenon, Address: Acropolis Hill");
});
return marker;
}
Here is where our marker will be:
var latlng = new GLatLng(37.97110, 23.72601);
map.addOverlay(createMarker(latlng));
Loading a map
We can load a map with 2 ways. We can set the map to load as soon as our page is loaded using the body onload event, or we can assign the loading process to another event. Either way, the functions we need are:
- initialize() To load the map
- GUnload() To unload the map and free some memory used by the map.
We also need to add a div layer (any block element will do the work) assigned the id used by the JavaScript code (In our example “map_canvas”). We can also apply CSS rules to the layer.
Customizing your Maps
You can use custom icons for markers and shadows. Two great tools for creating your own icons can be found here and here. You can also customize the appearance of balloons using HTML and CSS. You should properly escape quotes (“s and ’s) though.
Adding multiple markers and grouping them
We can mark multiple locations on our maps and group them according to our needs. So, we can set our map to display different marker icons for hotels based on their category, we can set an icon with a building to help our users identify buildings of interest or another icon for bridges. To do this, we have to use an XML file.A simple XML file looks like this:
<markers>
<marker name="Your Title here" label="This is the label of the marker" desc="Description of the balloon" lat="37.97167" lng="23.72581" type="Here we set the marker's type. For example Bridge" address="The address here" icona="We place an image path here"/>
</markers>
You can add as many markers as you want in the file. One thing you should be very aware of, is that you must escape special chars like quotes and double quotes, and “#@$<>” for your titles, and your links should be escaped too. The JavaScript needed is:
<script src="https://gmaps-utility-library.googlecode.com/svn/trunk/labeledmarker/release/src/labeledmarker.js" type="text/javascript"></script>
and we also set some parameters:
var iconRed = new GIcon();
iconRed.image = '../img/marker-red.png';
iconRed.shadow = '';
iconRed.iconSize = new GSize(32, 32);
iconRed.shadowSize = new GSize(22, 20);
iconRed.iconAnchor = new GPoint(16, 16);
iconRed.infoWindowAnchor = new GPoint(5, 1);
var customIcons = [];
customIcons["ancient"] = iconRed;
var markerGroups = { "ancient": []};
So we set the customIcons property for “ancient” to iconRed and we should also use this type (ancient) in our XML file. If we named our XML file as markers.xml, then we should use this code:
GDownloadUrl("markers.xml", function(data) { //We tell Google Maps to load our file
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker"); //and read markers
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name"); //From here down we assign variables.
var label = markers[i].getAttribute("label");
var desc = markers[i].getAttribute("desc");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var icona = markers[i].getAttribute("icona");
var point = new GlatLng(parseFloat(markers[i].getAttribute("lat")), //and we set the lat-long
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, name, label, desc, address, type, icona);
map.addOverlay(marker);
}
});
}
}
function createMarker(point, name, label, desc, address, type, icona) {
var marker = new LabeledMarker(point, {icon: customIcons[type], labelText: label, labelOffset: new GSize(-6, -8)})};
You can play with the GSize() function’s parameters and set the label of each marker to be in the marker’s borders. To Group the markers we need to do this:
markerGroups[type].push(marker);
var html = "<img src=" + icona + " height=150 border=0 /><br><br><span><b>"+ name + "</b><br/>" +
desc + "<br/><b>Address:</b> " + address + "<br/><br/><span>";
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
To set different icons based on interest you can do it using the same method described above with some variations. For each icon we use this code:
var iconRed = new GIcon();
iconRed.image = '../img/marker-red.png';
iconRed.shadow = '';
iconRed.iconSize = new GSize(32, 32);
iconRed.shadowSize = new GSize(22, 20);
iconRed.iconAnchor = new GPoint(16, 16);
iconRed.infoWindowAnchor = new GPoint(5, 1);
var iconGreen = new GIcon();
iconGreen.image = '../img/marker-green.png';
iconGreen.shadow = '';
iconGreen.iconSize = new GSize(32, 32);
iconGreen.shadowSize = new GSize(22, 20);
iconGreen.iconAnchor = new GPoint(16, 16);
iconGreen.infoWindowAnchor = new GPoint(5, 1);
var iconBrown = new GIcon();
iconBrown.image = '../img/marker-brown.png';
iconBrown.shadow = '';
iconBrown.iconSize = new GSize(32, 32);
iconBrown.shadowSize = new GSize(22, 20);
iconBrown.iconAnchor = new GPoint(16, 16);
iconBrown.infoWindowAnchor = new GPoint(5, 1);
var customIcons = [];
customIcons["hotel"] = iconRed;
customIcons["bridge"] = iconGreen;
customIcons["hill"] = iconBrown;
var markerGroups = { "hotel": [], "bridge": [], "hill": []};
So, if we set the type of each marker in our XML file as hotel,bridge and hill, we also set a different color for each icon.
Making our markers more dynamic
We can make our markers a little bit more user friendly. We can let the user decide which marker to show or hide using events from buttons, checkboxes or links.To do this you should add the following code right after the “map.addMapType(G_SATELLITE_3D_MAP); ” part:
document.getElementById("hotelCheckbox").checked = true;
document.getElementById("bridgeCheckbox").checked = true;
document.getElementById("hillCheckbox").checked = true;
document.getElementById("labelsCheckbox").checked = true;
and at the end of the JavaScript code you add this:
function toggleGroup(type) {
for (var i = 0; i < markerGroups[type].length; i++) {
var marker = markerGroups[type][i];
if (marker.isHidden()) {
marker.show();
} else {
marker.hide();
}
}
}
function toggleLabels() {
var showLabels = document.getElementById("labelsCheckbox").checked;
for (groupName in markerGroups) {
for (var i = 0; i < markerGroups[groupName].length; i++) {
var marker = markerGroups[groupName][i];
marker.setLabelVisibility(showLabels);
}
}
}
function hideAll() {
var boxes = document.getElementsByName("mark");
for(var i = 0; i < boxes.length; i++) {
if(boxes[i].checked) {
boxes[i].checked = false;
switchLayer(false, layers[i].obj);
chosen.push(i);
}
}
}
function checkChecked() {
var boxes = document.getElementsByName("mark");
for(var i = 0; i < boxes.length; i++) {
if(boxes[i].checked) return true;
}
return false;
}
The last thing to do is to add the checkbox elements on your page:
<input type="hidden" id="labelsCheckbox" onclick="toggleLabels()" checked=”checked” />
<label for=”hotelCheckbox”>Hotels</label><input type="checkbox" id="hotelCheckbox" onclick="toggleGroup('hotel')" checked=”checked” />
<label for=”bridgeCheckbox”>Bridges</label><input type="checkbox" id="bridgeCheckbox" onclick="toggleGroup('bridge')" checked=”checked” />
Our Google Maps are ready. I hope you to find this article helpful. We covered a big part of the Google Maps API and you should now be able to add Google Maps to your sites, place markers in groups and let the users choose which markers should be visible and which shouldn’t.
Read More