Google Maps Integration in SAP UI5

by | May 18, 2023 | UI5, UI5 Integrations

Home » SAP » UI5 » UI5 Integrations » Google Maps Integration in SAP UI5

Introduction

Welcome to our comprehensive guide on Google Maps integration in SAP UI5! In this article, we will explore the seamless integration of these two powerful technologies to enhance the user experience and unlock a world of geospatial possibilities. Discover how the integration of Google Maps and SAP UI5 can revolutionize your application by providing intuitive and interactive mapping functionalities. We will delve into the key features, implementation strategies, and best practices to ensure a successful integration. Get ready to embark on a journey that combines the strength of SAP UI5 with the versatility of Google Maps, resulting in an unparalleled user experience and improved business outcomes. Let’s dive in and explore the limitless potential of Google Maps integration in SAP UI5!

When we need Google Maps Integration in SAP UI5

Google Maps integration in SAP UI5 becomes essential in various scenarios where geospatial information and mapping capabilities are required within SAP applications. Here are a few instances when integrating Google Maps with SAP UI5 can be beneficial:

1. Location-Based Services: When you need to incorporate location-based services into your SAP UI5 application, such as displaying customer locations, tracking shipments, or finding the nearest store or service center.

2. Geographical Data Visualization: If you have large volumes of geographical data that need to be visualized effectively, Google Maps integration can help you present the information in a user-friendly and interactive manner.

3. Route Planning and Optimization: When your SAP application involves route planning, delivery management, or field service operations, integrating Google Maps allows you to calculate optimized routes, estimate travel distances and durations, and provide real-time traffic information.

4. Geolocation Tracking: If you require real-time tracking of assets, vehicles, or personnel within your SAP application, Google Maps integration enables you to track and display their positions on a map, facilitating monitoring and decision-making processes.

5. Address Validation and Geocoding: When it’s necessary to validate and standardize addresses entered by users or perform geocoding (converting addresses into geographic coordinates), integrating Google Maps can ensure accurate and reliable data.

6. Location Intelligence and Analytics: If you want to leverage location-based insights to enhance business intelligence and analytics, integrating Google Maps with SAP UI5 enables you to overlay geographical data with other business data, facilitating data-driven decision-making.

By integrating Google Maps with SAP UI5, you can unlock a wide range of geospatial functionalities, enrich your application with interactive maps, and provide a more intuitive and engaging user experience.

How to generate a Google Map API Key

To generate a Google Maps API key, follow these steps:

1. Go to the Google Cloud Platform Console: Visit the Google Cloud Platform Console at https://console.cloud.google.com/.

2. Create a new project: If you don’t have a project already, create a new one by clicking on the “Select a project” drop-down menu at the top of the page and selecting “New Project.” Give your project a name and click “Create.”

3. Enable the Maps JavaScript API: In the Cloud Platform Console, click on the “Enable APIs and Services” button. Search for “Maps JavaScript API” and select it from the results. Click on the “Enable” button to enable the API for your project.

4. Set up API credentials: From the left sidebar, click on “Credentials” and then click on the “Create Credentials” button. Select “API key” from the dropdown menu.

5. Restrict your API key (optional): For security purposes, it’s recommended to restrict your API key to only allow requests from specific websites or mobile apps. You can set up restrictions by clicking on the “Restrict key” button.

6. Configure your API key: Give your API key a name for easy reference and configure any additional settings or restrictions as needed.

7. Get your API key: Once you have configured your API key, it will be generated. Copy the API key and securely store it.

Congratulations! You have successfully generated a Google Maps API key. Make sure to include this API key in your SAP UI5 application when making requests to the Google Maps API services.

Types of Google Maps Integration in SAP UI5

iFrame based Integration

To perform iFrame-based integration in SAP UI5, you can follow these steps:

  1. Create an XML View: Define an XML view in your SAP UI5 application where you want to integrate the iFrame. This XML view will contain the iFrame control.
  2. Add iFrame control: Inside the XML view, add the iFrame control by using the <core:HTML> or <html:iframe> tag. Set the src attribute to specify the URL of the webpage or content you want to display within the iFrame.

    Example:

    <core:HTML content="<iframe src='https://www.example.com' width='100%' height='100%'></iframe>" />
    

     

  3. Adjust iFrame properties: Customize the iFrame by setting attributes such as width, height, scrolling, frameborder, etc., based on your requirements. These attributes define the appearance and behavior of the iFrame.
    <core:HTML content="<iframe src='https://www.example.com' width='800' height='600' scrolling='auto' frameborder='0'></iframe>" />
    

     

  4. Bind iFrame properties dynamically (optional): If you need to dynamically change the URL or other properties of the iFrame based on your application logic, you can bind the properties using data binding techniques provided by SAP UI5.
    <core:HTML content="<iframe src='{path>/iframeUrl}' width='100%' height='100%'></iframe>" />
    

     

  5. Style and position the iFrame: Apply CSS classes or inline styles to the iFrame or its parent containers to control the appearance, positioning, and responsiveness of the iFrame within your SAP UI5 application.
    <core:HTML content="<iframe src='https://www.example.com' width='100%' height='100%' class='myIframe'></iframe>" />
    

    In the CSS file:

    .myIframe {
        border: 1px solid #ccc;
        border-radius: 5px;
    }
    

     

For Google Maps, first, get the source URL from here: https://www.maps.ie/create-google-map/

And then add the following in the view file:

<mvc:View controllerName="Test.Test.controller.Main" xmlns:ndc="sap.ndc" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m"
    xmlns:core="sap.ui.core" xmlns:html="http://www.w3.org/1999/xhtml">
    <Shell id="shell">
        <App id="app">
            <pages>
                <Page id="page" title="Google Map Integration in SAP UI5">
                    <content>
                        <!--Fixed Google Map without API Key and without serch functionality-->
                        <html:iframe width="100%" height="600"
                            src="https://maps.google.com/maps?width=100%25&amp;height=600&amp;hl=en&amp;q=Noida+(My%20Project%20Ideas)&amp;t=&amp;z=14&amp;ie=UTF8&amp;iwloc=B&amp;output=embed"></html:iframe>
                    
                    </content>
                </Page>
            </pages>
        </App>
    </Shell>
</mvc:View>

Output

Google Maps Integration using iFrame in UI5

Google API-based Integration

To perform Google API-based integration in SAP UI5, you can follow these steps:

  1. Obtain a Google Maps API Key: Generate a Google Maps API key by following the steps outlined in the previous response titled “How to generate a Google Map API Key.” This key will be required to access and use Google Maps API services.
  2. Load the Google Maps API library: In your SAP UI5 application, include the Google Maps JavaScript library by adding the following script tag to the HTML view or index.html file of your application.
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
    

    Replace YOUR_API_KEY with the API key you obtained in Step 1.

  3. Create a UI5 control for Google Maps integration: In your SAP UI5 application, create a control (such as a custom control or an extension of an existing control) that encapsulates the Google Maps functionality. This control will be responsible for rendering the map and interacting with the Google Maps API.
  4. Initialize the map: Within your UI5 control, initialize the Google Map by calling the appropriate JavaScript functions provided by the Google Maps API. This includes specifying the map container element, setting the initial center coordinates, zoom level, and any additional options you want to apply to the map.
    var map = new google.maps.Map(mapContainer, {
      center: { lat: 37.7749, lng: -122.4194 },
      zoom: 12,
    });
    

    Here, mapContainer represents the HTML element where the map will be rendered.

  5. Utilize Google Maps API services: You can now leverage various Google Maps API services within your UI5 control. These services include displaying markers, drawing shapes, geocoding, reverse geocoding, route calculation, and more. Refer to the Google Maps API documentation for details on each service and how to use them.
    // Example: Add a marker to the map
    var marker = new google.maps.Marker({
      position: { lat: 37.7749, lng: -122.4194 },
      map: map,
      title: 'San Francisco',
    });
    

    This example creates a marker at the specified coordinates and displays it on the map.

  6. ustomize and interact with the map: You can customize the map’s appearance, add event listeners for user interactions, and apply other styling and functionality as per your application requirements. Use the available Google Maps API functions and options to achieve this.
    // Example: Add a click event listener to the map
    map.addListener('click', function(event) {
      console.log('Clicked on the map at coordinates:', event.latLng);
    });
    

    This example logs the clicked coordinates to the console when the user clicks on the map.

    By following these steps, you can integrate Google Maps API functionality into your SAP UI5 application and leverage its powerful mapping capabilities to enhance the user experience and add geospatial functionality to your application.

HTML code

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <!--<meta name="viewport" content="width=device-width, initial-scale=1.0">-->
        <title>My Project Ideas</title>
         <link rel="icon" type="image/x-icon" href="https://myprojectideas.com/wp-content/uploads/2021/08/cropped-Screenshot-2021-07-26-at-1.39.04-PM-32x32.png">
        <script id="sap-ui-bootstrap"
            src="resources/sap-ui-core.js"
            data-sap-ui-theme="sap_fiori_3"
            data-sap-ui-resourceroots='{"Test.Test": "./"}'
            data-sap-ui-compatVersion="edge"
            data-sap-ui-oninit="module:sap/ui/core/ComponentSupport"
            data-sap-ui-async="true"
            data-sap-ui-frameOptions="trusted">
        </script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBXMbsWFS5fKJD7IX7-E__5ZWKFgZTNeqs&libraries=places" type ="text/javascript"> 
</script>
<style>
.myMap {                   
height: 100%;
width: 100%  ;
}
</style>
    </head>
    <body class="sapUiBody">
        <div data-sap-ui-component data-name="Test.Test" data-id="container" data-settings='{"id" : "Test"}'></div>
    </body>
</html>

 

View Code

<mvc:View controllerName="Test.Test.controller.Main" xmlns:ndc="sap.ndc" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m"
    xmlns:core="sap.ui.core" xmlns:html="http://www.w3.org/1999/xhtml">
    <Shell id="shell">
        <App id="app">
            <pages>
                <Page id="page" title="Google Map Integration in SAP UI5">
                    <content>
                        <VBox fitContainer="true" justifyContent="Center" alignItems="Center">
                            <HBox fitContainer="true" justifyContent="Center" alignItems="Center">
                                <Input id="bntSearch" class="controls" type="text" placeholder="Search Box"/>
                                <Button id="button" text="search" press="onAfterRendering"/>
                                <Button id="Distance" text="Distance" press="onDistancePress"/>
                            </HBox>
                            <HBox fitContainer="true" justifyContent="Center" alignItems="Center">
                                <Input id="FromDis" placeholder="From" visible="false"/>
                                <Input id="ToDis" placeholder="To" visible="false"/>
                                <Button id="Okay" text="Ok" visible="false" press="onOkayPress"/>
                            </HBox>
                            <HBox id="map_canvas" fitContainer="true" justifyContent="Center" alignItems="Center"></HBox>
                        </VBox>
                    </content>
                </Page>
            </pages>
        </App>
    </Shell>
</mvc:View>

 

Controller Code

sap.ui.define([
    "sap/ui/core/mvc/Controller",
    "sap/m/MessageBox",
    "sap/m/MessageToast",
    "sap/ui/model/json/JSONModel",
], function (Controller, MessageBox, MessageToast, JSONModel) {
    "use strict";
    return Controller.extend("Test.Test.controller.Main", {
        onInit: function () {
            this.getView().byId("map_canvas").addStyleClass("myMap");
        },
        onAfterRendering: function () {
            if (!this.initialized) {
                this.initialized = true;
                this.geocoder = new google.maps.Geocoder();
                window.mapOptions = {
                    center: new google.maps.LatLng(28.5706333, 77.3272147),
                    zoom: 8,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                //This is basically for setting the initial position of the map, ie. Setting the coordinates, for the place by default
                var map = new google.maps.Map(this.getView().byId("map_canvas").getDomRef(), mapOptions);
                var infowindow = new google.maps.InfoWindow;
                var geocoder = new google.maps.Geocoder();
                var marker = new google.maps.Marker({
                    map: map,
                });
                google.maps.event.addListener(map, "click", function (e) {
                    var lolatitude = e.latLng.lat(); //calculates latitude of the point of click
                    var lolongitude = e.latLng.lng() //calculates longitude of the point of click
                    jQuery.sap.require("sap.m.MessageToast");
                    sap.m.MessageToast.show("Lat" + lolatitude + "\n Lng" + lolongitude);
                    var latlng = new google.maps.LatLng("latlng", lolatitude, lolongitude);
                    var text1 = new sap.m.Text({
                        text: lolatitude
                    });
                    var text2 = new sap.m.Text({
                        text: lolongitude
                    });
                    window.point1 = lolatitude;
                    window.point2 = lolongitude;
                    geocodeLatLng(geocoder, map, infowindow, text1, text2);
                });
                //This function is for what should happen if a user left clicks on the map
                function geocodeLatLng(geocoder, map, infowindow, text1, text2) {
                    var markers = [];
                    var input1 = text1.mProperties.text;
                    var input2 = text2.mProperties.text;
                    var latlng = {
                        lat: parseFloat(input1),
                        lng: parseFloat(input2)
                    };
                    geocoder.geocode({
                        'location': latlng
                    }, function (results, status) {
                        if (status === google.maps.GeocoderStatus.OK) {
                            if (results[1]) {
                                //Here result will consist of many result, but we have to take fist result //itself, since that would be the appropriate one
                                map.setZoom(11);
                                function addMarker(location) {
                                    var marker = new google.maps.Marker({
                                        position: location,
                                        map: newmap1
                                    });
                                    markers.push(marker); // A marker is added to the point where it was clicked
                                }
                                var address1 = results[1].formatted_address;
                                infowindow.setContent(results[1].formatted_address);
                                infowindow.open(map, marker);
                            } else {
                                window.alert('No results found');
                            }
                        } else {
                            window.alert('Geocoder failed due to: ' + status);
                        }
                    });
                }
                ////////////////////Distance//////////////////////
            } else if (this.initialized === true) {
                this.actSearch()
            }
        },
        actSearch: function () {
            var newmap = new google.maps.Map(this.getView().byId("map_canvas").getDomRef(), mapOptions);
            var address = this.getView().byId("bntSearch").getValue();
            this.geocoder.geocode({
                'address': address
            }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    newmap.setCenter(results[0].geometry.location);
                    newmap.setZoom(12);
                    var marker = new google.maps.Marker({
                        map: newmap,
                        position: results[0].geometry.location
                    });
                    //This function is for search. Here when a place is searched a marker is //applied and the map is zoomed to the particular position.
                } else {
                    alert('Geocode was not successful for the following reason: ' + status);
                }
            });
            return;
        },
        onDistancePress: function () {
            var loFrom = this.getView().byId("FromDis");
            var loTo = this.getView().byId("ToDis");
            var loOk = this.getView().byId("Okay");
            loOk.setVisible(true);
            loFrom.setVisible(true);
            loTo.setVisible(true);
        },
        //This function is triggered on click of distance button.
        onOkayPress: function () {
            //This function calculates approx. distance between the two places, since I //haven’t used Google Maps Distance API, therefore this ain’t the proper way //to calculate distance among the places
            var newmap1 = new google.maps.Map(this.getView().byId("map_canvas").getDomRef(), mapOptions);
            var address1 = this.getView().byId("FromDis").getValue();
            var address2 = this.getView().byId("ToDis").getValue();
            this.geocoder.geocode({
                'address': address1
            }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    window.lolatitude1 = results[0].geometry.location.lat();
                    window.lolongitude1 = results[0].geometry.location.lng();
                    window.add1 = results[0].formatted_address.split(",", 1)[0]
                    newmap1.setCenter(results[0].geometry.location);
                    newmap1.setZoom(12);
                    var marker = new google.maps.Marker({
                        map: newmap1,
                        position: results[0].geometry.location
                    });
                } else {
                    alert('Geocode was not successful for the following reason: ' + status);
                }
            });
            this.geocoder.geocode({
                'address': address2
            }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    window.lolatitude2 = results[0].geometry.location.lat();
                    window.lolongitude2 = results[0].geometry.location.lng();
                    window.add2 = results[0].formatted_address.split(",", 1)[0]
                    newmap1.setCenter(results[0].geometry.location);
                    newmap1.setZoom(10);
                    var marker = new google.maps.Marker({
                        map: newmap1,
                        position: results[0].geometry.location
                    });
                    sap.m.MessageToast.show("Approx. Distance Between" + " " + window.add1 + " " + "and" + " " + window.add2 + " " + "is" + " " +
                        getDistanceFromLatLonInKm(window.lolatitude1, window.lolongitude1, window.lolatitude2, window.lolongitude2) + "KM", {
                            width: "30em",
                            duration: 10000
                        });
                } else {
                    alert('Geocode was not successful for the following reason: ' + status);
                }
            });
            function getDistanceFromLatLonInKm(lolatitude1, lolongitude1, lolatitude2, lolongitude2) {
                var R = 6371; // Radius of the earth in km
                var dLat = deg2rad(window.lolatitude2 - window.lolatitude1); // deg2rad below
                var dLon = deg2rad(window.lolongitude2 - window.lolongitude1);
                var a =
                    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                    Math.cos(deg2rad(window.lolatitude1)) * Math.cos(deg2rad(window.lolatitude2)) *
                    Math.sin(dLon / 2) * Math.sin(dLon / 2);
                var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
                var d = R * c; // Distance in km
                return d.toLocaleString();
            }
            function deg2rad(deg) {
                return deg * (Math.PI / 180)
            }
            var flightPlanCoordinates = [{
                    lat: window.lolatitude1,
                    lng: window.lolongitude1
                }, {
                    lat: window.lolatitude2,
                    lng: window.lolongitude2
                }
            ];
            var flightPath = new google.maps.Polyline({
                path: flightPlanCoordinates,
                geodesic: true,
                strokeColor: '#FF0000',
                strokeOpacity: 1.0,
                strokeWeight: 2
            });
            flightPath.setMap(newmap1);
        }
    });
});

 

Output

Google Maps Integration using API Key in UI5

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author