Advanced Google Maps Functionality Tutorial

Advanced Google Maps Functionality Tutorial

The Google Maps API is a web service that allows you to use Google maps on your website, as well as access geocoding, directions, elevation, place and time zone information. This article will show some advanced techniques used when integrating Google maps with web applications.

Basic Settings

Implementing a basic Google map is pretty straightforward:

                  

First, the Google maps JavaScript is loaded. You will notice that you need to obtain an API key and add it to the code, which you can do here. Next, the function initialize is where the map is created. It contains the map options and the map object.

There are many map options available. Center is used to determine which latitude and longitude to show after map initialization, while the zoom option sets the initial zoom level. Minimum and maximum zoom levels limit map zoom levels. Options, that are not shown, include changing the map type (road map, terrain map, satellite map) and customizing map controls and can be found here.

Finally, a div which will hold the map is created inside the HTML body tag.

Markers

Markers are a way to mark a certain location on the Google map. A simple marker is created like this:

marker = new google.maps.Marker({		position: new google.maps.LatLng(37.442219,-122.141705), // marker position on the map - latitude and longitude		map: map, // this is the map object		title: 'Marker title'		icon: 'images/marker-icon.png' // Custom marker icon (optional)	});

Note that the markers are created after creating the map object. If the icon configuration is omitted, the default marker icon would be used (red bubble). Google maps offer a few other marker icons as well. However, you can use virtually any image as an icon.

The Marker object can be extended to hold additional data. Also, it is a good idea to create an array that will hold marker objects in order to allow easier customizations:

// Adds marker to the map// Array containing all marker objectsvar markers_array = [];// Currently selected marker object// This is needed later for marker and infobox customizationvar last_marker = null; function add_marker(map,data) {	marker = new google.maps.Marker({		position: new google.maps.LatLng(data.lat, data.lng), // Latitude and longitude where the marker would be shown		map: map, // Google maps map object		title: data.title, // Marker title	});		// Additional data added to the marker from data object	marker.city = data.city;	marker.county = data.country;	marker.zip_code = data.zip_code;		marker.lat = data.lat;	marker.lng = data.lng;		markers_array.push(marker);	return marker;}

Having all markers in an array allows us to remove all markers from the map. This is very useful in cases where we have multiple marker categories that need to be changed on click:

// Removes the overlays from the map, but keeps them in the arrayfunction clear_overlays() {	if (markers_array) {		for (i in markers_array) {	    	markers_array[i].setMap(null);	    }	}}//Deletes all markers in the array by removing references to themfunction delete_overlays() {	  if (markers_array) {    for (i in markers_array) {    	if(markers_array[i]!=last_marker) {    		markers_array[i].setMap(null);    	}          }    markers_array.length = 1;  }}

Now, let’s see how the markers would be created if we are fetching the data from an external data source:

$.getJSON('your_url/items.json',function(json) {		// Delete all markers if there are any		delete_overlays();				// Foreach json object		for(i in json.items) {			var marker = add_marker(map,data[i]);                                               // Creates an infobox			// This will be explained below with more details			create_infobox(marker, map, data[i]);		}});

Note that the actual JSON object names may be different, depending on your data source.

Infoboxes

Infobox (or infowindow) is a box with additional information that opens up when you click on a marker. Here is a function that creates an infobox with some additional customizations:

function create_infobox(marker, map, data) {	// Generate HTML for the infobox – see below	var html = infobox_html(data);		// Creates the infobox and sets its content	var infowindow = new google.maps.InfoWindow({	    content: html	});		// Assigns the infobox to the corresponding marker	marker.infobox = infowindow;		// Open the infobox when clicked on a marker	google.maps.event.addListener(marker, 'click', function() {				// If a previous infobox is opened, close it		// So, only one infobox at a time can be visible		close_infobox();				// Currently selected marker becomes last selected marker		last_marker = marker;				// Show the infobox		infowindow.open(map,marker);		last_infobox = infowindow;		last_infobox.info = info;				// Code to be executed when the infobox is closed		google.maps.event.addListener(infowindow, 'closeclick', function() {			close_infobox();		});								// Enlarge marker icon for selected marker		var image = marker.getIcon();		marker.setIcon('images/marker-icon-large.png');	});}function close_infobox() {		// Change the icon back to the normal icon	if(last_marker!=null) {		var last_image = last_marker.getIcon();				last_marker.setIcon('images/marker-icon.png');		last_marker = null;						}			// Close the infoboxif(last_infobox!='') {		last_infobox.close();		last_infobox = '';	}	}// Generate the HTML code for the infoboxfunction infobox_html(data) {	return '
' + data.city + '
"';}

The function above changes the marker icon when the infobox is opened, adds custom HTML code to the infobox and makes sure that only one infobox at a time can be visible.

Map Bounds

In some cases, you might want to limit the area of the map which a user can see and interact with. For example, you are creating a map that needs to show only one country or a continent. This is done by creating a dragend listener and adding it to the initialize function below the line that creates the map object:

// Set bounds	var strictBounds = new google.maps.LatLngBounds(	     new google.maps.LatLng(28.70, -127.50), 	     new google.maps.LatLng(48.85, -55.90)	);	// Add the dragend listener to the map	google.maps.event.addListener(map, 'dragend', function() {	     // The map is still inside the bounds	    // Don't do anything	     if (strictBounds.contains(map.getCenter())) return;	     // The map is out of bounds     // Move the map back within the bounds	     var c = map.getCenter(),	         x = c.lng(),	         y = c.lat(),	         maxX = strictBounds.getNorthEast().lng(),	         maxY = strictBounds.getNorthEast().lat(),	         minX = strictBounds.getSouthWest().lng(),	         minY = strictBounds.getSouthWest().lat();	     if (x < minX) x = minX;	     if (x > maxX) x = maxX;	     if (y < minY) y = minY;	     if (y > maxY) y = maxY;	     map.setCenter(new google.maps.LatLng(y, x));	});

So, when someone drags the map out of bounds, the map will be returned to the nearest boundary. In this example, the map is limited to show only United States.

Note

Google maps API has daily rate limits. Please check that before starting any larger projects.

devx-admin

devx-admin

Share the Post:
Bold Evolution

Intel’s Bold Comeback

Intel, a leading figure in the semiconductor industry, has underperformed in the stock market over the past five years, with shares dropping by 4% as

Semiconductor market

Semiconductor Slump: Rebound on the Horizon

In recent years, the semiconductor sector has faced a slump due to decreasing PC and smartphone sales, especially in 2022 and 2023. Nonetheless, as 2024

Learn Web Security

An Easy Way to Learn Web Security

The Web Security Academy has recently introduced new educational courses designed to offer a comprehensible and straightforward journey through the intricate realm of web security.

Military Drones Revolution

Military Drones: New Mobile Command Centers

The Air Force Special Operations Command (AFSOC) is currently working on a pioneering project that aims to transform MQ-9 Reaper drones into mobile command centers

Tech Partnership

US and Vietnam: The Next Tech Leaders?

The US and Vietnam have entered into a series of multi-billion-dollar business deals, marking a significant leap forward in their cooperation in vital sectors like

Bold Evolution

Intel’s Bold Comeback

Intel, a leading figure in the semiconductor industry, has underperformed in the stock market over the past five years, with shares dropping by 4% as opposed to the 176% return

Semiconductor market

Semiconductor Slump: Rebound on the Horizon

In recent years, the semiconductor sector has faced a slump due to decreasing PC and smartphone sales, especially in 2022 and 2023. Nonetheless, as 2024 approaches, the industry seems to

Elevated Content Deals

Elevate Your Content Creation with Amazing Deals

The latest Tech Deals cater to creators of different levels and budgets, featuring a variety of computer accessories and tools designed specifically for content creation. Enhance your technological setup with

Learn Web Security

An Easy Way to Learn Web Security

The Web Security Academy has recently introduced new educational courses designed to offer a comprehensible and straightforward journey through the intricate realm of web security. These carefully designed learning courses

Military Drones Revolution

Military Drones: New Mobile Command Centers

The Air Force Special Operations Command (AFSOC) is currently working on a pioneering project that aims to transform MQ-9 Reaper drones into mobile command centers to better manage smaller unmanned

Tech Partnership

US and Vietnam: The Next Tech Leaders?

The US and Vietnam have entered into a series of multi-billion-dollar business deals, marking a significant leap forward in their cooperation in vital sectors like artificial intelligence (AI), semiconductors, and

Huge Savings

Score Massive Savings on Portable Gaming

This week in tech bargains, a well-known firm has considerably reduced the price of its portable gaming device, cutting costs by as much as 20 percent, which matches the lowest

Cloudfare Protection

Unbreakable: Cloudflare One Data Protection Suite

Recently, Cloudflare introduced its One Data Protection Suite, an extensive collection of sophisticated security tools designed to protect data in various environments, including web, private, and SaaS applications. The suite

Drone Revolution

Cool Drone Tech Unveiled at London Event

At the DSEI defense event in London, Israeli defense firms exhibited cutting-edge drone technology featuring vertical-takeoff-and-landing (VTOL) abilities while launching two innovative systems that have already been acquired by clients.

2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications, it suffers from certain limitations.

Cisco Growth

Cisco Cuts Jobs To Optimize Growth

Tech giant Cisco Systems Inc. recently unveiled plans to reduce its workforce in two Californian cities, with the goal of optimizing the company’s cost structure. The company has decided to

FAA Authorization

FAA Approves Drone Deliveries

In a significant development for the US drone industry, drone delivery company Zipline has gained Federal Aviation Administration (FAA) authorization, permitting them to operate drones beyond the visual line of

Mortgage Rate Challenges

Prop-Tech Firms Face Mortgage Rate Challenges

The surge in mortgage rates and a subsequent decrease in home buying have presented challenges for prop-tech firms like Divvy Homes, a rent-to-own start-up company. With a previous valuation of

Lighthouse Updates

Microsoft 365 Lighthouse: Powerful Updates

Microsoft has introduced a new update to Microsoft 365 Lighthouse, which includes support for alerts and notifications. This update is designed to give Managed Service Providers (MSPs) increased control and

Website Lock

Mysterious Website Blockage Sparks Concern

Recently, visitors of a well-known resource website encountered a message blocking their access, resulting in disappointment and frustration among its users. While the reason for this limitation remains uncertain, specialists

AI Tool

Unleashing AI Power with Microsoft 365 Copilot

Microsoft has recently unveiled the initial list of Australian clients who will benefit from Microsoft 365 (M365) Copilot through the exclusive invitation-only global Early Access Program. Prominent organizations participating in

Microsoft Egnyte Collaboration

Microsoft and Egnyte Collaboration

Microsoft has revealed a collaboration with Egnyte, a prominent platform for content cooperation and governance, with the goal of improving real-time collaboration features within Microsoft 365 and Microsoft Teams. This

Best Laptops

Top Programming Laptops of 2023

In 2023, many developers prioritize finding the best laptop for programming, whether at home, in the workplace, or on the go. A high-performing, portable, and user-friendly laptop could significantly influence

Renaissance Gaming Magic

AI Unleashes A Gaming Renaissance

In recent times, artificial intelligence has achieved remarkable progress, with resources like ChatGPT becoming more sophisticated and readily available. Pietro Schirano, the design lead at Brex, has explored the capabilities

New Apple Watch

The New Apple Watch Ultra 2 is Awesome

Apple is making waves in the smartwatch market with the introduction of the highly anticipated Apple Watch Ultra 2. This revolutionary device promises exceptional performance, robust design, and a myriad

Truth Unveiling

Unveiling Truths in Bowen’s SMR Controversy

Tony Wood from the Grattan Institute has voiced his concerns over Climate and Energy Minister Chris Bowen’s critique of the Coalition’s support for small modular nuclear reactors (SMRs). Wood points

Avoiding Crisis

Racing to Defy Looming Financial Crisis

Chinese property developer Country Garden is facing a liquidity challenge as it approaches a deadline to pay $15 million in interest associated with an offshore bond. With a 30-day grace

Open-Source Development

Open-Source Software Development is King

The increasingly digital world has led to the emergence of open-source software as a critical factor in modern software development, with more than 70% of the infrastructure, products, and services

Home Savings

Sensational Savings on Smart Home Security

For a limited time only, Amazon is offering massive discounts on a variety of intelligent home devices, including products from its Ring security range. Running until October 2 or while

Apple Unleashed

A Deep Dive into the iPhone 15 Pro Max

Apple recently unveiled its groundbreaking iPhone 15 Pro and iPhone 15 Pro Max models, featuring a revolutionary design, extraordinary display technology, and unrivaled performance. These new models are the first