Enterprise Resource Planning Blog Posts by Members
cancel
Showing results for 
Search instead for 
Did you mean: 
Mahmoud-Farag
Participant
1,885

Business Case:

In the logistics industry, real-time shipment tracking is a necessity. Traditional systems often lack a visual component, leaving businesses without critical insights into routes, distances, and potential delays. Shipment Tracking Application, built with SAPUI5 and Google Maps, addresses these challenges by combining route visualization, detailed instructions, and multilingual support into a single application.

MahmoudFarag_0-1734988678533.png

Features:

1. Interactive Map Integration

  • Seamless integration with Google Maps to display real-time shipment routes.
  • Dynamic updates based on user input, such as shipment ID.

2. Step-by-Step Directions

  • Instructions and distances for each step in the route.
  • Multilingual support to cater to global users.

3. Shipment Search

  • Simple search functionality to retrieve shipment routes using shipment IDs.

4. Real-Time Distance Calculation

  • Display total distance for the shipment route instantly.

Setup Instructions

Step 1: Configure Google Maps API
To integrate Google Maps, you need to set up an API key:

  1. Go to the Google Developers Console.
  2. Create or select a project:
    • If you don’t have an existing project, create a new one.
  3. Enable Google Maps JavaScript API:
    • Search for "Google Maps JavaScript API" in the library and enable it.
  4. Create API Credentials:
    • Navigate to the "Credentials" page.
    • Generate a Browser Key for your application.
  5. Set API Restrictions:
    • Restrict the key to your application’s domain for security purposes.

Example API URL for integration:

 

 

 

 

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

 

 

Replace YOUR_API_KEY with the key generated in the Google Developers Console. 

MahmoudFarag_1-1734988791435.png

Step 2: Configure OData Service

  • Create an OData service with an entity set, e.g., ShipmentSet.
  • Ensure the service fetches StartCoords and EndCoords based on the shipment number.

 

 

{
    "StartCoords": { "lat": 30.0444, "lng": 31.2357 },
    "EndCoords": { "lat": 31.2023, "lng": 29.9014 }
}

 

 

 

XML View

 

 

 

<mvc:View controllerName="shiptrack.controller.View1"
    xmlns:mvc="sap.ui.core.mvc" displayBlock="true 
    xmlns:core="sap.ui.core"
    xmlns="sap.m" xmlns:l="sap.ui.layout">
    <Page id="page" title="Shipment Tracker">
        <VBox>
            <SearchField id="searchField" placeholder="Enter Shipment ID" search=".onFindShipment" />
            <Text id="totalDistanceText" text="Total Distance: {route>/distance}" />
            <l:Splitter orientation="Horizontal" width="100%" height="500px">
                <l:Splitter>
                    <!-- Directions List -->
                    <List id="directionsList" items="{route>/steps}">
                        <CustomListItem>
                            <VBox>
                                <Text text="{route>instruction}" />
                                <Text text="{route>distance}" />
                            </VBox>
                        </CustomListItem>
                    </List>
                </l:Splitter>
                <l:Splitter>
                    <!-- Map Container -->
                     <Core:HTML id="mapContainer" width="70%" height="500px" />
                </l:Splitter>
            </l:Splitter>
        </VBox>
    </Page>
</mvc:View>

 

 

 

 

 

Full Controller Code:

 

 

 

sap.ui.define([
    "sap/ui/core/mvc/Controller",
    "sap/m/MessageToast",
    "sap/ui/model/json/JSONModel"
], function (Controller, MessageToast, JSONModel) {
    "use strict";

    return Controller.extend("shiptrack.controller.View1", {
        onInit: function () {
            this._map = null;
            this._directionsService = null;
            this._directionsRenderer = null;

            const oModel = new JSONModel({ steps: [], distance: "" });
            this.getView().setModel(oModel, "route");

            this._loadGoogleMaps().then(() => {
                this._initializeMap();
            }).catch((error) => {
                console.error("Google Maps could not be loaded:", error);
                MessageToast.show("Unable to load Google Maps. Please try again later.");
            });
        },

        _loadGoogleMaps: function () {
            return new Promise((resolve, reject) => {
                if (typeof google !== "undefined" && google.maps) {
                    resolve();
                    return;
                }
                const script = document.createElement("script");
                script.src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry";
                script.async = true;
                script.defer = true;
                script.onload = resolve;
                script.onerror = reject;
                document.head.appendChild(script);
            });
        },

        _initializeMap: function () {
            const mapContainer = this.byId("mapContainer").getDomRef();
            this._map = new google.maps.Map(mapContainer, {
                center: { lat: 0, lng: 0 },
                zoom: 2
            });
            this._directionsService = new google.maps.DirectionsService();
            this._directionsRenderer = new google.maps.DirectionsRenderer({ map: this._map });
        },

        onFindShipment: function () {
            const shipmentId = this.byId("searchField").getValue();
            if (!shipmentId) {
                MessageToast.show("Please enter a shipment ID.");
                return;  }

   // Fetch shipment details using OData service.
         /*   const oDataModel = this.getOwnerComponent().getModel(); // 
              Replace with your OData model.
            oDataModel.read(`/ShipmentSet('${shipmentNumber}')`, {
                success: (data) => {
                    const startCoords = data.StartCoords;
                    const endCoords = data.EndCoords;
                    this._displayRoute(startCoords, endCoords);
                },
                error: (error) => {
                    console.error("Failed to fetch shipment details:", 
                     error);
                    MessageToast.show("Unable to retrieve shipment 
                 details.");
                }
            }); */


            const startCoords = { lat: 30.0444, lng: 31.2357 };
            const endCoords = { lat: 31.2023, lng: 29.9014 };

            this._displayRoute(startCoords, endCoords);
        },

        _displayRoute: function (startCoords, endCoords) {
            const request = {
                origin: startCoords,
                destination: endCoords,
                travelMode: google.maps.TravelMode.DRIVING
            };

            const oModel = this.getView().getModel("route");

            this._directionsService.route(request, (result, status) => {
                if (status === google.maps.DirectionsStatus.OK) {
                    this._directionsRenderer.setDirections(result);

                    const route = result.routes[0];
                    const distance = route.legs[0].distance.text;
                    const steps = route.legs[0].steps.map((step) => ({
                        instruction: step.instructions.replace(/<[^>]+>/g, ''),
                        distance: step.distance.text
                    }));

                    oModel.setProperty("/steps", steps);
                    oModel.setProperty("/distance", distance);

                    MessageToast.show(`Total distance: ${distance}`);
                } else {
                    MessageToast.show("Unable to retrieve directions.");
                }
            });
        }
    });
});

 

 

 

 

 

Final Demo Video

Watch the application in action: 
Shipment Tracking - App.gif


Conclusion

With the combination of SAPUI5 and Google Maps API, our Shipment Tracking Application delivers a powerful solution for real-time logistics management. By following the provided setup instructions and integrating the Google Maps API securely, you can create an efficient and user-friendly tool for your business. 

Feel free to implement this application in your SAP projects and customize it as per your needs.
Happy coding! ðŸ˜‰

 

2 Comments