- PhoneGap 4 Mobile Application Development Cookbook
- Zainul Setyo Pamungkas
- 1303字
- 2021-07-09 21:26:48
Retrieving map data through geolocation coordinates
In this recipe, we will examine how to render a map on the screen and generate a marker based on latitude and longitude coordinates reported by the device geolocation sensors using the Google Maps API for JavaScript.
Getting ready
Before we can continue with coding the application in this recipe, we must first prepare the project and obtain access to the Google Maps services:
- First, sign up for a Google Maps API key. Visit https://code.google.com/apis/console/ and log in with your Google account.
- Select APIs & auth followed by APIs from the left-hand side menu and activate the Google Maps JavaScript API v3 service.
- Once the service has been activated, you must create a new credential. Go to APIs & auth | Credentials, and under Public API access select Create new Key. Select Server key and hit Create. A new key will be created for any IPS.
We can now proceed with the recipe.
How to do it…
We'll use the device's GPS ability to obtain the geolocation coordinates, build and initialize the map canvas, and display the marker for our current position as follows:
- First, create a new PhoneGap project named
maps
by running the following command:phonegap create maps com.myapp.maps maps
- Add the device platform. You can choose to use Android, iOS, or both:
cordova platform add ios cordova platform add android
- Add the geolocation plugin by running the following command:
phonegap plugin add org.apache.cordova.geolocation
- Open
www/index.html
and clean up unnecessary elements; so you have the following:<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="format-detection" content="telephone=no" /> <meta name="msapplication-tap-highlight" content="no" /> <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" /> <title>You are here</title> </head> <body> <script type="text/javascript" src="cordova.js"></script> <script type="text/javascript"> // Custom code goes here </script> </body> </html>
- Include the required JavaScript for the Google Maps API under the Cordova reference. Append your API key to the query string in the script
src
attribute:<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=your_api_key&sensor=true"> </script>
Note
When we included the Google Maps API JavaScript into our document, we set the
sensor
query parameter totrue
. If we were only allowing the user to manually input coordinates without automatic detection, this could have been set tofalse
. However, we are using the data obtained from the device's sensor to automatically retrieve our location. - Start creating the custom code within the JavaScript tag block. First, create the event listener to ensure the device is ready and also create the
onDeviceReady
method, which will run using the listener:// Set the event listener to run when the device is ready document.addEventListener( "deviceready", onDeviceReady, false); // The device is ready, so let's // obtain the current geolocation data function onDeviceReady() { navigator.geolocation.getCurrentPosition( onSuccess, onError ); }
- Next, write the
onSuccess
method, which will give you access to the returned location data via theposition
object. - Take the
latitude
andlongitude
information obtained from the device geolocation sensor response and create alatLng
object to be sent into theMap
when the component is initialized. - Then set the options for the
Map
, setting its center to the coordinates set into thelatLng
variable. Not all of the Google Maps controls translate well to the small screen, especially in terms of usability. You can define which controls you would like to use. In this case, acceptzoomControl
but notpanControl
. - To define the
Map
itself, reference adiv
element and pass it through themapOptions
previously declared. - To close this method, create a
Marker
to display at the exact location as set in thelatLng
variable:// Run after successful transaction // Let's display the position data function onSuccess(position) { var latLng = new google.maps.LatLng( position.coords.latitude, position.coords.longitude); var mapOptions = { center: latLng, panControl: false, zoomControl: true, zoom: 16, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map( document.getElementById('map_holder'), mapOptions ); var marker = new google.maps.Marker({ position: latLng, map: map }); }
- To ensure that you correctly handle any errors that may occur, include the
onError
function, which will display the specific string message according to the error within adiv
element:// Run if we face an error // obtaining the position data function onError(error) { var errString = ''; // Check to see if we have received an error code if(error.code) { // If we have, handle it by case switch(error.code) { case 1: // PERMISSION_DENIED errString = 'Unable to obtain the location information ' + 'because the device does not have permission '+ 'to the use that service.'; break; case 2: // POSITION_UNAVAILABLE errString = 'Unable to obtain the location information ' + 'because the device location could not be ' + 'determined.'; break; case 3: // TIMEOUT errString = 'Unable to obtain the location within the ' + 'specified time allocation.'; break; default: // UNKOWN_ERROR errString = 'Unable to obtain the location of the ' + 'device due to an unknown error.'; break; } } // Handle any errors we may face var element = document.getElementById('map_holder'); element.innerHTML = errString; }
- With the
body
tag, include thediv
element into which the map will be displayed:<body> <div id="map_holder"></div> </body>
- Finally, add a
style
block within thehead
tag to supply some essential formatting to the page and themap
element:<style type="text/css"> html { height: 100% } body { height: 100%; margin: 0; padding: 0 } #map_holder { height: 100%; width: 100%; } </style>
- Upon running the application on the device, you will see a result similar to the following:
How it works...
Thanks to the use of exposed mapping services such as Google Maps, we are able to perform geolocation updates from the device and use the obtained data to create rich, interactive visual mapping applications.
In this example, we centered the Map
using the device coordinates and also created a Marker
overlay to place upon the mark for easy visual reference.
The available APIs for mapping services such as this are incredibly detailed and contain many functions and methods to assist you in creating your location-based tools and applications. Some services also set limits on the number of requests made to the API, so make sure you are aware of any restrictions in place.
In this recipe, we used the dynamic Google Maps API. We did this so that we could use the zoom controls and provide our user with a certain level of interaction by being able to drag the map. As an alternative, you could use the Google Static Maps service, which simplifies the code needed to generate a map and will return a static image showing the location.
You can choose to use an API key with this service, but it is not required. You will still have to enable the API in the same way the API access was enabled at the start of this recipe.
Consider the following code. It is an amendment to the onSuccess
method, which runs after the geolocation data has been obtained:
// Run after successful transaction // Let's display the position data function onSuccess(position) { var mapOutput = '<img src="http://maps.googleapis.com/maps/api/staticmap?center='+position.coords.latitude+','+position.coords.longitude+'&zoom=12&size=300x300&scale=2&sensor=true">'; var element = document.getElementById('map_holder'); element.innerHTML = mapOutput; }
Here, instead of creating the coordinates, the map, and the markers as in the earlier code listing, we simply request an image source using the Static Maps API, and send in the coordinates, image size, and other data as parameters.
By using the Static Maps API, you lose the interactivity offered through the dynamic map, but you gain an incredibly simple, easy-to-use service that requires very little code to achieve results.
There's more…
We used the Google Maps API for JavaScript in this recipe. There are variations in the API level offered by Google, and other mapping systems are also available through other providers, such as MapQuest, MultiMap, and Yahoo! Maps. Explore the alternatives and experiment to see if a particular solution suits your application better than others.
See also
- You can find out more about the Google Maps API from the official documentation at https://developers.google.com/maps/documentation/javascript/.
- You can also find out more about the Google Static Maps API on the official documentation, available at https://developers.google.com/maps/documentation/staticmaps/.
- Learning Scala Programming
- Kubernetes實戰
- 自己動手實現Lua:虛擬機、編譯器和標準庫
- Windows系統管理與服務配置
- 用Python實現深度學習框架
- 利用Python進行數據分析(原書第3版)
- Learning Three.js:The JavaScript 3D Library for WebGL
- 深入剖析Java虛擬機:源碼剖析與實例詳解(基礎卷)
- Mastering Web Application Development with AngularJS
- IBM Cognos TM1 Developer's Certification guide
- Magento 2 Beginners Guide
- INSTANT Apache ServiceMix How-to
- JavaScript Concurrency
- JavaScript Mobile Application Development
- Natural Language Processing with Python Cookbook