Google Maps Example

From OpenStreetMap Wiki
Jump to: navigation, search
Available languages — Google Maps Example
Afrikaans Alemannisch aragonés asturianu azərbaycanca Bahasa Indonesia Bahasa Melayu Bân-lâm-gú Basa Jawa Baso Minangkabau bosanski brezhoneg català čeština dansk Deutsch eesti English español Esperanto estremeñu euskara français Frysk Gaeilge Gàidhlig galego Hausa hrvatski Igbo interlingua Interlingue isiXhosa isiZulu íslenska italiano Kiswahili Kreyòl ayisyen kréyòl gwadloupéyen kurdî latviešu Lëtzebuergesch lietuvių magyar Malagasy Malti Nederlands Nedersaksies norsk norsk nynorsk occitan Oromoo oʻzbekcha/ўзбекча Plattdüütsch polski português português do Brasil română shqip slovenčina slovenščina Soomaaliga suomi svenska Tiếng Việt Türkçe Vahcuengh vèneto Wolof Yorùbá Zazaki српски / srpski беларуская български қазақша македонски монгол русский тоҷикӣ українська Ελληνικά Հայերեն ქართული नेपाली मराठी हिन्दी অসমীয়া বাংলা ਪੰਜਾਬੀ ગુજરાતી ଓଡ଼ିଆ தமிழ் తెలుగు ಕನ್ನಡ മലയാളം සිංහල ไทย မြန်မာဘာသာ ລາວ ភាសាខ្មែរ ⵜⴰⵎⴰⵣⵉⵖⵜ አማርኛ 한국어 日本語 中文(简体)‎ 吴语 粵語 中文(繁體)‎ ייִדיש עברית اردو العربية پښتو سنڌي فارسی ދިވެހިބަސް

The examples on this page demonstrate how to embed OpenStreetMap tiles as a layer within a Google Map (i.e. using the Google Maps JavaScript library for map display, but displaying OpenStreetMap map tiles).

This is one of several approaches for deploying your own Slippy Map. Many developers working with OpenStreetMap will prefer to use Leaflet or OpenLayers, since they are more in-keeping with the OSM ethos, but there are plenty of reasons why you might want or need to use the Google Maps JavaScript. For example you may have invested a lot in building a Google Maps interface (logic for showing overlays, click handling etc). In this case, it's still easy enough to just swap in OpenStreetMap as the map tile provider, or offer it as one possible basemap layer in your application.

Example Using Google Maps API V3

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Google Maps v3 API Example</title>
        <style>
            html, body, #map {
                height: 100%;
                width: 100%;
                margin: 0;
                padding: 0;
            }
            div#footer {
                position: fixed;
                left: 0;
                right: 0;
                bottom: 0;
                width: 100%;
                height: 18px;
                margin: 0;
                padding: 6px;
                z-index: 2;
                background: WHITE;
            }
        </style> 
    </head>
    <body>
        <div id="map" style="float: left;"></div>
        
        <div id="footer">&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors</div>
        
        <!-- bring in the google maps library -->
        <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
        
        <script type="text/javascript">
            //Google maps API initialisation
            var element = document.getElementById("map");
 
            var map = new google.maps.Map(element, {
                center: new google.maps.LatLng(57, 21),
                zoom: 3,
                mapTypeId: "OSM",
                mapTypeControl: false,
                streetViewControl: false
            });
 
            //Define OSM map type pointing at the OpenStreetMap tile server
            map.mapTypes.set("OSM", new google.maps.ImageMapType({
                getTileUrl: function(coord, zoom) {
                    // "Wrap" x (longitude) at 180th meridian properly
                    // NB: Don't touch coord.x: because coord param is by reference, and changing its x property breaks something in Google's lib
                    var tilesPerGlobe = 1 << zoom;
                    var x = coord.x % tilesPerGlobe;
                    if (x < 0) {
                        x = tilesPerGlobe+x;
                    }
                    // Wrap y (latitude) in a like manner if you want to enable vertical infinite scrolling

                    return "https://tile.openstreetmap.org/" + zoom + "/" + x + "/" + coord.y + ".png";
                },
                tileSize: new google.maps.Size(256, 256),
                name: "OpenStreetMap",
                maxZoom: 18
            }));
        </script>
    </body>
</html>

See it running here

Example - Using Google Maps API v3 setting OSM as a base map layer

This example adds OpenStreetMap as a default Google Maps base layer. Note that you need to set maxZoom in the ImageMapType for it to work as a base layer. The Apple-specific meta tag enables full screen operation when started as a web application on an iPhone or iPad.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <title>OpenStreetMap with Google Maps v3 API</title>
        <style type="text/css">
            html, body, #map {
                height: 100%;
                margin: 0;
                padding: 0;
            }
        </style>
    </head>
    <body>
        <div id="map"></div>

        <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
        <script type="text/javascript">
            var element = document.getElementById("map");

            /*
            Build list of map types.
            You can also use var mapTypeIds = ["roadmap", "satellite", "hybrid", "terrain", "OSM"]
            but static lists suck when Google updates the default list of map types.
            */
            var mapTypeIds = [];
            for(var type in google.maps.MapTypeId) {
                mapTypeIds.push(google.maps.MapTypeId[type]);
            }
            mapTypeIds.push("OSM");

            var map = new google.maps.Map(element, {
                center: new google.maps.LatLng(48.1391, 11.5802),
                zoom: 11,
                mapTypeId: "OSM",
                mapTypeControlOptions: {
                    mapTypeIds: mapTypeIds
                }
            });

            map.mapTypes.set("OSM", new google.maps.ImageMapType({
                getTileUrl: function(coord, zoom) {
                    // See above example if you need smooth wrapping at 180th meridian
                    return "https://tile.openstreetmap.org/" + zoom + "/" + coord.x + "/" + coord.y + ".png";
                },
                tileSize: new google.maps.Size(256, 256),
                name: "OpenStreetMap",
                maxZoom: 18
            }));
        </script>
    </body>
</html>

Example Using Google Maps API V2 (marked as Deprecated by Google )

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>OpenStreetMap</title>
  <meta http-equiv="content-type" content="text/html; charset=utf-8"/>

  <script src="https://maps.google.com/maps?file=api&amp;v=2&amp;key=YOUR_KEY_HERE" type="text/javascript"></script>
  <script type="text/javascript">
  //<![CDATA[

  function load()
  {
    if (!GBrowserIsCompatible())
        return;

    var copyOSM = new GCopyrightCollection("<a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a>");
    copyOSM.addCopyright(new GCopyright(1, new GLatLngBounds(new GLatLng(-90,-180), new GLatLng(90,180)), 0, " "));

    var tilesMapnik     = new GTileLayer(copyOSM, 1, 17, {tileUrlTemplate: 'https://tile.openstreetmap.org/{Z}/{X}/{Y}.png'});
    var tilesOsmarender = new GTileLayer(copyOSM, 1, 17, {tileUrlTemplate: 'https://tah.openstreetmap.org/Tiles/tile/{Z}/{X}/{Y}.png'});

    var mapMapnik     = new GMapType([tilesMapnik],     G_NORMAL_MAP.getProjection(), "Mapnik");
    var mapOsmarender = new GMapType([tilesOsmarender], G_NORMAL_MAP.getProjection(), "Osmarend");
    var map           = new GMap2(document.getElementById("map"), { mapTypes: [mapMapnik, mapOsmarender] });

    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter( new GLatLng(55.95, -3.19), 13);
  }

  //]]>
  </script>
</head>
<body onload="load()" onunload="GUnload()">

<div id="map" style="width: 600px; height: 600px; border:1px solid gray;"></div>

</body>
</html>

Notes

Prior to embedding this map (V2) in a web page, you should replace YOUR_KEY_HERE with your Google Maps API key. You'll need to generate one.


Google maps via Mapstraction

Mapstraction is a JavaScript library providing an abstraction layer across JavaScript map libraries. Google Maps is supported and can be invoked with OSM tiles. This means you're not coding against the Google Maps API, but against the Mapstraction API instead, but it then allows you to make a switch to another library.


More examples

The following are a few examples of people using Google Maps API with OpenStreetMap.

Related links