Google Maps on Tizen
PUBLISHED
1 Using Google Maps in Tizen web applications
The Google Maps service is a well known maps service. It allows you to access Google location-based services from your apps. It provides the intuitive UI, good user experience, and rich services such as finding locations, calculating directions, depicting traffic conditions and reviewing Google Street View images. With recently launched Google Street View service,you can even embed the Street View panorama images in your web apps. Google provides you very flexible JavaScript APIs and a set of HTTP based web services to use these features. Meanwhile, you can use the HTML5 W3C Geolocation API to get the location data from the device. We will show you how to do it in conjunction with Google Maps API in this article. There are two ways to use Google Maps in your web applications:
- Use existing Google Maps web services (HTTP API calls): This requires you to implement the callback of AJAX calls upon receiving the data from the Google server. Using AJAX calls to obtain data from remote servers may be difficult due to the same origin policy. Fortunately the Tizen web browser allows you to send AJAX calls regardless the security restrains.
- Use Google Maps API v3: It provides all JavaScript APIs that you need to develop fully featured location-based applications.
In this article we will cover both above cases.
2 Prerequisites
The attached example application utilizes Google Maps Web Services, Google Maps APIs and W3C Geolocation APIs. The UI is based on the jQuery Mobile 1.2.0framework. jQuery Mobile framework allows you to create highly scalable web applications with intuitive and coherent user interface. To be able to use jQuery Mobile, your application must include jQuery 1.8.0 library. For more about how to use jQueryMoible framework, find it from here (http://jquerymobile.com/). The sample application was tested on Tizen SDK 2.1.0.
Sample application screen shot
TIP
Web applications that heavily use AJAX calls and APIs that access remote servers should implement the on-demand Internet connection verification mechanism. On Tizen, you can use tizen.systeminfo device API. For more information, Please refer to the isInternetConnection method in ./js/lib/tlib/tlib.network.js file.
|
TIP
jQuery Mobile framework is designed to handle web pages from the HTTP server via the HTTP protocol, while the Tizen application is designed to use the FILE protocol. So we recommend to turn off AJAX page requests for using page transition as they will fail with the FILE protocol. Remember this is only for the page transition, You can use AJAX requests normally for other purposes on Tizen.
|
3 Basic Google Maps and Geolocation features
This article will show you how to use features from Google Maps API and Google Maps web services in your Tizen web application.
In location-based applications, you might want to get the current location of the device. You can get the current location using the W3C Geolocation API, and it is supported by Tizen. Once you obtain your current location, you can set it as the centre of the map. Attached example application will show you how to do it.
When we’re talking about “searching a location”, we actually perform a translation from a human-readable address to geographical coordinates. This process is called geocoding. Google Maps also provides the service called Google Distance Matrix. It allows you to calculate what the distance is between two given locations and how long it takes to get to the destination by various means of transportation, for example by car or by foot.
Additionally, Google also provides the Google Street View service, and it’s getting more and more popular. We can use some of the features in your Tizen Web Applications as well.
Warning: At the time of writing, not all Street View features are supported by Tizen, such as refreshing the panorama view We suggest you to use only the Google Street View Image API, which gives you the passive view. We will show you how to use it in the later section of this article.
a) Obtaining your position
W3C Geolocation API allows you to get the user’s position based on the GPS data. You can use this API to request one location at one time or track the user’s real-time location. Below is the example code of how to request a GPS location passive way. But it is not recommended to obtain real-time location updates (e.g. tracking user’s location) in this way. There is another API available from the navigator.geolocation
object to do that (navigator.geolocation.watchPosition
).
navigator.geolocation.getCurrentPosition(function(position) { console.log('Latitude: ' + position.coords.latitude + 'Longitude: ' + position.coords.longitude); }, function(error) { console.error('GPS error occurred'); });
b) Basic Google Map view
Once you have the current location of user, you can display the map. We use the basic Google Map view in our example. You can use the map view in Tizen in exactly the same way as you use it in your web sites. First, you create a container for a map.
<div id="map_canvas"></div>
Then you create the CSS stylesheet for this container. Normally you give the percentage value to the map container. It can be up to 100% of width and height of the entire screen. After that, you initialize the map using the map option object. Please remember the tip (you can find it at the end of this article) of turning off the Google Street View feature.
var mapOptions = { center : new google.maps.LatLng(52.33, 54.12), zoom : 6, // zoom value from 0 up to 18 mapTypeId : google.maps.MapTypeId.HYBRID, streetViewControl : false }; var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
c) Obtaining directions
You have the map displayed. Now we will show you how to get the directions between two places. There are two approaches to get the direction:
- Using the Google Directions Service: It is easier approach because you don’t need to send all AJAX requests by yourself.
- Using Google Directions API: This is the conventional web service accessed via the RESTful APIs. This approach is slightly more complex because you have to implement AJAX calls by yourself.
In this example we will use the first approach. To send the direction request, you only need to provide the origin and destination for the direction you want to find and the preference for the travel mode, for example, by car or by foot. The sample code is shown as below.
var directionsService = new google.maps.DirectionsService(); var directionsDisplay = new google.maps.DirectionsRenderer(); // we assume that the map is already defined and displayed directionsDisplay.setMap(map); var request = { origin : 'Warsaw', destination : 'Paris', travelMode : google.maps.TravelMode.DRIVING }; directionsService.route(request, function(result, status) { if (status === google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(result); } else { console.error('Unable to get directions'); } });
d) Geocoding
Geocoding service provides the translation between a human-readable address to geographic coordinates. It is one of the core services provided by Google Maps API and Google Maps web services. This API gives you the access to Google’s database. The locations you passed to the geocoding API can be a street name, a city name, or a region name. And geocoding API returns you the geographic coordinates from the server. The Geocoded data can be acquired using two approaches:
- Using Google Geocoding Service: This is an easier approach because you don’t need to perform all server AJAX requests by yourself.
- Using Google Geocoding API: It is a web service accessed by sending simple HTTP GET requests. This approach is slightly more complex because you have to perform AJAX calls by yourself.
In this example, we will go for more complicated approach. First, you send the AJAX call to Google Geocoding API using the following, sample URL: http://maps.googleapis.com/maps/api/geocode/json?address=[location_strin.... Where the location_string
is a URI encoded name of the location you want to geocode. Please remember that the Tizen web browser allows cross domain requests, if you run below script in a ordinary PC browser, it will fail due to same origin policy as we mentioned earlier. Tizen emulator and simulator doesn’t follow the same origin policy. After the AJAX request sent, you need to verify whether the returned geocoder status is OK, and see whether there are any valid values in the response.
var locationForGeocoding = "London"; $.ajax({ url : 'http://maps.googleapis.com/maps/api/geocode/json?address=' + locationForGeocoding + '&sensor=true', success : function(data) { if (google.maps.GeocoderStatus.OK === data.status && data.results.length !== 0) { /** * We take into account only first result returned from Google Maps * API */ var foundLocation = data.results[0]; console.log(foundLocation.geometry.location.lat); console.log(foundLocation.geometry.location.lng); // here we can use procedure to create map on a given container } else { console.error("Unable to find this location!"); } } });
e) Calculate the distance
In this section, we will explain how we use Google Maps distance matrix to find the nearest capital city around you. The Distance Matrix allows you to calculate the distance between two or more locations. You can either define locations in readable address, such as city name “Torino” which we used in our example. (In this case, the Google Geocoding service will automatically translate the address to geographical coordinates) or you can use geographical coordinates explicitly. The distance can be calculated using two approaches:
- Using Google Distance Matrix Service: This is an easier to approach because you don’t need to perform all server AJAX requests by yourself.
- Using Google Distance Matrix API: It is the web service accessed by sending simple HTTP GET requests. This approach is slightly more complex because you have to perform AJAX calls by yourself.
In this example we use the first approach. We will use the getDistanceMatrix()
method available from the DistanceMatrixService
object. The getDistanceMatrix()
method takes two arrays: The first one is the origin locations and the second one is the destination locations. The Distance Matrix API also allows you to set the sorting order for the returned directions, for example you can find the nearest route. In our sample application, it means the nearest capital city will be appeared first.
// this is the location given by the user var origin = "Torino"; // this is an array with destination locations // Google will use Geocoding to get coordinates var locations = [{ name : "London" }, { name : "Paris" }, { name : "Berlin" }, { name : "Moscow" }, { name : "Rome" }]; var service = new google.maps.DistanceMatrixService(); var destParsed = []; // Google Distance Matrix service accepts only simple arrays, not JSON // so we need to convert for (var i = 0; i < locations.length; i++) { destParsed[i] = locations[i].name; } service.getDistanceMatrix({ origins : [ origin ], destinations : destParsed, // we are using DRIVING mode travelMode : google.maps.TravelMode.DRIVING, // we don't want to avoid anything avoidHighways : false, avoidTolls : false }, function(response, status) { if (status == google.maps.DistanceMatrixStatus.OK) { if (response.rows.length === 0) { console.err("Unable to get distance"); return false; } // there is only one row so we can simply get it, // because there was only one origin location response = response.rows[0].elements; // because we do not want to change the original locations array // we can create a copy var locationsCopy = locations.slice(); for (i = 0; i < locationsCopy.length; i++) { if (response[i].status === "OK") { locationsCopy[i].distance = response[i].distance; } else { locationsCopy = locationsCopy.splice(1, i); } } // sorting var sorted = locationsCopy.sort(function (a, b) { return a.distance.value - b.distance.value; }); // here are our sorted results console.log(sorted); } else { console.error("Unable to get distance"); } });
f) Passive Google Street View
The final feature we introduced in this article is the Google Street View. The Google Street View was launched by Google in 2007. It allows you to review panorama street images at supported locations. You can use it in two different ways:
- Using Google Street View Image API: that allows you to get static images of all available destinations. You can pass the string based location to this API, and it will be translated into geographical coordinates automatically.
- Using Google Street View Service: allows you to access the street view with all available features. This unfortunately is not supported by Tizen
Here is the example code for the first option.
// location to find the street view for var loc = 'New York'; // your Google API key var key = 'AIzaSyDdKjhStoKF6t0xxA_hFxYBmKrEb77b-nQ'; // if needed, we create img HTML element to put the street view in it if ($(document.body).find('#streetViewImg').length === 0) { $(document.body).append($('<img alt="StreetView" id="streetViewImg">')); } // the browser will perform request for image $('#streetViewImg').attr('src', 'http://maps.googleapis.com/maps/api/streetview?size=640x640&location=' + loc + '&sensor=true&key='+key);
TIP We suggest to turn off Google Street View form every map (it is turned on by default) that is displayed in Tizen Web Application. Currently the performance of Google Street View with the most complex UI is not sufficient on Tizen.
var mapOptions = { center : new google.maps.LatLng(52.12, 54.23), zoom : 6, mapTypeId : google.maps.MapTypeId.HYBRID, streetViewControl : false // turns off Street View }; var map = new google.maps.Map(document.getElementById('container'), mapOptions); |
TIP In each jQuery Mobile project the viewport setting is essential. Current maximum resolution of Tizen equipped device is 720p, that stands for 720x1280. Unfortunately with this setting jQuery Mobile UI is very small and the UX for touching screen elements is poor. Viewport element configuration for 720p resolution.
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, height=device-height, target-densitydpi=device-dpi> So we suggest to use lower resolution 360x640 with following viewport setting: <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, height=device-height"> |
4 Summary
In this article, we explain how you can use Google Maps features such as displaying a basic map, searching a location, caculating the distance and accessing the Street View images in Tizen web apps. We also provide some tips, so that you can use these features in a easy and hassle-free way. As you probably already see, it doesn’t require much modifications to make them work on Tizen if you had these features on your web site already. Actually you probably get more benefits when you use the Google Maps on the mobile devices compared to the desktop environment since mobile devices are more suitable environment for location-based apps.