Published on: 08 October, 2018

How to use Promise in Google Map?

Tumblr Digg Google Plus

in this tutorial, you will learn how to use Promise.all. We will use this feature function in geocoding location in Google Map. So what exactly a promise is? A promise is an asynchronous operation that will result in a success or fail result. Below is the simple skeleton function code for our first Promise code.

let promise = new Promise(function(resolve, reject) {
  //enter the code in here
});
		

To see how the resolve and reject method work, you can see the following example.

var total = 10;
let promise = new Promise(function(resolve, reject) {
  if (6 + 4 == total) {
	resolve("The total is correct");
  } else {
	reject("The total is wrong");
  }
});
console.log(promise);
		

You basically want to resolve a promise if the operation is successful, otherwise you want to return a reject response.

So lets get started to use Promise in getting the geolocation in Google Map. Firstly we need to create a HTML div that will be used to populate the Google map object.

			<div id="map" style="width:100%; height:500px"></div>
		

Then we need to include the Google map javascript API including with the API Key.

			<script type='text/javascript' src='https://maps.googleapis.com/maps/api/js?key=MYKEY'></script>
		

The last step is to create the initialization script for the Google Map. We are going to create two functions. The first function will perform a geocode location. We are going to wrap this function in Promise. The second function will perform a map initialization by getting the geolocation first before loading the map. We will then add an event click handler that will display the location name address.

Here is the full script code.

<script>
	var map;
	function getLatitudeLongitudePromise (address){
		return new Promise(function(resolve, reject){
			geocoder = new google.maps.Geocoder();
			if (geocoder) {
				geocoder.geocode({
					'address': address
				}, function (results, status) {
					if (status == google.maps.GeocoderStatus.OK) {
						resolve(results);
					}else{
						reject(status);
					}
				});
			}
		});
	}

	function initMap() {
		//wrap all the requests in Promise.all
		Promise.all([
			getLatitudeLongitudePromise("Newton NSW Australia"),
			getLatitudeLongitudePromise("Five Dock NSW Australia"),
			getLatitudeLongitudePromise("University of Sydney NSW Australia"),
			getLatitudeLongitudePromise("Rose Bay NSW Australia"),
			getLatitudeLongitudePromise("North Bondi NSW Australia"),
			getLatitudeLongitudePromise("Surry Hills NSW Australia")
		]).then(function (results) {
			//once all the requests have been performed, we then initiate the map
			map = new google.maps.Map(document.getElementById('map'), {
			  zoom: 12,
			  center: new google.maps.LatLng(-33.855699,151.223520)
			});
			
			//run through each result and set the click event handler
			results.forEach(function(result){
				var marker = new google.maps.Marker({
					position: new google.maps.LatLng(result[0].geometry.location.lat(), result[0].geometry.location.lng()),
					map: map
				});
				
				var infowindow = new google.maps.InfoWindow();
				google.maps.event.addListener(marker, 'click', function () {
					infowindow.setContent("<div class='googlemap-windowinfo'><div class='googlemap-title'>" + result[0].formatted_address + "</div>");
					infowindow.open(map, this);
				});
			});
		})
		
	}

	//initiate the map
	initMap();
</script>
		
When using a geocoding request, Google may limit the number of requests per second. If you have a huge list of geocoding requests, you may want to do it in a batch. You can use a setTimeout function to perform a batch request in a second.

Demo of Javascript Promise in Google Map

If you have any question regarding with this tutorial, feel free to post your questions below.

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.