ACME Updates

13aug2018 Converting *Your* Google Maps to Leaflet

If you have a Google Maps API page that is suddenly costing you real money, and you want to switch to Leaflet like I did, here's how!

First, go to the Leaflet.js page and bookmark it. You will be referencing it a lot.

The Leaflet page has a section called Tutorials, and the first tutorial is called Leaflet Quick Start Guide. It's a nice simple guide to making your first Leaflet map. Read through it. Work the examples.

As part of making your example map, you'll be opening a Mapbox account to get an access token. Mapbox provides Leaflet-compatible map tiles as a commercial service Their rates and free usage level are lower than Google's new ones, but higher than Google's old ones. Better, but still expensive. You should consider them a temporary tile provider just to get things working.

Once you have an example map going, you are ready to start converting your real map. Make a copy of your HTML & JS and start editing them. First change the HTML part. You will need to add the Leaflet CSS stylesheet to the <head> of your document. And you will need to change the Google Maps API JavaScript library load into the Leaflet JavaScript library load. Both of these lines can be copied from your example map.

Now start looking through your JavaScript for anywhere the string "google" appears. Use the Leaflet docs page to figure out the Leaflet equivalent. Usually it's pretty obvious.

Here are some examples of Google to Leaflet conversions:

Google Maps API Leaflet.js
map = new google.maps.Map( div, options ); map = L.map( div, options );
google.maps.event.addListener( map, 'click', ClickHandler ); map.on( 'click', ClickHandler );
ll = new google.maps.LatLng( lat, lng ); ll = L.latLng( lat, lng );
map.setCenter( ll ); map.panTo( ll );
marker = new google.maps.Marker( { position: ll, map: map } ); marker = L.marker( ll ).addTo( map );
new google.maps.Polyline( { map: map, path: points, strokeColor: color } ); L.polyline( points, { color: color } ).addTo( map );

When you run out of "google" stuff to convert, give your map a try. But first, open up your browser's JavaScript Console. You can probably find it in a menu under "developer tools" or something like that. The JS console is where you will find errors to fix. The errors will be things like "undefined" or "no such method". The error message will tell you what line of your file is the problem. Go look at that line, consult the Leaflet docs, figure out what's wrong. Keep fixing errors and doing a Reload until you run out of errors and your map works.

Once you have your map going, it's time to re-visit your choice of tile provider. As mentioned previously, Mapbox is still kind of expensive. This Providers Preview page lets you try out a whole bunch of basemaps and overlays. Look through them and pick one you like. The page gives you a JavaScript snippet that you can paste right into your code.

Back to ACME Updates.