ZOOM Technologies

Networking Blog

Showing India alone on Google Maps

View Demo

For the past few months, our team has been working on a dashboard app in which user statistics are dynamically displayed on an India map. Ironically, the backend programming took just a fraction of the time it took us to make a truly interactive map using Google maps alone.

We looked at a number of commercial mapping solutions, but most of them showed Jammu and Kashmir as disputed territory with the LoC as the actual India border. There was no way we could use that. A few like amCharts, HighCharts did have the actual India map, but the subscription pricing was exorbitant. Another obstacle we encountered was the lack of support for newly carved states like Telangana. We decided to take the Google map route (this was before Google bowled a googly at map users, charging for map clicks!)

Anyway, after much trial and error and the help of numerous anonymous contributors to GitHub and Google Developer Support pages, we managed to show the India map alone on a white background. We used a geoJson file to overlay state polygons on the India map. I wish I could acknowledge the creator of the India geoJson but he / she remains nameless too. Google ji, aap ko hamara salaam!

We modified the file as per our requirements. You may download it here.

Now, without further ado, here’s the source code in javascript. Check out the demo here. Single click on a state lets you zoom in, double click triggers zoom out. The state name appears on the top right if you hover on that state.

Load both the html file and the php file on the same webserver!

	
	< p>IndiaMapAlone.html< /p>
	
	< style>
	
        #map {
            width: 100%;
            height: 100%;
        }
        html,
        body {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
        }
        .nicebox {
            position: absolute;
            text-align: center;
            width: auto;
            font-family: "Roboto", "Arial", sans-serif;
            font-size: 13px;
            z-index: 5;
            box-shadow: 0 4px 6px -4px #333;

            background: rgb(255, 255, 255);
            background: linear-gradient(to bottom, rgba(255, 255, 255, 1) 0%, rgba(245, 245, 245, 1) 100%);
            border: rgb(229, 229, 229) 1px solid;
        }
        #data-box {
            top: 70px;
            right:300px;
            height: 45px;
            line-height: 45px;
            display: none;
             background:#ffffff;
        }
        #data-value {
            font-size: 1.0em;
            font-weight: bold;
            padding-right: 10px;
        }
        #data-label {
            font-size: 1.0em;
            font-weight: normal;

            padding-left: 10px;
        }
       }
    < /style>

	< /head>

	< body>

		< div id="data-box" margin='auto' width='auto' class="nicebox">
			< label id="data-label" for="data-value">< /label>
			< span id="data-value">< /span>
		< /div>

			< !-- Google Map Area -->
		   
			< div id="map">< /div>
			
	< /body>

	< script>
    
	//all Important - this is what makes the other countries / water bodies invisible
	var mapStyle = [{
        'stylers': [{
            'visibility': 'off'
        }]
		}, {
			'featureType': 'landscape',
			'elementType': 'geometry',
			'stylers': [{
				'visibility': 'on'
			}, {
				'color': '#ffffff'
			}]
		}, {
			'featureType': 'water',
			'elementType': 'geometry',
			'stylers': [{
				'visibility': 'off'
			}, {
				'color': 'white'
			}]
		}];
          
   var map;

    function initMap() {

        // load the map
        map = new google.maps.Map(document.getElementById('map'), {
            center: {
                lat: 22.85,
                lng: 83.10
            },
            zoom: 4,

            styles: mapStyle,
            disableDefaultUI: true,
            mapTypeControl: false,
            draggable: false
        });

        // set up the style rules and events for the map

        // load the states with the geojson file
        loadStates();
        map.data.addListener('mouseover', mouseInToRegion);
        map.data.addListener('mouseout', mouseOutOfRegion);
        
      // zoom to the clicked state on single click
        map.data.addListener('click',zoomInToRegion);
      // zoom out on  double click
        map.data.addListener('dblclick',zoomOutofRegion);
       
		}

		function processPoints(geometry, callback, thisArg) {
			if (geometry instanceof google.maps.LatLng) {
				callback.call(thisArg, geometry);
			} else if (geometry instanceof google.maps.Data.Point) {
				callback.call(thisArg, geometry.get());
			} else {
				geometry.getArray().forEach(function(g) {
					processPoints(g, callback, thisArg);
				});
			}
		}

		function loadStates() {
			var jsonData;
			jsonData = $.ajax({
				url: "sendIndiacjson.php",
				dataType: "json",
				async: false
			}).responseText;
			var parsedData = JSON.parse(jsonData);
			map.data.addGeoJson(parsedData, {
				idPropertyName: "st_nm"
			});

			map.data.setStyle(styleFeature);
		}

		function mouseInToRegion(e) {
			// set the hover state so the setStyle function can change the border
			e.feature.setProperty('state', 'hover');


			// update the label
			document.getElementById('data-label').textContent =
				e.feature.getProperty('st_nm');
			document.getElementById('data-box').style.display = 'block';

	   }
	   
		/* * Responds to the mouse-out event on a map shape (state).
		
		 */
		function mouseOutOfRegion(e) {
			// reset the hover state, returning the border to normal
			e.feature.setProperty('state', 'normal');

		}

	   // singleclick to zoom in to state
		function zoomInToRegion(e) {
				
			   
				var bounds = new google.maps.LatLngBounds();
				processPoints(e.feature.getGeometry(), bounds.extend, bounds);
				map.fitBounds(bounds,0);
						
			}
		
	   // doubleclick to zoom out
	   function zoomOutofRegion(e) {
           
            map.setZoom(4);
            map.setCenter(new google.maps.LatLng(
                parseFloat(22.85), parseFloat(83.10)));
            
     }
   // set the map style
    function styleFeature(feature) {
        var color = [50, 238, 238]; // base color
        var StrokeColor;
        var fill;
        var outlineWeight = 0.5,
            zIndex = 1;
        if (feature.getProperty('state') === 'hover') {
            outlineWeight = zIndex = 2;
            fill = '#0c457d';
            StrokeColor= '#fff';

        } else {
            fill = 'rgb(' + color[0] +',' + color[1] + ',' + color[2] + ')';
            StrokeColor= '#a9a9a9';
        }
        return {
            strokeWeight: outlineWeight,
            strokeColor: StrokeColor,
            zIndex: zIndex,
            fillColor: fill,
            fillOpacity: 1,
     
        };
    }
   
    google.maps.event.addDomListener(window, 'load', initMap);
	< /script>

	< /body>
	< /html>

	The PHP code to retrieve the json file :
	sendIndiacjson.php

	< ?php

	header("Access-Control-Allow-Origin: *");
	header('Content-type:application/json');
	echo file_get_contents("india-map.json");

	?>

	
	

Our Special Offers
Exclusive Premium Packages for Classroom Training Only

INR. 9,900 / USD 140
INR. 25,000 / USD 350
INR. 5,500 / USD 80
INR. 5,500 / USD 80

Copyright © 1996 - 2021 ZOOM Technologies. All Rights Reserved.