Wednesday, November 3, 2021

Google base Maps in LeafletJS

 LeafletJS web map supports not just open source basemaps but also other preparatory basemaps such as Google maps and ESRI maps.

In this post, we shall see how to add varying flavors of Google basemaps.



The code below was inspired by this stackoverflow question.

<!DOCTYPE html>
<html>
<head>
	
	<title>Leaflet Map...</title>

	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	
	<!-- <link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" /> -->

    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin=""/>

    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>

	
</head>
<body>


<div id="mapid" style="width: 100%; height: 600px;"></div>



<script>
	// Create the map obj...
	var mymap = L.map('mapid', {minZoom: 2, maxZoom: 20})
				 .setView([0, 0], 2);


	// Restrict panning to this bounds
	var southWest = L.latLng(-90, -180),
		northEast = L.latLng(90, 180);
	var bounds = L.latLngBounds(southWest, northEast);

	mymap.setMaxBounds(bounds);


	// Set a default base map to...
    L.tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{
        // minZoom: 0,
     	maxZoom: 18,
        subdomains:['mt0','mt1','mt2','mt3']
    }).addTo(mymap);



// CREATE GOOGLE MAP LAYER
	// 1- Streets...
	googleStreets = L.tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{
	    maxZoom: 20,
	    subdomains:['mt0','mt1','mt2','mt3']
	});


	// 2- Hybrid...
	googleHybrid = L.tileLayer('http://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}',{
	    maxZoom: 20,
	    subdomains:['mt0','mt1','mt2','mt3']
	});


	// 3- Satellite...
	googleSat = L.tileLayer('http://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}',{
	    maxZoom: 20,
	    subdomains:['mt0','mt1','mt2','mt3']
	});



	// 4- Terrain...
	googleTerrain = L.tileLayer('http://{s}.google.com/vt/lyrs=p&x={x}&y={y}&z={z}',{
	    maxZoom: 20,
	    subdomains:['mt0','mt1','mt2','mt3']
	});



var overlayMaps = {
    // Other layers will go here....
};



var baseLayers = {
	'Google Street Map':googleStreets,
	'Google Hybrid Map':googleHybrid,
	'Google Satellite Map':googleSat,
	'Google Terrain Map':googleTerrain,
};

// Adding baseMaps and overlayMaps
L.control.layers(baseLayers, overlayMaps, {collapsed: false}).addTo(mymap);


</script>



</body>
</html>

That is it!

No comments:

Post a Comment