The Mappr project used Google Maps JavaScript API V3 to create a dynamic map onto which Flickr’s geotagged photos could be added. (See A Better Way to Map Photos.) But just because you’re using the Google API doesn’t mean you’re limited to Google maps. They make it easy to include other maps, the best of which is from the OpenStreetMap Foundation.

The OpenStreetMap project offers geographical data free of use. They are created collaboratively, letting everyone post map data, much the way Wikipedia works. The two samples below aren’t substantially different, other than for the color of the water. Google is on the left; OpenStreetMap is on the right.

The google.maps.Map new constructor has a parameter called mapTypeId which lets you pick which options the user will see. The default choices are ROADMAP and SATELLITE. Google also offers HYBRID and TERRAIN. The following code will create a new object for mapTypeIds.

var mapTypeIds = [];
for (var type in google.maps.MapTypeId) {

We start out with a blank array, then go through whatever settings were in our default (or we could have specified any of the ROADMAP/SATELLITE/HYBRID/TERRAIN choices). Then we add one called OSM (to be defined later).

Now we can call the google.maps.Map new constructor:

map = new google.maps.Map(element, {
  center: new google.maps.LatLng(48.139, 11.580),
  zoom: 11,
  mapTypeId: "OSM",
  mapTypeControlOptions: {mapTypeIds: mapTypeIds}

Here we specify that we want OSM to be the default option, and below it we give it the entire list of map choices. This code is made more confusing by having the parameter mapTypeIds and the object mapTypeIds use the same name, but oh well.

Finally we get around to defining what OSM actually is. The mapTypes.set method will attach our custom map type to the map’s registry. In this example we squeeze a new object directly into the method’s parameter, which includes a function definition right there in the parameter.

map.mapTypes.set("OSM", new google.maps.ImageMapType({
  getTileUrl: function(coord, zoom) {
    return "" + zoom + "/" + coord.x + "/" + coord.y + ".png";
  tileSize: new google.maps.Size(256, 256), 
  name: "OpenStreetMap", 
  maxZoom: 18

That custom function just returns an image of one of the tiles used to draw the world. has a server that just sits there and delivers little images all day, little pieces of its maps. The name parameter lets us pick what to call the choice in the map’s menu. I used “OpenStreetMap,” but you can pick any other text.

You can see this in action in the Mappr application.

Adding OpenStreetMaps to Google Maps

Leave a Reply