Web Maps Lite API Examples
- Simple Map
- Map Controls
- Map Control Positioning
- Custom Map Controls
- Map Markers
- Custom Map Markers
- Draggable Map Markers
- Basic Events
- Info Window
- Polylines and Polygons
- Routing
- Geocoding
- KML and GeoRSS
- Tile overlay
- Sidebars
- Google Wrapper
Custom Map Markers
Your very own icons on a map
Javascript Level: Beginner
In the previous example, we learnt how to put a standard marker on the map. You can make your maps more interesting by using your own images as markers, like this:
Here's the JavaScript for the example:
var cloudmade = new CM.Tiles.CloudMade.Web({key: 'BC9A493B41014CAABB98F0471D759707'});
var map = new CM.Map('cm-example', cloudmade);
var CloudMadeIcon = new CM.Icon();
CloudMadeIcon.image = "/js-api/examples/images/cloudmade.gif";
CloudMadeIcon.iconSize = new CM.Size(76, 93);
CloudMadeIcon.iconAnchor = new CM.Point(22, 83);
var officeLocation = new CM.LatLng(51.50757, -0.1078);
var officeMarker = new CM.Marker(officeLocation, {
title: "CloudMade office in London",
icon: CloudMadeIcon
});
map.setCenter(officeLocation, 15);
map.addOverlay(officeMarker);
Lets see what each bit of the code does:
1. First we set up a new CloudMade Map in the usual way:
var cloudmade = new CM.Tiles.CloudMade.Web({key: 'BC9A493B41014CAABB98F0471D759707'});
var map = new CM.Map('cm-example', cloudmade);
2. Next we create a new CloudMade Icon object:
var CloudMadeIcon = new CM.Icon();
3. Now we assign an image to the icon, the image can be any JPEG, GIF or PNG on your filesystem or on the internet, so be creative.
CloudMadeIcon.image = "/js-api/examples/images/cloudmade.gif";
4. Now set the size of the icon:
CloudMadeIcon.iconSize = new CM.Size(76, 93);
5. Now we specify the offset of the icon. Sometimes you might want your icon to appear directly over a point and sometimes you might want it to be offset from the point. In this example we've offset the icon 22 pixels to the left of the center point and 80 pixels above it:
CloudMadeIcon.iconAnchor = new CM.Point(22, 80);
6. Next we create a LatLng object to hold the co-ordinates of the position we want to centre the map on:
var officeLocation = new CM.LatLng(51.5077, -0.1077);
7. Now we create a Marker object, passing it the LatLng object and a Javascript hash which contains the title of the marker and the Icon object:
var officeMarker = new CM.Marker(officeLocation, {
title: "CloudMade office in London",
icon: CloudMadeIcon
});
8. Now we set the centre of the map to be the location of the office and set the zoom level:
map.setCenter(officeLocation, 15);
9. Finally, we add our marker to the map as an overlay:
map.addOverlay(officeMarker);
Now, stand back and admire your custom marker
Next up, we learn about draggable markers. I can't wait!.