Google Maps

Adding a Marker

More of this Tutorial

Get an API Adding a Map Zooming In and Out Latitude and Longitude Adding a Description Visitor Move/Zoom Satellite Images Multiple Maps

It would of course be much easier to see the centre of the map if we actually add a marker to the map that points to that exact spot. Without a marker we can only estimate where the centre of the map is or use a tool such as the measureIt add-on for Firefox to attempt to measure where the centre is. Google have made it really easy to add all the markers we like to the map, all we need to do is to add one extra line of code.

map.addOverlay(new GMarker(
continued from previous linenew GLatLng(-33.9417, 150.9473)));

Of course this is duplicating the GLatLng function call that we already have to define the centre of the map and so rearranging our code a little to store the position into a variable so that we can reuse it without having to call the function multiple times will improve the efficiency of our code. Let's assign the position to a variable so that we can reference it in both the centre and overlay marker statements without duplicating the function call.

var point = new GLatLng(-33.9417, 150.9473);
map.setCenter(point, 10);
var marker = new GMarker(point);

We now have only one call to each function. The setting up of a separate variable to contain the marker isn't strictly necessary for this code but will make adding things to the marker easier as we will see in the next tutorial.

Whichever way we add the code our map showing where I live now looks like this:

Of course you can always add additional markers to your map simply by replicating our first overlay marker statement and specifying the latitude and longitude where we want each of those markers to appear. In those instances there will be multiple calls to the same functions but the values passed into the functions will be different meaning that the calls will not be duplicates.

People will be able to tell more easily what a marker is for if we add a description.