Hi readers!! I was just trying out integrating google maps
in ui5 application, so here I am with another tutorial blog. In this blog, I
will show you how to create Google developer API key and then how to use it in
sap ui5 application to integrate google maps.
To integrate Google Maps to sapui5 application, you will
need google map API. There are several
API 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. The google Maps JavaScript APIs will only work with a Browser key. APIs of
the same platform can use the same key.
Now before proceeding with sapui5, I will just quickly go
through with how to create a developer key and how we will use it in our sapui5
application.
- Go to the Google Developers Console.
- Create or select a project.
- Click Continue to enable the API and any related services.
- On the Credentials page, get a Browser key (and set the API Credentials).
Hereby, your API developer key will be created and then you
can use it in your application.
To specify a key, include it as the
value of a key parameter when
loading the API.
For example:
<script
async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
type="text/javascript"></script>
type="text/javascript"></script>
Hope you got the basic idea how to create your API key, now
that’s done, lets focus on how to use it in sap ui5 application.
Lets’ make an application, in which we will integrate
google maps.
Step 1 Create a
new Project in Eclipse, here I am naming it demo_GoogleMaps
Step 2 Now, in
the index.html file add the URL containing your API Key. Also add your first
page, here I have named it as app.view.xml.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible"
content="IE=edge">
<meta http-equiv='Content-Type'
content='text/html;charset=UTF-8'/>
<script src="resources/sap-ui-core.js"
id="sap-ui-bootstrap"
data-sap-ui-libs="sap.m"
data-sap-ui-theme="sap_bluecrystal"
data-sap-ui-resourceroots='{
"com.googlemaps":"./"
}'>
</script>
<script>
var app = new
sap.m.App({initialPage:"idapp"});
var page1 =
sap.ui.view({id:"idapp", viewName:"com.googlemaps.view.app",
type:sap.ui.core.mvc.ViewType.XML});
app.addPage(page1);
app.placeAt("content");
</script>
<script
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"
type ="text/javascript">
</script>
<style>
.myMap {
height: 100%;
width: 100% ;
}
</style>
</head>
<body class="sapUiBody"
role="application">
<div id="content"></div>
</body>
</html>
Step 3 In the
app.view.xml file and the following piece of code:
<core:View controllerName="com.googlemaps.controller.app"
xmlns="sap.m" xmlns:core="sap.ui.core"
xmlns:mvc="sap.ui.core.mvc"
xmlns:html="http://www.w3.org/1999/xhtml">
<App id="appMaps">
<mvc:XMLView id="mainView"
viewName="com.googlemaps.view.maps"></mvc:XMLView>
</App></core:View>
Here I have added new page, and named it as maps.view.xml. In
this page I will add the google maps.
Step 4 Now in the maps.view.xml
file I am placing a VBox and inside this VBox, I am placing three HBox. In the
first HBox, I am placing search field and the distance button and in the second
HBox, I am placing the input box for distance calculation. Lastly, in the third
HBox I will place the map.
<core:View height="100%"
controllerName="com.googlemaps.controller.maps"
xmlns="sap.m" xmlns:core="sap.ui.core"
xmlns:mvc="sap.ui.core.mvc"
xmlns:vbm="sap.ui.vbm" xmlns:l="sap.ui.layout"
xmlns:html="http://www.w3.org/1999/xhtml">
<Page id="mainPage"
enableScrolling="false" title="GMaps">
<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>
</Page>
</core:View>
Step 5 We will do most of the coding in
maps.controller.js file. I am adding
the code here, I will try to explain it step wise through comments.
sap.ui.controller("com.googlemaps.controller.maps", {
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(-34.397, 150.644),
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 Screen
Search a Place on the
map
Find
Distance among two places
On clicking a place on a map