Skip to Content
Author's profile photo Abhishek Sharma

Integrate Google Map with SAPUI5 Application

Hi Readers !!

Google Map in Ui5 application can be used for the logistics purpose of the organization as it provides output for optimized route for any vehicle, optimized distance, optimized travelling time, Traffic updates on the map, Toll Roads, information about the route and many more.

Map services are provided by many vendors which can be implemented in Ui5 applications.This blog explains about the Google Map integration with SapUi5 application.

To integrate Google Maps to sapui5 application, you need google map API. There are several APIs available for Google maps itself, like Google Map android API, Google Maps for IOS, Google maps for Street, Google maps Directions API, similarly many more. The one we are going to use is Google Maps JavaScript API.

To use google API, you will need particular developer API key. Below are the steps on how to create a developer key to use the API in the application.

  1. Go to the Google Developers Console.
  2. Create or select a project.
  3. Click Continue to enable the API and any related services.
  4. On the Credentials page, get a Browser key (and set the API Credentials)

Example: “https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap”

Steps to create the application:

  • Open the SAP WEB IDE from Services.
  • Choose File -> NEW -> Project From Template -> SAPUI5 Application.
  • Provide the basic information(Project Name and NameSpace) to the application.
  • Select the View Type (HTML,XML,JSON,JavaScript) as HTML(using in our application).

Write the following code in your view(HTML)

 

<form>
      <div id="front-div">
      <strong>Start:</strong> <input id="origin"><br>
      <strong>End:</strong> <input id="destination">
      </div>
</form>
<div id="left-div"></div>
<div id="map"></div>
<script src="model/distCal.js"></script>


Create a JS(javascript file) in the project folder model and add the following code

 

window.addEventListener('load', function() {
	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.src =
		'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&avoid=TOLLS&libraries=places&callback=initMap';
	document.body.appendChild(script);
});

function initMap() {
	var directionsRenderer = new google.maps.DirectionsRenderer({
		map: map
	});
	var directionsService = new google.maps.DirectionsService;
	var map = new google.maps.Map(document.getElementById('map'), {
		zoom: 6,
		center: {
			lat: 23.0225,
			lng: 72.5714
		} //Initial Location on Map
	});
        directionsRenderer.setMap(map);
	directionsRenderer.setPanel(document.getElementById('left-div'));
	var control = document.getElementById('front-div');
	control.style.display = 'inline';
	map.controls[google.maps.ControlPosition.TOP_CENTER].push(control);
        document.getElementById('origin').addEventListener('change', function() {
		distanceCalculator(directionsService, directionsRenderer);
	}, false);

	document.getElementById('destination').addEventListener('click', function() {
		distanceCalculator(directionsService, directionsRenderer);
	}, false);
}

/***************To Calculate and Display the Route*************/
function distanceCalculator(directionsService, directionsRenderer) {
	var origin = document.getElementById('origin').value;
	var destination = document.getElementById('destination').value;
	var req = {
		origin: origin,
		destination: destination,
		travelMode: 'DRIVING'
	};
	directionsService.route(req, function(response, status) {
		if (status === 'OK') {
			directionsRenderer.setDirections(response);
	}
	});
}

Snapshots of the application in desktop and mobile view


NOTE: This is the basic application to integrate google map with UI5 Application.Comment your questions for further details and features you require or want to add to the application 


Assigned Tags

      24 Comments
      You must be Logged on to comment or reply to a post.
      Author's profile photo Former Member
      Former Member

      Good blog Abhishek! Very helpful.. Keep up the good work.

      Author's profile photo Former Member
      Former Member

      I followed your process, But still unable to load the google api, Based on u r suggestion  I got the API_KEY. Find the below link which I was consumed in my App.

      'https://maps.googleapis.com/maps/api/js?key=AIzaSyC_8vZXS3Ht9L_QdwR8VNmo3x6dy9IXLuI&callback=initMap'

      I am facing the below errors.

       

      Could you please help me on this.

      BestRegards

      Sai Sravya

       

       

       

      Author's profile photo Abhishek Sharma
      Abhishek Sharma
      Blog Post Author

      Hi Sai,

      I hope you have written the code in JS file and you are using the valid API Key.If all this is correct let me know.

      Author's profile photo Viktor Misurak
      Viktor Misurak

      Hi Sai,

       

      you can ignore the design time error for the "google" object. It will be loaded upon loading the window.

       

      However, I had to apply one fix in the view HTML:

      Replace this line:

      <div id="map"></div>

      To:

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

       

      It was working all the time just the map div was not visible... 🙂

       

      @Abhishek: thanks for the blog, nice one!

       

      Best regards,

      Viktor

      Author's profile photo Abhishek Sharma
      Abhishek Sharma
      Blog Post Author

      Hello Sai,

       

      Application would with these error as it is resolved during the run time using your API.

       

      If you are still facing the issue please put up your query again.

       

      Regards,

      Abhishek Sharma

      Author's profile photo Former Member
      Former Member

      Hi Abhishek,

      We have a requirement to integrate our SAP UI5 application with maps and plot our customers on map. Post that we should be able to select a few customers and we should be able to see optimized route on map and other customers close to that route. Would you have some idea if that is possible?

      Regards

      Jitendra

      Author's profile photo Abhishek Sharma
      Abhishek Sharma
      Blog Post Author

      Hi Jitendra,

      Certainly it is possible.You need to build the application to locate your customers on map using their gps and save location in your DB and update it same on the map or you can use the IOT.

      Check this https://blogs.sap.com/2017/02/02/dynamic-geo-tracking/ if it can be helpful 

      Thanks

      Author's profile photo Former Member
      Former Member

      Hi Abhishek,

      Can you please put some more light on how we can achieve the same using SAP IOT for android/iOS devices?

      Thanks in advance.

      Regards,

      SK

      Author's profile photo Former Member
      Former Member

      Hello Sharma,
      i have a same Problem as Sai,
      my structor is same as Master Detail from fiori Web IDE

       

      Could you please help me on this.
      BestRegards

      controller

      VIEW:

      ERROR;

       

      Author's profile photo Federico Cicerchia
      Federico Cicerchia

      Hello Amir, did you resolved this? Can you share it?

      Author's profile photo Princis RAKOTOMANGA
      Princis RAKOTOMANGA

      Hello,

      I’ve achieved this with a Custom Control :

      • Load google script :
        • only once
        • Inside a Promise to avoid the "callback=initMap"(in this case initMap must be defined globally while in sapui5 context, it is defined within a controller : it's a matter of javascript scope)
      • Externalize API Key (ex: one user = one API Key)
      • Reuse the control

       

      sap.ui.define(
      		["sap/ui/core/Control","sap/m/MessageBox"],
      	function(Control,MessageBox) {
      		"use strict";
      		return Control.extend("com.raprincis.ui5.googleMap.controls.GoogleMap", {
      			metadata: {
      				properties: {
      					//Externalize key in order to get it from parameters or OData or whatever 
      					"key": "string", 
      					"address": "string", 
      					"defaultAdress": "string", 
      					"title": { 
      						"type": "string",
      						"defaultValue": "Loading..."
      					},
      					"description": "string",
      					/**
      					 * Google Container
      					 * width : Map width
      					 * height : Map height
      					 * **/
      					"width": { 
      						"type": "sap.ui.core.CSSSize",
      						"defaultValue": "100%"
      					},
      					"height": { 
      						"type": "sap.ui.core.CSSSize",
      						"defaultValue": "400px"
      					},
      					"backgroundColor": { 
      						"type": "sap.ui.core.CSSColor",
      						"defaultValue": "#C6BEBE"
      					},
      					/**
      					 * Google Variables
      					 * @link(https://developers.google.com/maps/documentation/javascript/examples/map-simple)
      					 * **/
      					"mapType": { 
      						"type": "string",
      						"defaultValue": "roadmap"
      					},
      
      					"mapZoom": { 
      						"type": "string",
      						"defaultValue": "17"
      					}
      				},
      				aggregations: {}
      			},
      			init: function() {},
      			renderer: function(oRm, oControl) {
      				//Loading Style : we can externalise these Styles
      				var sGlobalStyle = `width:${oControl.getWidth()};height:${oControl.getHeight()};background:${oControl.getBackgroundColor()}`; // Come on it's ES6 Mr SAP
      				var sLoadingStyle = `color:#A09494;text-align:center;font-size:1rem;padding-top:2rem`;
      				
      				/**
      				 * Target
      				 * <div id='idoFThis' style='width:100%;height:400px;background:#C6BEBE'>
      				 *	<h1>Loading ....</h1>
      				 * </div>
      				 * */
      				oRm.write('<div');
      				oRm.writeControlData(oControl);
      				oRm.writeAttributeEscaped("style", sGlobalStyle);
      				oRm.write('><h1');
      				oRm.writeAttributeEscaped("style", sLoadingStyle);
      				oRm.write(`>${oControl.getTitle()}</h1>`)
      				oRm.write('</div>')
      			},
      			onAfterRendering: function() {
      				//No API Key : No Google Map
      				if (!this.getKey()) {
      					this._showError('No API Key');
      					return;
      				}
      				
      				var sBaseUrl = `https://maps.googleapis.com/maps/api/js?key=${this.getKey()}`, // Come on it's ES6 Mr SAP
      					fnInitialize = this.displayAdress.bind(this),
      					fnOnError = this._showError.bind(this);
      				 
      				this._loadScript(sBaseUrl)
      				.then(fnInitialize)
      				.catch(fnOnError);
      			},
      			_loadScript: function(sUrl) {
      				return new Promise(function(resolve, reject) {
      					try {
      						//Load only once
      						if (google) {
      							resolve();
      						}
      					} catch (e) {
      						/**
      						 * If Google library was not loaded we have something like 'ReferenceError'
      						 * */
      						if (e instanceof ReferenceError) {
      							$.getScript(sUrl)
      								.done(function(script, textStatus) {
      									resolve();
      								})
      								.fail(function(jqxhr, settings, exception) {
      									reject('Error while loading Google Maps');
      								});
      						}
      					}
      				})
      			},
      			_showError: function(sError){
      							MessageBox.error( sError );
      						},
      			displayAdress: function() {
      				var sAdress = this.getAddress();
      				
      				var fnResolver = this._showMap.bind(this),
      					fnError = this._showError.bind(this);
      				
      				//Promise to Search Adress
      				var oSearchAdress = new Promise((resolve,reject)=>{
      					var geocoder = new google.maps.Geocoder();
      					geocoder.geocode({ address: sAdress }, 
      					(results, status)=>{
      						if (status == google.maps.GeocoderStatus.OK) {
      							resolve(results);
      							return;
      						}
      						reject(`"<u>${sAdress}</u>" : Not Found`);
      					});
      				});
      				
      				//Launch Searching
      				oSearchAdress
      				.then(fnResolver)
      				.catch(fnError);
      			},
      			_showMap: function(aResults) {
      				var oDocument = this.getDomRef(),
      					sMapType = this.getMapType(),
      					iZoom = parseInt(this.getMapZoom()),
      					sAdress = this.getAddress(),
      					oLocation = aResults[0].geometry.location; //Take the first Result for instance
      				
      				var mapOptions = {
      					center: oLocation, 
      					zoom: iZoom,
      					mapTypeId: 'roadmap',
      					fullscreenControl: false
      				}
      				var map = new google.maps.Map(oDocument, mapOptions);
      				var marker = new google.maps.Marker({
      					map: map,
      					position: oLocation,
      					title: sAdress,
      					animation: google.maps.Animation.DROP
      				});
      				map.setCenter(oLocation);
      			}
      
      		});
      	}
      );

      Then use it in a XML view:

      <mvc:View 
      	controllerName="com.raprincis.ui5.googleMap.controller.Home" 
      	xmlns:html="http://www.w3.org/1999/xhtml" 
      	xmlns:mvc="sap.ui.core.mvc"
      	xmlns:raprincis="com.raprincis.ui5.googleMap.controls"
      	displayBlock="true" xmlns="sap.m">
      	<App>
      		<pages>
      			<Page title="{i18n>title}">
      				<content>
      					<!-- The Magic is here -->
      					<raprincis:GoogleMap 
      						key="AIzaSyAz7irkOJQ4ydE2dHYrg868QV5jUQ-5FaY" 
      						address="Place du Capitole 31000 Toulouse"/>
      					
      				</content>
      			</Page>
      		</pages>
      	</App>
      </mvc:View>

      And as a Result:

       

       

       

      Author's profile photo Naydson Mariosa
      Naydson Mariosa

      It's really awesome! Best practice with custom control. I'll implement it and will give a feedback

      Author's profile photo Former Member
      Former Member

      Hi  everyone,

      I have to build a map where it shows some addresses with markers and when those markers are clicked, the info window shoes the data corresponding to that address (name, street, etc.). Im using WEB IDE.

      I have the same error in the controller.js where it says that google is not define, although when I run the index.html it works fine and the map shows and the markers are created with the info window.

      When I run the app in with SAP Fiori Launchpad Sandbox I get erros. There errors are google is not define, and others.

       

      I tried to load the google maps js api in the manifest.json first, then in the controller and it is not working. I tried the following.

       

      var gmapsURL = "https://maps.googleapis.com/maps/api/js?key=AIzaSyAfBbljYsPPkqi5ws_23uT1kX-wd6g5HiQ&callback=initMap";
      			
      			jQuery.sap.includeScript(gmapsURL, function(){
      				console.log("Loaded");
      			});
      
      //I get error that window is invalid
      window.addEventListener('load', function() {
      				var script = document.createElement('script');
      				script.type = 'text/javascript';
      				script.src =
      					'https://maps.googleapis.com/maps/api/js?key=AIzaSyAfBbljYsPPkqi5ws_23uT1kX-wd6g5HiQ&avoid=TOLLS&libraries=places&callback=initMap';
      				document.body.appendChild(script);
      			});

       

      Can anybody help me? How do I load the googlemapsjs api? I already have a working API KEY (I tried already running the html file with the api in the script tag in the html file).

      I am new to SAPUI5. I'll really appreciate some help.

      Thank you.

      Author's profile photo Abhishek Sharma
      Abhishek Sharma
      Blog Post Author

      Hello David,

       

      If you are still facing the issue ,please share your email address i will send you the code for the same.

       

      Regards,

      Abhishek Sharma

      Author's profile photo Saket Amraotkar
      Saket Amraotkar

      Hi Abhishek,

      Please send me the code on saket.amraotkar@gmail.com.

       

      Would really appreciate your help.

       

      Regards

      Saket

      Author's profile photo Pradeep V
      Pradeep V

      HI Experts,

       

      I am new to UI5, and having trouble to integrate maps in ui5, could you please tell me in detail how to integrate the map in ui5?, i am using sap wed ide and xml view, any sample example would be great ,

       

      Thanks,

      Pradeep

      Author's profile photo Abhishek Sharma
      Abhishek Sharma
      Blog Post Author

      Hello Pradeep,

       

      This blog is from basic you can easily follow.Please ask if you further have any queries.

       

      Regards,

      Abhishek Sharma

      Author's profile photo Former Member
      Former Member

      Hello Abhishek,

      Your blog is really very helpful to me.

      I am using WEB IDE.

      Created new project  File -NEW -> Project From Template -> SAPUI5 Application and select view as HTML.

      I am unable to see path when i entered start(Delhi,India) and end(Mumbai,Maharastra,India).

      Even i unable to see left side window like in your demo.

      please suggest.

       

       

       

      Author's profile photo Abhishek Sharma
      Abhishek Sharma
      Blog Post Author

      Hello Dhara,

       

      Have you adapted the device resolution in the code dynamically ?

       

      Regards,

      Abhishek Sharma

      Author's profile photo George Abraham
      George Abraham

      Hi Abhishek,

       

      Nice article, however, on trying, I am running into some or the other issues and the output is not appearing - just a semicolon - not sure what's wrong

       

      Would it be possible for you to mail me the code project/all files to george[dot]abraham1912[at]gmail[dot]com?

      Author's profile photo pragyan pradeepta panigrahi
      pragyan pradeepta panigrahi

      Hi Abhishek , Nice Blog.

      I have followed all the steps explained by you.But i am getting some error.

       

      Could you please help me on this.

       

       

      Regards

      Pragyan

       

       

      Author's profile photo Charan Naidu
      Charan Naidu

      can you share this application.  Because i'm unable to get . my mail id: iamcharran@gmail.com

       

      Author's profile photo Fitha Zakkeer
      Fitha Zakkeer

      Hi Experts,

      can you please help me with this question reagrding marker clustering in google map

      https://answers.sap.com/questions/13566828/how-to-add-marker-clusterer-in-google-map-in-sapui.html

      Thanks and Regards

      Fitha

      Author's profile photo Abhinay Dogiparthi
      Abhinay Dogiparthi

      Any idea on how to draw a curved polyline or a route between two points using Google Maps/SAP UI5 Geo Map Routes ?

       

      Thanks,

      Abhi