Obtaining device location
This section will make you learn about geolocation and how we can obtain our device location using PhoneGap. Geolocation provides us information about the longitude and latitude. The longitude and latitude are the information of our device's location. The Global Positioning System, which is also referred to as GPS and location inferred from network signals such as IP address, WiFi, RFID, and Bluetooth MAC addresses, and GSM/CDMA cell IDs are some common sources of location information. The API can or cannot return the device's actual location. After determining the device location, we can use this information in our application.
In the geolocation section, we can use geolocation.getCurrentPosition, geolocation.watchPosition, geolocation.clearWatch methods and these methods can have several arguments such as geolocationSuccess, geolocationError, geolocationOptions. We can also use Position, PositionError, and Coordinates objects.
Firstly, we will learn how to obtain the device's location, and then we will hook up with the two most important APIs, i.e., Google Places API and Google Maps API. We will also learn how we can get the latitude and longitude. There are hundreds of mobile apps that are available based on these APIs in the play store.
These are the following steps which we have to perform for obtaining the device location in PhoneGap:
1) Create a new project
Firstly, we will create a new PhoneGap project with a blank template. If you don't know how to create an app with a blank template, go through the PhoneGap project link.
2) Creating space for latitude and longitude
We will change the title in the head section and add a heading in the body section using <h1></h1> tags. We will create space for latitude and longitude using the <p></p> tags. We will also use <output></output> tag for both latitude and longitude with an ID.
3) Creating a window.onload function
In the next step, we will create a window.onload function. We know that this function will be called automatically when the window screen is loaded. We will add an event listener called the deviceready event, which we will be called as the init callback function.
4) Creating init callback function
5) Creating onSuccess and onError callback function
Now, we will create both the callback functions. The onError function will show an alert message defining error. The onSuccess function has a parameter called position. This function will get the latitude and longitude positions coordinates and show in the space created for latitude and longitude output. Both the functions will be coded in the following way:
In the next section, we will learn about how we can use this information with Google Places.