Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Leaflet plugin that enables the use of Google Map tiles - http://matchingnotes.com/using-google-map-tiles-with-leaflet
/*
* L.TileLayer is used for standard xyz-numbered tile layers.
*/
L.Google = L.Class.extend({
includes: L.Mixin.Events,
options: {
minZoom: 0,
maxZoom: 18,
tileSize: 256,
subdomains: 'abc',
errorTileUrl: '',
attribution: '',
opacity: 1,
continuousWorld: false,
noWrap: false,
},
// Possible types: SATELLITE, ROADMAP, HYBRID
initialize: function(type, options) {
L.Util.setOptions(this, options);
this._type = google.maps.MapTypeId[type || 'SATELLITE'];
},
onAdd: function(map, insertAtTheBottom) {
this._map = map;
this._insertAtTheBottom = insertAtTheBottom;
// create a container div for tiles
this._initContainer();
this._initMapObject();
// set up events
map.on('viewreset', this._resetCallback, this);
this._limitedUpdate = L.Util.limitExecByInterval(this._update, 150, this);
map.on('move', this._update, this);
//map.on('moveend', this._update, this);
this._reset();
this._update();
},
onRemove: function(map) {
this._map._container.removeChild(this._container);
//this._container = null;
this._map.off('viewreset', this._resetCallback, this);
this._map.off('move', this._update, this);
//this._map.off('moveend', this._update, this);
},
getAttribution: function() {
return this.options.attribution;
},
setOpacity: function(opacity) {
this.options.opacity = opacity;
if (opacity < 1) {
L.DomUtil.setOpacity(this._container, opacity);
}
},
_initContainer: function() {
var tilePane = this._map._container
first = tilePane.firstChild;
if (!this._container) {
this._container = L.DomUtil.create('div', 'leaflet-google-layer leaflet-top leaflet-left');
this._container.id = "_GMapContainer";
}
if (true) {
tilePane.insertBefore(this._container, first);
this.setOpacity(this.options.opacity);
var size = this._map.getSize();
this._container.style.width = size.x + 'px';
this._container.style.height = size.y + 'px';
}
},
_initMapObject: function() {
this._google_center = new google.maps.LatLng(0, 0);
var map = new google.maps.Map(this._container, {
center: this._google_center,
zoom: 0,
mapTypeId: this._type,
disableDefaultUI: true,
keyboardShortcuts: false,
draggable: false,
disableDoubleClickZoom: true,
scrollwheel: false,
streetViewControl: false
});
var _this = this;
this._reposition = google.maps.event.addListenerOnce(map, "center_changed",
function() { _this.onReposition(); });
map.backgroundColor = '#ff0000';
this._google = map;
},
_resetCallback: function(e) {
this._reset(e.hard);
},
_reset: function(clearOldContainer) {
this._initContainer();
},
_update: function() {
this._resize();
var bounds = this._map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
var google_bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(sw.lat, sw.lng),
new google.maps.LatLng(ne.lat, ne.lng)
);
var center = this._map.getCenter();
var _center = new google.maps.LatLng(center.lat, center.lng);
this._google.setCenter(_center);
this._google.setZoom(this._map.getZoom());
//this._google.fitBounds(google_bounds);
},
_resize: function() {
var size = this._map.getSize();
if (this._container.style.width == size.x &&
this._container.style.height == size.y)
return;
this._container.style.width = size.x + 'px';
this._container.style.height = size.y + 'px';
google.maps.event.trigger(this._google, "resize");
},
onReposition: function() {
//google.maps.event.trigger(this._google, "resize");
}
});
@spatialbits

This comment has been minimized.

Copy link

commented Apr 18, 2013

Very handy plugin, Crofty. Thanks!
I'm pretty new to GitHub and web dev in general so I could very easily be wrong here, but there seems to be a trailing comma on line 16 of leaflet-google.js that IE doesn't like.

@cihadturhan

This comment has been minimized.

Copy link

commented Jul 10, 2013

I'm trying make this code run with leaflet-google.js but I couldn't make it.

https://developers.google.com/maps/documentation/javascript/examples/maptype-styled-simple

Can anyone help me about this issue?

@yellowcap

This comment has been minimized.

Copy link

commented Sep 20, 2013

This has been very useful for my work, thanks Crofty!
Its a small detail, but I think there is a trailing comma on line 16
https://gist.github.com/crofty/2197042#file-leaflet-google-js-L16

@chmartinez

This comment has been minimized.

Copy link

commented Dec 3, 2013

Great post!
I used it with Leaflet draw, but when I drawn new features on the OSM layer, I could not see them when swtiching to the Google Layer.. Maybe something related to the z-index? Any thoughts?

@notasausage

This comment has been minimized.

Copy link

commented Mar 12, 2014

Just for the record, I used this bit of code with a little more customization in a client site running on Statamic, the static file CMS. Statamic has location stuff built-in but uses Cloudmade for map tiles, and my client wanted Google Maps. So I plugged this into Statamic with a little work and now the CMS is using Google tiles instead of Cloudmade.

http://esplanadetravel.com

@hxgf

This comment has been minimized.

Copy link

commented Apr 2, 2014

righteous. thank you, sir.

btw, i had a similar issue to @chmartinez (my markers were being covered by the google tiles). it's easy to fix layer issues with css like so:

.leaflet-google-layer{
    z-index: 0;
}
.leaflet-map-pane{
    z-index: 100;
}
@snario

This comment has been minimized.

Copy link

commented Apr 21, 2014

I have an issue where I want to add a native Google control (for example the pegman), so in mapOptions I set the street view property to true and the pegman is visible but I can't click on him. Same thing with any other UI like zoom or panning; they are visible but not clickable. Does anyone know how to fix this? I have tried to order the z-index properties many times but no luck.

Thanks

Here is a fiddle of what I mean:

http://jsfiddle.net/fJFWN/34/

@cballou

This comment has been minimized.

Copy link

commented May 23, 2014

I noticed that even if you try to add the Google Map to the bottom layer, it still applies it to the top: map.addLayer(googleLayer, true); This would appear to be a bug. The workaround is as @jyoungblood mentioned, with one caveat.

.leaflet-google-layer{
    z-index: 0 !important;
}
.leaflet-map-pane{
    z-index: 100;
}
@jbhatab

This comment has been minimized.

Copy link

commented Jun 29, 2014

Thought I'd post this because it was useful to me. Here's a minimal setup of a coffeescript file that initializes the map with the google layer.

$ ->
map = L.map("map").setView([51.505, -0.09], 13)
googleLayer = new L.Google("ROADMAP")
map.addLayer googleLayer

@trusktr

This comment has been minimized.

Copy link

commented Apr 13, 2015

@yellowcap

I think there is a trailing comma on line 16

Trailing commas are fine in JavaScript. In an object literal the trailing comma doesn't do anything, but in an Array it does (the array length is longer depending on how many trailing commas you have).

@trusktr

This comment has been minimized.

Copy link

commented Apr 13, 2015

@crofty Have you used this with overlays (polygons, geojson, etc)? If so, do the overlays move in sync with the map?

@ShirtlessKirk

This comment has been minimized.

Copy link

commented Jun 29, 2015

Whether a trailing comma is valid JavaScript is irrelevant. Old IE doesn't like it. End of.

FWIW it isn't valid JSON for that matter.

@palaniyappan

This comment has been minimized.

Copy link

commented Sep 29, 2015

Try the below option for click option not visible in the map :

this._container = L.DomUtil.create('div', 'leaflet-google-layer leaflet-top leaflet-left');

change to -->

this._container = L.DomUtil.create('div', 'leaflet-google-layer);

@asotoopensky

This comment has been minimized.

Copy link

commented Oct 1, 2015

Hi all,

I'm creating a map and i'm trying to add a tile layer with Leaflet 1.0.0 Beta, this is my code:

var myCenter = new L.LatLng(50.5, 30.51);
var map = new L.Map('map', {center: myCenter, zoom: 15});
var positron = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {});
map.addLayer(positron);

It works perfectly, but when i try to add a Google Layer with Leaflet Google library(http://matchingnotes.com/javascripts/leaflet-google.js) doesn't work:



var map = new L.Map('map', {center: myCenter, zoom: 15});
var ggl = new L.Google();
   map.addLayer(ggl);

after that i tried to change the version of Leaflet to 0.7.5 and worked perfectly. I need to use Leaflet 1.0.0 Beta because of some features so i can't just change the version on my project.

Check an example in:
http://jsbin.com/nafoloxade/edit?html,console,output

Please could you help me with this?

@fbazbo

This comment has been minimized.

Copy link

commented Nov 17, 2015

@palaniyappan, the change to make the google commands clickable worked, but how would you bypass the map drag while dragging the street view icon?

Never mind, figured it out myself doing something like:

    google.maps.event.addListenerOnce(map, 'idle', function(){
        var pegman = $("div[aria-label='Street View Pegman Control']");
        if (pegman) {
          pegman
            .mousedown(function() {
                _this._disableLeafletDrag();
            })
            .mouseup(function() {
                _this._enableLeafletDrag();
            });
        }
        google.maps.event.addListener(map.getStreetView(),'visible_changed',function(){
            if (!this.getVisible()) {
                _this._enableLeafletDrag();
            }
        });
    });
@FonMaestro

This comment has been minimized.

Copy link

commented Apr 15, 2016

@snario do you fix your issue?

I have a similar problem. I set the street view property to true in MapOptions. The pegman is visible but I can't click on him. I try to reorder layers with z-index but doesn't work.

Thank you

@S767

This comment has been minimized.

Copy link

commented Jul 4, 2016

Due new version on Leaflet you need to change
some extra lines to this plugin for working with out JS error
L.Google = L.Layer.extend within L.Google = L.Class.extend

and comment string
this._limitedUpdate = L.Util.limitExecByInterval(this._update, 150, this);

@artamonovdev

This comment has been minimized.

Copy link

commented Jul 13, 2016

@S767, thank you very much!

@catbadger

This comment has been minimized.

Copy link

commented Aug 26, 2016

What version does this code apply to? Not the current one.

@thecristen

This comment has been minimized.

Copy link

commented Oct 7, 2016

Unfortunately I can't get this to work with https://github.com/consbio/Leaflet.Basemaps

@OutThisLife

This comment has been minimized.

Copy link

commented Jan 13, 2017

Very laggy.

@geozoone

This comment has been minimized.

Copy link

commented Jan 13, 2017

anybody get this work with leaflet 1.0.2 ?

@mikhailir

This comment has been minimized.

@Goury

This comment has been minimized.

Copy link

commented Mar 16, 2017

Please fix the URL, correct one should be http://www.matchingnotes.com/using-google-map-tiles-with-leaflet.html
Your returns 404
Also user HTTPS please.

Also this is not working anymore.

@ihssan

This comment has been minimized.

Copy link

commented Aug 10, 2017

I want use google direction

@Oakwv

This comment has been minimized.

Copy link

commented Jan 2, 2018

Does anyone have a working jsfiddle with pegman dragable? I have him visible but nothing happens when I click . Leafelt 1.2.0 GridLayer.GoogleMutant 0.6.4 thanks in advance.

@bernhardreiter

This comment has been minimized.

Copy link

commented Aug 26, 2019

License Status

Note on the license status of this file.
As indicated on (the archive page) https://web.archive.org/web/20180728014324/http://matchingnotes.com/using-google-map-tiles-with-leaflet @crofty has started with https://web.archive.org/web/20180728014324/http://psha.org.ru/leaflet/Google.js which got imported into
https://raw.githubusercontent.com/shramov/leaflet-plugins/ on 2019-04-18.

The difference to the initially imported file from @shramov shows that @crofty has only made a very small change
which very likely is not copyrightable, see the change:

curl
https://raw.githubusercontent.com/shramov/leaflet-plugins/6b13ac67aacbb3d46df5e78905f836cacb31b86a/layer/tile/Google.js
-o Google-20120418shramov.js 

curl -O
https://gist.githubusercontent.com/crofty/2197042/raw/235e1842856de77035cfc69e8abb42cd7e3793d2/leaflet-google.js
leaflet-google-2012crofty.js
diff -U0 Google-20120418shramov.js leaflet-google-2012crofty.js
--- Google-20120418shramov.js   2019-08-26 11:38:37.062456529 +0200
+++ leaflet-google-2012crofty.js        2019-08-26 11:00:35.545241651 +0200
@@ -4 +3,0 @@
-
@@ -81,2 +80,2 @@
-                       this._container.style.width = size.x;
-                       this._container.style.height = size.y;
+                       this._container.style.width = size.x + 'px';
+                       this._container.style.height = size.y + 'px';
@@ -139,2 +138,2 @@
-               this._container.style.width = size.x;
-               this._container.style.height = size.y;
+               this._container.style.width = size.x + 'px';
+               this._container.style.height = size.y + 'px';

Thus we can conclude that the 99% of the file the rights will be with @shramov.
He placed the files in the github repository under MIT on 2012-07-31 (see shramov/leaflet-plugins@39cd5da#diff-9879d6db96fd29134fc802214163b95a) , which included an improved Google.js file, which still is quite similar. If we assume that this clarification in July 2012 was meant for earlier versions of the file as well, then this file is most likely copyright @shramov under MIT.

@shramov

This comment has been minimized.

Copy link

commented Aug 30, 2019

Thx for pointing. Yes, that's based on my script. Later it was dropped from leaflet-plugins since there is better version: shramov/leaflet-plugins#250

@bernhardreiter

This comment has been minimized.

Copy link

commented Aug 30, 2019

@shramov thanks for the clarification!

Note that the problem with the new "version" is that it is not properly licensed so far, see https://gitlab.com/IvanSanchez/Leaflet.GridLayer.GoogleMutant/issues/102

@shramov

This comment has been minimized.

Copy link

commented Aug 30, 2019

Licence for this script is really minor issue compared to debatable status of whole plugin - is it legal to use Google maps this way or not :)

@bernhardreiter

This comment has been minimized.

Copy link

commented Aug 30, 2019

@shramov unfortunately those are two different questions, which are both important.

  • As we are using Free Software in a commercial setting, the current Leaflet.GridLayer.GoogleMutant will not pass any serious licensing clearing house (precisely there is no permission to use it, because the license of you and Bergot is violated).
  • When using the Google Maps API with a key, a number of people evaluated this as acceptable. But this is a matter between different parties: google and the organisation that bought the api key from them. Maybe this should or is discussed in more depth somewhere else?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.