So, we have now started to improve the layout a little bit. However, the map is still fundamentally the same. The next thing we will do is to add some markers. This should be relatively straightforward as I've already got you to do this in Unit 2. However, we'll go into a little more detail here.
To create a Marker, we use the google.maps.Marker
. An example of this is given below:
var marker = new google.maps.Marker(
{
position: latlng,
map: map,
title:"Hello World!"
}
);
The process for adding a marker is fairly simple: we create a new instance
of the Marker()
object, and supply various properties:
position
– where the marker is to be locatedmap
– the name of the map object on which to place the new
marker title
– a title that will be seen when we move the mouse
over the markerThese properties are supplied using the JSON '{key: value}
' object notation:
the Marker()
initialization method takes one parameter, but that parameter is an object with
multiple properties.
Assuming the example code above integrates into our map,
we'd be using the same latlng
variable that was created to
centre the map. If we wanted to use a different location, we
could create an additional LatLng
type object, and use that instead. The second
property is the potentially confusing 'map: map
'. The first term
here – 'map:
' – indicates the property (of the
Marker()
object) that we are setting. Its parameter (the second
'map
') refers to the name of the google.maps.Map()
object that we
created in the line:
var map = new
google.maps.Map(document.getElementById("map_canvas"),myOptions);
Note
that the text supplied for the title
property is a string object,
and must be placed in quotes.
Without looking at the code for the marker we created in the first tutorial, can you put the above code in the correct place in your html file? Now assume that you wish to add a second marker. How would you do this?
Before you begin, save a copy of your work!
Creating a single marker (which so far, will not do anything useful, other than display itself on the map) is of limited value – what we need to do is to attach some information to the marker, and then look towards creating multiple markers, each with information attached.
However, before we do that it would be useful to re-consider the code of the example. It is growing in length, and now would be a good time to restore some order!