Create a gist now

Instantly share code, notes, and snippets.

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");
}
});

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.

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?

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

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?

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 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 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 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 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 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 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?

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.

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);

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 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();
            }
        });
    });

@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 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);

@S767, thank you very much!

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

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

Very laggy.

anybody get this work with leaflet 1.0.2 ?

Goury 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 commented Aug 10, 2017

I want use google direction

Oakwv 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment