How to build location-aware mobile apps using Google Places API

Image for post
Image for post

Location-aware features in apps can provide much more help than simply detect your current whereabouts. Without geolocation in smartphones and tablets, it would have never been possible to search for a nearby movie theater, restaurant or store, choose an interesting event to attend or a place to visit, surf through a dating or social-networkingapp to find a new acquaintance in your neighborhood, or receive any real-time services through an app.

Image for post
Image for post

Location-based app development has changed the nature of the interaction between consumers and brands who now can reach their customers precisely at the right time and place. It has introduced new business services and marketing tactics.

In this blog post, you will take a deep insight into the typical features of a location-aware mobile app. You will also learn about technologies that stand behind their development.

Image for post
Image for post

What are location-based apps

Let’s make it clear what location-aware mobile application is. Both iOS and Android location-aware apps are apps that provide content to a user according to their immediate geographical location. People carry mobile devices everywhere they go. As a result, geolocation apps have become a useful tool that facilitates and speeds up the task of finding a place or a person in a big physical world.

Location details for aware apps are received through GPS/satellite, cell tower data, and Wi-Fi. With the built-in GPS, smartphones determine a user’s location coordinates. You can additionally enhance GPS with the help of mobile network and Wi-Fi. If a user is inside a building where GPS signal gets weaker, location awareness is often supported by Bluetooth.

Image for post
Image for post

Development of such mobile applications requires using maps and location services APIs. They provide information about closest objects and offer respective suggestions, directions and useful details about a place (website, phone number, working hours, etc.).

When it comes to app development, both Android and iOS platforms offer their own location-based APIs. For Android Studio, it is Android API for Google Maps, and for iOS, it is Apple Map Kit. Unfortunately, Apple Map Kit does not provide indoor navigation and route suggestions. Google Maps is cross-platform and works perfectly well both for Android phones, iPhones, and Windows phones.

What Google Maps APIs are used for geolocation based app development

Image for post
Image for post

Google Play services provide location APIs that simplify the process of adding location-aware features to a mobile app. Depending on your app idea and the geolocation features, you will need to use one of the four most popular Google Maps APIs.

  • Google Maps API provides the most popular map service in the world. Maps can be displayed right in a mobile app and be tailored to your brand color style. Places are filtered to include information that is most relevant to a user, help predict travel time and give directions to a user.
  • Google Places API is part of Google Maps APIs family and accessing more than 100 million places around the world. It provides precise and real-time information for mapping, navigation, business listings and interest points. Mobile app users receive detailed information about their current location and places nearby. With the autocomplete service, Google Places API also returns place predictions. These predictions are based on search queries that a user sees while typing.
  • Google Maps Directions API provides information about directions, starting from a current location to a destination. It displays different ways of getting there by walking and going by car, bike, or public transport.
  • Google Distance Matrix API calculates approximate travel time and distance (including traffic density) from a current user location to their destination and specifies the type of transport.

Let’s take a look at some of the groups of mobile apps that use geolocation to provide services to users.

What are some categories of location-based mobile apps

Geolocation has significantly broadened the list of mobile app categories that provide various services using an individual’s location.

  • Weather apps

We are all used to the regular checking of the weather forecast. Weather apps constitute the most popular category among geolocation-based applications. These location-aware apps provide information about current weather conditions, support forecast customization based on a user’s latitude and longitude and enable a real-time alert feature.

Below you can find examples of two popular Android apps for weather on Google Play, AccuWeather and GO Weather:

Image for post
Image for post
Image for post
Image for post
  • Navigation apps

The simplest use of geolocation is reflected in mobile apps that provide assistance in getting around a place. These include directions, street views, trip and route planning, and real-time traffic updates.

  • Health and sports apps

Geolocation is perfectly combined with walking, running, cycling and swimming activities. Fitness tracking apps have become extremely popular among more than half of smartphone users.

  • Travel apps

Most travelers make preparations for their holidays and trips ahead of time. Location-aware apps give recommendations, such as where to stay, where to go, what to see, and what route to take.

  • On-demand services apps

With geolocation you can request taxi or product delivery and enjoy a vast number of other nonconventional services: booking a home massage, ordering laundry and dry cleaning delivery, requesting childcare services and getting a dog-sitter for your pet.

Below you can find examples of two popular on-demand apps with geolocation, Uber and Domino’s:

Image for post
Image for post
Image for post
Image for post
  • Dating and social networking apps

Today’s dating apps use geolocation to match a user with people who have been to the same places or have walked past the user within several hundred meters. Such apps have learned to indicate where your paths have intersected and when.

  • Game apps

Game apps offer real-time challenges for outside fun and interaction with the surrounding world. Running games with a scary plot, augmented reality with quests, and treasure hunting apps are a few examples of creative geolocation use.

Image for post
Image for post

How you can use Google Places to create an app

Before Google Places came to exist, offering location services through mobile apps was a complicated task for developers. They could only rely on longitude and latitude coordinates. Google Places API signaled the beginning of the era of location-aware apps.These applications point to a set of basic coordinates and provide rich descriptive information about venues. Details about places include their ID and name, type of place and other similar places located close to a user, contact information and place reviews from other users (if available).

Below we’ll see how Google Places API was used to build Wine Picker, an iOS and Android app that assists users with making the best wine choice and uses a unique wine selection algorithm. The app takes into account user location and their wine preferences and helps select wine at any given restaurant.

Image for post
Image for post

How to create a location-based app using Google Places API

Wine Picker searches for restaurants using Google Places API and performs wine selection from a wine list at a specific restaurant. Caching of search location data and regular data updates are integrated into the app independently of the platform.

Before we could start working on geolocation features for Wine Picker, we needed to register the project with Google Places services and obtain an API key. When working with the API key, we had to consider the approximate number of queries that would be processed by the app per 24 hour period. This was important because this number is limited by Google Places.

You can use your API key without identity verification if the limit does not exceed 1,000 requests per 24 hour period. This was not an option for Wine Picker app at all. The upper limit for an API key comes when the number of queries gets to 150,000 per 24 hour period. If the app goes beyond the default limit for requests, it will start failing.

Our goal was to be able to process as many requests as possible and remain within the upper limit of requests, so our team made a decision to cache data on locations into the app’s database. Also, we created a rule for data caching. If a user at Location A uses Wine Picker, information about restaurants in that area will be collected and cached, so when another user uses the app at Location A, they will get the cached information about restaurants that was obtained from the previous user.

To enable the geolocation functionality for Wine Picker, four Python scripts are launched. The app must process a user’s coordinates, search locations, gather information about restaurants and their wine lists, cache location data and conduct updates of cached data.

  • System initiation script

The first script wine-picker/require_once/update_city_bboxes.py gets started only once in order to initiate the system in case of transferring to a new server or the Places’ current database is empty. The system obtains information about 45 cities around the world, including 15 major locations located in Europe, 15 cities in the U.S. and 15 major cities from three other continents.

The initiation script processes this list of places, finds their coordinate values and saves the information into the database (city_bboxes is created).

City boundaries need to be determined so that a user could use location-based information in their Wine Picker app. We retrieve this data through Nominatim API, a search engine for OpenStreepMap data (bounding box).

Determining city boundaries in a convenient format was the first considerable challenge for our team of developers. Our decision for Wine Picker is based on the use of squares, an unconventional approach that helped keep the process simple and fast for implementation.

A response contains the coordinates of a rectangle framing the city. If a response provides multiple bounding boxes, the script selects the largest bounding box square.

Once the initial information about restaurants is received, the next task for the app is to perform location search in the boundaries of each selected city. This is where the second script launches.

  • Coordinates processing script

The second script wine-picker/require_once/update_place_list.py is started only once, after the first script, to initiate the system. It processes city coordinates from the database (from the table city_bboxes). Our goal here is to divide each of the 45 cities into 3km x 3km squares and search for restaurants within each square.

Using Google Places API, the app determines a user’s location and searches for restaurants in 500 meters proximity from a user.

If a 3km x 3km square contains more than 20 restaurants (equal to one Google page), the square is divided into 4 squares and search is performed in the current square once again. The action is repeated until 20 or fewer restaurants per square are left. The pointer to the next page is the indicator of square division.

Once 20 or less places have been found, their IDs are automatically added to the database (table temp_place_caching, which is a queue for processing).

  • Cached places processing script

wine-picker/cron-5-minutes/cache_google_places is the script that processes cached places. It is started every 5 minutes and for processing it fetches restaurants in batches of 100 from table temp_place_caching.

The script checks whether the restaurants are present in the database and when the latest update of those restaurants was made.

For a place that was updated in the past 45 days, the system designates it as updated and removes its ID from table temp_place_caching. If more than 45 days has passed, the system retrieves information about the place using Google Places API, Place Details.

The script conducts check whether the restaurant is closed (parameter permanently_closed). If the response is empty or shows permanently_closed=TRUE, the place with all its data is deleted from the database (from table temp_place_caching).

If a place was not updated in the past 45 days and is not permanently closed, the place gets updated. The following parameters are processed for Wine Picker app:

  • opening_hours (conversion to json);
  • photo (if there are multiple photos, the system selects the first one and processes the reference for a hyperlink to the photo);
  • type verification (is_geo_object).

Using types parameter from the response on places, the type of the place is determined by search in the following list:

‘administrative_area_level_1’,

‘administrative_area_level_2’,

‘administrative_area_level_3’,

‘administrative_area_level_4’,

‘administrative_area_level_5’,

‘colloquial_area’,

‘country’,

‘floor’,

‘geocode’,

‘intersection’,

‘locality’,

‘natural_feature’,

‘neighborhood’,

‘political’,

‘post_box’,

‘postal_code’,

‘postal_code_prefix’,

‘postal_code_suffix’,

‘postal_town’,

‘premise’,

‘room’,

‘route’,

‘street_address’,

‘street_number’,

‘sublocality’,

‘sublocality_level_4’,

‘sublocality_level_3’,

‘sublocality_level_2’,

‘sublocality_level_1’,

‘subpremise’,

‘transit_station’,

If any of the parameters is present in the place’s type parameter, it is designated as is_geo_object= true and is excluded from a response during restaurants search, but remains in the places table (general table of places) and is used during autocomplete search.

In case, Google reviews are found, they get stored in a separate table (place_reviews) with the following parameters: restaurant ID, author’s name, photo of the author, review text, and author’s rating.

place_id,

one_review.get(‘author_name’),

self.gplace.get_google_user_image_url(one_review.get(‘author_url’)),

one_review.get(‘text’),

one_review.get(‘rating’),

one_review.get(‘time’)

Users’ reviews are added every time a restaurant is updated. The app’s database filters duplicates using unique fields (place_id, timestamp, name (comparing the first 10 characters of the author’s name). The review data is necessary for calculating the users’ evaluation histogram on the restaurant’s details screen. This is how the histogram calculation function is performed:

max_rating = max(ratings.values())

weight = 100 / float(max_rating)

histogram = {

‘avoid’: int(ratings[1] * weight),

‘poor’: int(ratings[2] * weight),

‘fair’: int(ratings[3] * weight),

‘good’: int(ratings[4] * weight),

‘great’: int(ratings[5] * weight),

}

values — user’s highest rate

Currency for restaurant places is determined based on the code of the country in which it is located (e.g., GB for British pound sterling, USD otherwise).

currency = defaultdict(lambda: u’$’)

currency[‘GB’] = u’£’

A restaurant’s updated parameters are added to the general places table. This script also functions during search of restaurants, map scrolling, and any place-related request. Restaurants are not updated if there are no requests for them.

  • Places updating scripts (for search of new and closing old places)

When a map is scrolled or search for new restaurants is performed, the system receives the radius of the application displays at a given moment in time and location coordinates (screen center) from a request sent by a user.

Using the script, the system receives the places (up to 60 places):

  • If the square contains less than 60 places, the places are saved by adding their IDs to the temp_place_caching table;
  • If there are 60 places, the location coordinates and the radius are entered into table temp_coords_caching (presuming there are other places present in the square);
  • every 5 minutes the system starts script wine-picker/cron-5-minutes/google_place_grabber which uses temp_coords_caching and receives places by dividing the square determined by the coordinates and radius.

That square, determined by the location coordinates and radius from the table, is divided into 4 squares. If any of the smaller squares has more than 20 places, it is divided into 4 once again, and so on, until one square has 20 or fewer places. Once 20 or less places have been found, their IDs are added to temp_place_caching, to the queue to be processed.

To update places data, script wine-picker/cron-5-minutes/cache_google_places (cached places processing script) is started every 5 minutes. It fetches places to process from the temp_place_caching table.

The use of Google Places API described above allows users of Wine Picker to use this app when they are traveling around the country and even around the world. The app performs a thorough place search so that a user receives the ultimate choice in taste preferences and pricing among various available possibilities.

You can find out more details about Wine Picker app development by checking our case study here.

READ THE CASE STUDY

Image for post
Image for post

FOLLOW US:

Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post

Written by

Onix-Systems provides IT services in website, mobile app and emerging technologies software development. Check our blog -> https://onix-systems.com/blog

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store