Vous êtes sur la page 1sur 16

Home Tutorials jQuery Mobile Building an app with Google Maps & geolocation

If you find any errors, typos or have general feedback, select the text and click CTRL+ALT+ENTER.

Introduction
Appery.io provides the Google Maps component a convenient way to work with Google Maps. The main
benefit of using the Google Maps component is that you can simply drag it on the page, configure it via the
properties panel like any other UI component, and then use it as the Google Maps API via JavaScript.
This tutorial will show you how to use the Google Maps API when building a mobile app in Appery.io. You
will learn how to:

Show directions from point A to point B.

Place a marker or multiple markers.

Place multiple markers based on the data retrieved from the database.

Add layers (such as the traffic layer).

Fit the map to the bounds.

Retrieve current user location via Geolocation service and display it on the map as a marker with
custom icon.

The app will look like:

Try it yourself

Live demo
See the live demo of this app here.

Creating from the backup


You can create this from the backup (Download backup) to see how its built.
To create an app from the backup:
1. Click Create new app.
2. Type an app name.
3. Click From backup and select the project backup file.
4. Click Create.
You still have to create the database manually as described in this section below. If youve already created
the database, find theX-Appery-Database-Id:

And paste it to location_settings > database_id:

Before you begin

Tutorial level: intermediate.

Creating a new app


Create a new app in the App Builder. From the Apps page, enter an app name, and click Create. Youll see
a start page.

Building the UI
The UI will look like:

1. First, select the startScreen and change Predefined Screen Size to 480800 in the PROPERTIES panel:

2. Place the Map component on the page:

3. On the right, in the PROPERTIES panel, clear the Address value. Change the Zoom property to 2. Rename
the component togoogle_map, and, finally, set Dimension to 300px:

4. The Map component contains a predefined marker component. The marker is not needed in this tutorial,
because all the markers will be created programmatically. Select the marker by clicking on it or using
the breadcrumbs:

5. In the PROPERTIES panel to the right of the screen, clear the Address and Text properties. Also,
uncheck Visible:

6. Its time to add the buttons and input fields. Place the Button on the page and rename it (change
the Name property) toshow_directions. Change the Text property to Show directions:

7. Place two Input components below the show_directions button.


8. Rename the first Input to from and the second one to to. Change the Text properties of these inputs to the
locations you want. In this example, there is London for the from input, and Abu Dhabi for the to input:

9. Now, place the Button, which will trigger the marker placement. Change the buttons Text property
to Place marker and rename it to place_marker:

10. Next, add the Input component below the place_marker button. Rename it to
(change Name property) marker_location. Type in Text property location names, separated by a comma. For
example Chicago, Los Angeles, San Francisco:

11. Lastly, place three buttons on the page. Change the Text property of the first to Show traffic. Also,
rename it to show_traffic.
12. For the second button, change the Text property to Get markers from DB and rename it to get_markers.
13. For the third button, change the Text property to Show my location and rename it to show_my_location:

Thats all for the UI.

Adding services and local storage variables


Three services and four local storage variables need to be created for this app. One service will get locations
from the database, a second one will convert friendly location names to latitude and longitude values and the
third one is a Geolocation service which will be used to determine the users location.

Local storage variables


Create the following local storage variables by navigating to Project > Model and Storage > Storage:

markerLat.

markerLng.

currentLng.

currentLat.

markerLat

and markerLng variables will serve as temporary storage for the Google Geocoding service.

currentLng

and currentLat variables will take the current location values returned by by the Geolocation

service.

Here are how your local storage variables should look:

List service
Before importing the List service, lets create a database and collection. The app will retrieve collection data,
and markers will be added to the map based on it. Create a locations collection with the following structure:

In the screenshot above, there is a sample collection with the name locations, stored in the location database.
Once its done, go to the Appery.io Builder and import the List service:
1. From the Appery.io builder: CREATE NEW > Database Services, select your database (location, in this
example), expand thelocations data collection, and select the List service:

2. Click Import selected services.

Google Geocoding service


1. From the builder: CREATE NEW > Service, type name ConvertAddress and click Create Service:

2. In the Settings tab of the newly-created service, type the following URL:
1 https://maps.googleapis.com/maps/api/geocode/json

This is how the Settings tab should look:

3. Go to the Request tab and add two parameters address and sensor. Type a mock value for
the address parameter (for example Chicago) and false for the sensor parameter:

4. Switch to the Test tab and click Test. After the test finishes successfully, click Import as Response to
fill the Response data:

5. Go to startScreen and switch to the DATA tab. For datasource, select Service, and then
select ConvertAddress. Click Add. Rename the added service to convert_address:

6. Then, on the DATA tab, click Mapping for Success event, and create the following mapping:

7. Click Save and return. Now, for datasource, select Service and then
select location_locations_data_list_service (the name of this service is based on your database and collection

names). Click Add. Rename the added service toget_db_locations:

8. By clicking a checkbox next to the Add button of Success event, from a drop-down menu, choose Run
JavaScript, add the following code, and save:
1 for (var i = 0; i < data.length; i++) {
2
convert_address.execute({
3
'data': {
4
'address': data[i].location,
5
'sensor': false
6
}
7
});
8}

9. Theres only one more event left for the Google Geocoding service; it places markers based on the
converted values through the Google Geocoding service. Open the EVENTS tab, and add the following
event: convert_address > Success > Run JavaScript.
Then add the following JavaScript:
1
2
3
4
5
6
7
8
9
1
0
1
1

var markerLatLng = new google.maps.LatLng(localStorage.getItem('markerLat'),


localStorage.getItem('markerLng'));
var marker = new google.maps.Marker({
position: markerLatLng,
map: map,
title: data.results[0].address_components[0].long_name,
animation: google.maps.Animation.DROP
});
bounds.extend(markerLatLng);
map.fitBounds(bounds);

10. Click Save.

Geolocation service

1. From the builder: CREATE NEW > Service. Check Geolocation and click Create Service:

2. Go to startScreen and switch to the DATA tab. For datasource, select Device, and then
select GeolocationService. Click Add:

3. Then, on the DATA tab, click Mapping for the Success event, and create the following mapping:

4. Click Save and return.


5. Add a Run JavaScript event for the Success event of geolocation1 datasource:

6. Add the following JavaScript code and click Save:


1
2
3
4
5
6
7
8

var markerLatLng = new google.maps.LatLng(Apperyio.storage.currentLat.get(),


Apperyio.storage.currentLng.get());
var marker = new google.maps.Marker({
position: markerLatLng,
map: map,
icon: 'http://i.imgur.com/fDUI8bZ.png'
});

9
1 map.setCenter(markerLatLng);
0 map.setZoom(15);

This code will add a marker with custom icon on user position. Thats all for the services in this example.

Adding the JavaScript


Its helpful to keep the bigger part of the code in a separate JavaScript file.
1. From the builder: CREATE NEW > JavaScript, enter the name GoogleMapJS, and click Create JavaScript.
The new JavaScript file will be listed under the JavaScript folder.
2. Open the GoogleMapJS file and add the following code:
1
2
3
4
5
6
7
8
9
1
0
1
1
1
2
1
3
1
4
1
5
1
6
1
7
1
8
1
9
2
0
2
1
2
2
2
3
2
4
2
5
2
6
2
7
2
8
2
9
3
0
3
1
3
2
3

var
var
var
var

map;
directionsDisplay;
directionsService = new google.maps.DirectionsService();
bounds = new google.maps.LatLngBounds();

function initialize() {
console.log('Initializing...');
map = Apperyio("google_map").gmap;
if (!map) {
setDelay();
} else {
directionsDisplay = new google.maps.DirectionsRenderer();
}
}
function displayDirections(sourceAddress, destinationAddress, map) {
var request = {
origin: sourceAddress,
destination: destinationAddress,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
directionsDisplay.setMap(map);
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
alert("Directions query unsuccessful. Response status: " + status);
}
});
}
function setDelay() {
setTimeout(initialize, 50);
}

3
3
4
3
5

3. Save.

Adding events
Once the JavaScript file is ready, its time to map some events:
1. Open the DESIGN tab.
2. Select startScreen (use breadcrumbs), open the EVENTS tab, and add the following event: startScreen >
Load > Run JavaScript.
3. Add the following JavaScript code:
1 initialize();

4. Click Save.
Now we need to build the directions by clicking the show_directions button. Select
the show_directions button and the following event:
1. show_directions > Click > Run JavaScript.
2. Add the following JavaScript:
1 var sourceAddress = Apperyio("from").val();
2 var destinationAddress = Apperyio("to").val();
3 displayDirections(sourceAddress, destinationAddress, map);

3. Click Save.
By clicking the place_marker button, data is read from the input field marker_location and passed to the
service that converts location names to latitude and longitude. Select place_marker, and add the following
event: place_marker > Click > Run JavaScript.
4. Add the following JavaScript:
1
2
3
4
5
6
7
8
9
1
0
1
1

var locations = [];


locations = Apperyio('marker_location').val().split(",");
for (var i = 0; i < locations.length; i++) {
convert_address.execute({
'data': {
'address': locations[i],
'sensor': false
}
});
}

5. Click Save.
By clicking the show_traffic button, the traffic layer will be added to the map. Select the show_traffic button,
and add the following event: show_traffic > Click > Run JavaScript.
1. Add the following JavaScript:
1 var trafficLayer = new google.maps.TrafficLayer();
2 trafficLayer.setMap(map);

2. Click Save.
By clicking the get_markers button, data will be downloaded from the database, and location names will be
converted to latitude and longitude values. Select get_markers, and add the following event: get_markers >
Click > Invoke service > get_db_locations and click Save.

By clicking the show_my_location button, the Geolocation service will be triggered. Once the Geolocation
service will return success, the marker on the retrieved location will be added. Select show_my_location and
add the following event: show_my_location > Click > Invoke service > geolocation1.
Now, all startScreen events should look like:

The final app will look like:

To show traffic, you need to zoom in the map:

Using Google Maps API key


Read this thread if you want to use your own Google Maps API
key: https://getsatisfaction.com/apperyio/topics/how-to-use-your-own-google-maps-api-key

Vous aimerez peut-être aussi