Every new jQuery Mobile app comes bundled with the Apache Cordova library which provides access to various native APIs. In this short tutorial you will learn how to use the Geolocation API. We also provide a short video.
To start you are going to create a new jQuery Mobile app.
- Go to Apps page and click Create new app link.
- Name the app GeolocationApp, select jQuery Mobile tab and then Blank template. Click the Create button.
After a few seconds, a new jQuery Mobile app will load in the App Builder.
Next step is to design the app UI. The UI will be simple, you will place a button on the page which will invoke the Geolocation and two labels to display the latitude and longitude information from the Geolocation service.
- In the app you just created, open Project > startScreen.
- Click the header inside the device, then in Properties change the Text property to Geolocation.
- Next drag and drop the Button component.
- Change the button's Text property to Show Location in the Properties panel.
- Drag and drop two Label components below the button. One will display the latitude, the other will display the longitude.
- Clear the default Label text from both buttons.
Your page should look like this:
In this step you are going to add the Geolocation service.
- Click Create new > Service. Check Geolocation service and click the Create Service button. Geolocation service will be added under Services folder.
As this service is a wrapper for the Cordova API, you don't need to edit the service. The next step is to use it on a page.
To add the service to a page:
- Open startScreen page, then switch to Data view.
- Select Device from the first list, then select GeolocationService and click Add.
For service input you are going to keep the default values so you only need to create mapping for service response.
- Click Mapping for Success event.
- Click Expand all on both sides of the mapping.
- Using drag and drop create the following mapping:
- Click Save and return button.
- Switch back to Design view.
The last step is to invoke the service.
To invoke the service:
- Click the button and open the Events tab.
- Double check that the button is selected in Component list and click event is select in Event.
- For Action select Invoke service > geolocation1 > Save.
You are now ready to test the app.
You are now ready to test the app. Click the Test button in the App Builder to launch the app in the browser.
Desktop browsers will try to use the IP address to determine the location. This should work in most cases, however the latitude/longitude information returned might be for a different location. It's best to test Geolocation on the actual device as you will get a lot more accurate results.
You can also easily test the app directly on the device by using the Appery.io Tester App