Guides
Last Updated Apr 25, 2024

Location Based Apps: How to Develop a Geolocation App

Doug Sillars

Table of Contents:

Get your free
API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required
Get your free
IP Geolocation API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Types of Location-Based Apps

Both iOS and Android offer SDKs to easily use geolocation during application development.  In this section, we’ll describe some of the methods your development team might use when building geolocation services on these two platforms.

Let’s send your first free
API
IP Geolocation API
call
See why the best developers build on Abstract
Get your free api

Using Location on Android

When utilizing Android-supported location services, your application must request access to location services functionality.  There are two categories of permission:

  • Foreground and background: A foreground application is being used by the user. For example - If you start up Uber, the application will gain access to your location. This permission persists if the app is still running another app is visible, or the screen is turned off. A background application can access your location even when the application is not in active use. Use cases include location-sharing applications or applications that use a geofence.
  • Precision: Your application can ask for a precise location ACCESS_FINE_LOCATION or approximate location ACCESS_COARSE_LOCATION. Fine location will be your exact location - within a few feet of your actual location, whereas coarse location is accurate to about 3 square kilometers (1.2 square miles).

The Tides app asks for precise location, but it can be changed to approximate.  The access is foreground only, but we can get more granular: while the app is being used, just this time, or reject access

Get Last Location

  • Once you have permission to use Location services in your application, a very useful API call is the getLastLocation() method. The advantage of this method is that the last location recorded on the device is probably very close to the actual location of the device. While potentially not as fresh as the actual GPS location, it is faster and uses significantly fewer device resources.

Using the Location Provider

When requesting a location on Android, a best practice is to ask for the last location for an initial pinpoint.

Aside:  This is a much better user experience than applications that use 0 latitude/0 longitude as a starting point.  If the map blips to the Atlantic Ocean off of Africa before zooming to your location - that’s what the app is doing.  Once you see it, you cannot unsee it.

When requesting a location, you have several parameters that can be utilized:

When requesting a location, you have several parameters that can be utilized:

setInterval() : How often (in ms) will the location be updated?

Priority: There are four levels of priority:

  • PRIORITY_HIGH_ACCURACY - This will use GPS to get the best possible accuracy.
  • PRIORITY_BALANCED_POWER_ACCURACY - This level balances accuracy for battery drain. Location is generally accurate to 100m. More likely to use dropdown#toggle" data-dropdown-placement-param="top" data-term-id="295364857" style="box-sizing: border-box; background-color: rgb(255, 242, 204);"dropdown#toggle" data-dropdown-menu-id-param="menu_term_295364857" data-dropdown-placement-param="top" data-term-id="295364857" style="box-sizing: border-box;"Wi-Fi or dropdown#toggle" data-dropdown-placement-param="top" data-term-id="295364891" style="box-sizing: border-box; background-color: rgb(255, 242, 204);"dropdown#toggle" data-dropdown-menu-id-param="menu_term_295364891" data-dropdown-placement-param="top" data-term-id="295364891" style="box-sizing: border-box;"Cell tower positioning over GPS.
  • PRIORITY_LOW_POWER - City-level location. Considered to use very low amounts of power.
  • PRIORITY_NO_POWER This level will use no power and will rely on location updates from other applications.

Here is a sample application that uses the last known location to quickly provide location access to the application:


import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Check for location permissions
        if (checkLocationPermission()) {
            // Permission granted, get last known location
            showLastKnownLocation();
        } else {
            // Request location permissions
            requestLocationPermission();
        }
    }

    private boolean checkLocationPermission() {
        return ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                == PackageManager.PERMISSION_GRANTED;
    }

    private void requestLocationPermission() {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                LOCATION_PERMISSION_REQUEST_CODE);
    }

    private void showLastKnownLocation() {
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        if (locationManager != null) {
            if (checkLocationPermission()) {
                // Get last known location
                Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                if (lastKnownLocation != null) {
                    // Use last known location
                    double latitude = lastKnownLocation.getLatitude();
                    double longitude = lastKnownLocation.getLongitude();

                    // Now you can do something with the latitude and longitude values
                    showToast("Latitude: " + latitude + "\nLongitude: " + longitude);
                } else {
                    showToast("Last known location is not available.");
                }
            } else {
                // Permission not granted, request again or handle accordingly
                showToast("Location permission not granted.");
            }
        }
    }

    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    // Handle location permission request result
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission granted, get last known location
                showLastKnownLocation();
            } else {
                // Permission denied, handle accordingly
                showToast("Location permission denied.");
            }
        }
    }
}

Ensure you have added the correct permissions in your manifest file.

Using Location on iOS

  • Location usage is framed similarly as it is for Android.
  • Foreground or background: Foreground access to the location is provided by the NSLocationWhenInUseUsageDescription key. If background usage is required, use NSLocationAlwaysAndWhenInUseUsageDescription.
  • When requesting location on iOS, you can request a one-time request requestLocation(), or a continuous request startUpdatingLocation() . This will run until the request is stopped stopUpdatingLocation(). Both of these methods will use GPS to get the location to a high level of accuracy.
  • iOS also offers the startMonitoringSignificantLocationChanges() , that will only update if large changes in location have occurred. This method uses Wi-Fi and cellular radio, not the GPS.
  • The following code uses the foreground access NSLocationWhenInUseUsageDescription to get a one-time location request:

import CoreLocation

class LocationManager: NSObject, CLLocationManagerDelegate {

    private var locationManager = CLLocationManager()

    func getCurrentLocation(completion: @escaping (Result<(latitude: Double, longitude: Double), Error>) -> Void) {
        // Set the delegate to receive location updates
        locationManager.delegate = self
        // Request location authorization
        locationManager.requestWhenInUseAuthorization()
        // Use the best accuracy for a one-time location request
        locationManager.desiredAccuracy = kCLLocationAccuracyBest

        // Request a single location update
        locationManager.requestLocation { (location, error) in
            if let error = error {
                // Handle error
                completion(.failure(error))
                return
            }

            if let location = location {
                // Location request successful
                let latitude = location.coordinate.latitude
                let longitude = location.coordinate.longitude

                // Call the completion handler with the result
                completion(.success((latitude, longitude)))
            }
        }
    }
}

Background location and geofencing

Geofencing is the creation of virtual fences in an area. When a target device enters (or leaves) the area, the user is alerted. Geofencing can be used for targeting advertising - “Get 15% off pumpkin spice lattes, today only with the Starbucks app” when a customer enters a geofence around a popular coffee shop.

Android

Geofencing requires background location access - it is unlikely that everyone has the Starbucks app open at every given minute! To prevent over-alerts, Android offers both GEOFENCE_TRANSITION_ENTER (the user has entered the geofence, and GEOFENCE_TRANSITION_DWELL (how long the user has been inside the geofence). So if they are driving through - the alert might not fire. Android suggests that geofence alerts may take 2 minutes to fire - as background location tracking is not as frequent to save battery.

iOS

iOS works much the same way. Once a user has crossed the boundary of your geofence, iOS waits 20 seconds to send the alert - making sure that the user is still on the same side of the geofence.

Location Based Apps Best Practices

Smartphones are mobile computers, and if your location can utilize the specific location of the device, you can better optimize the experience for your customers.  But there are privacy and “creepiness factors” that must also be taken into account when in the development process of your location-based application.

When using GPS location, your application is collecting the exact location of your user.  There are implications that you should understand before collecting this data.

Privacy:  How will your application store user data?  If your application is using precise location data, laws like GDPR and CPRA require specific actions to protect your customer’s data. While apps like Strava now hide the start/stop of your run (in order to not publicly broadcast your front door), Strava accidentally exposed the location of US military bases in Iraq and Afghanistan with a data release.

For fleet tracking apps (think UPS and FedEx, but also perhaps the delivery app for doordash Uber Eats, and the driver apps for Lyft and Uber, the precise location of your employees is a great way to track that everything is going as expected.

On a positive note, all users must grant permission to share location data with the application. Users can use the device settings to review all apps with location permission and revoke location access to any app.

Creepiness: It is important to know your target audience. For example, it is probably inappropriate to use precise locations to match in a dating app. Using the city-level location would be more acceptable (and possibly a lot safer for those on your application). It is also a key indicator of dating success.

Apps should broadcast the user’s current location with extreme discretion. For example, sharing your Uber ride with friends adds a level of safety.  Sharing your drive to grandma’s house gives grandma a heads-up as to your ETA.

Battery: When your customer’s device uses GPS, Wi-Fi, or Bluetooth to obtain the location, radio receivers are powered up to receive signals. These receivers use battery resources, so it is important to balance the frequency and accuracy of the location call with the amount of power drain that will result. If your location application can get your users out to the wilderness, but not back from the wilderness, you might have angry customers (or worse).

AT&T’s Drive Mode app suspends the delivery of Text messaging when your speed is over 25 MPH. By delaying SMS messages from arriving, distracted driving accidents can be decreased.  The initial version of the Android App used GPS location every 3 minutes to determine speed (even when you are sitting on your sofa watching Netflix).  This led to complaints about battery drain. The app has since been improved to use the Android Activity Recognition API to determine you are in a car, before using the GPS to measure speed.

Alternatives to Location-based services

Smartphone location-based services have resulted in the launch of entire industries.  But, there is also a mistrust of developers who misuse location data (“Why does my sudoku app need my location?”). So, what are the alternatives to using the location sensors in the device?

One such option is AbstractAPI’s IP Geolocation service.  When your application makes a call to your server, you’ll receive the IP address assigned to the mobile device.  Use the Geolocation API to look up the IP Address, and return a coarse location.  This requires a free API key that you can create when you sign in to AbstractAPI.

The request looks like this:


https://ipgeolocation.abstractapi.com/v1/?api_key=<apikey>&ip_address=<ip address>

This should be considered a very coarse location.  Your mobile data does not enter the “internet” when it hits the cell tower - it is carried to a data center owned by your cell carrier.  In my case, the API shows my location to be about 90 minutes by car away from my actual location.

One advantage to this approach is that your application will not require the granting of location permissions.  The downside to this is that you’ll have to be very careful in how you utilize location - for both accuracy and to not appear as if you are trying to circumvent any app store guidelines.

4.5/5 stars (12 votes)

Doug Sillars
Doug Sillars is a distinguished web development expert, specializing in JavaScript and APIs, and recognized as a Google Developer Expert and O’Reilly author. Renowned for simplifying intricate web technologies, he's a sought-after international keynote speaker and influential blogger. Doug's expertise spans across RESTful APIs, Node.js, and front-end development.
Get your free
IP Geolocation API
API
key now
Unlock the power of precise location services with Abstract's IP Geolocation API. Enhance your app's functionality and user experience by integrating it today!
get started for free

Related Articles

Get your free
API
IP Geolocation API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required