How to Build a Store Locator App Using Apple's Maps SDK for iOS and Google's Places API

Introduction to Store Locator for iOS using Google Maps

As mobile applications continue to grow in popularity, developers are faced with new challenges. One such challenge is creating a user-friendly interface that provides users with relevant information and services at their fingertips. In this blog post, we will explore how to create a store locator for an iOS application using Google Maps.

Understanding the Requirements

The ideal situation for our store locator is as follows:

  • The user enters their zip code.
  • A map displays the store locations within a radius of that zip code.
  • Locations can be stored in a Google Places account or within the app’s code.
  • Results can be displayed on both a map view and a list view.

We will explore how to achieve these features using Apple’s Maps SDK for iOS and integrate it with Google’s Places API.

Step 1: Setting Up the Project

To start, we need to create a new project in Xcode. We will also install the required frameworks:

  • GoogleMaps
  • GooglePlaces

We can do this by opening Xcode, selecting “Create a new Xcode project” and then choosing “Single View App”. In the project navigator, select the app delegate file (main.storyboard) and add the following lines of code to enable the Google Maps SDK for iOS:

// Import the necessary frameworks

import UIKit
import GoogleMaps

// Set up the map view

let mapView = GMMapView()
view.addSubview(mapView)

Step 2: Configuring the Map View

Now that we have set up our map view, let’s configure it to display the store locations.

  • We will use a custom MapViewDelegate to handle events such as marker clicks and location changes.
  • To get the store locations, we will need to download the data from a remote server or use an existing database.

Let’s assume that we have a function called downloadStoreLocations that downloads the store locations in JSON format:

// Function to download store locations

func downloadStoreLocations(completion: @escaping ([Location]?, Error?) -> Void) {
    // Download data from remote server or database
    let stores = [
        Location(name: "Store 1", latitude: 37.7749, longitude: -122.4194),
        Location(name: "Store 2", latitude: 37.7858, longitude: -122.4364),
        // ...
    ]

    completion(stores, nil)
}

Step 3: Displaying Store Locations on the Map

Now that we have our store locations, let’s display them on the map.

We can do this by creating a Marker for each location and adding it to the map view:

// Function to add markers to the map view

func addMarkers(toView view: GMMapView) {
    var markers = [GMMapMarker]()
    
    for store in stores {
        let marker = GMMapMarker(position: CLLocationCoordinate2D(latitude: store.latitude, longitude: store.longitude))
        
        // Add marker to map view
        marker.map = view
        
        // Animate the marker
        UIView.animate(withDuration: 0.5) {
            marker.alpha = 1.0
        }
        
        markers.append(marker)
    }

    for marker in markers {
        view.addSubview(marker)
    }
}

Step 4: Sorting and Displaying Store Locations

Now that we have our store locations displayed on the map, let’s sort them by distance from the user’s location.

We can do this by using the distanceFrom method of the CLLocationCoordinate2D struct to calculate the distance between two points:

// Function to calculate the distance between two points

func calculateDistance(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) -> Double {
    let lat1 = from.latitude * M_PI / 180.0
    let lon1 = from.longitude * M_PI / 180.0
    let lat2 = to.latitude * M_PI / 180.0
    let lon2 = to.longitude * M_PI / 180.0

    let dlat = lat2 - lat1
    let dlon = lon2 - lon1

    let a = pow(sin(dlat / 2), 2) + cos(lat1) * cos(lat2) * pow(sin(dlon / 2), 2)
    let c = 2 * atan2(sqrt(a), sqrt(1 - a))

    return 6371 * c
}

Step 5: Implementing the Store Locator

Now that we have our functions in place, let’s implement the store locator.

We will add a ZIPCode text field to the view controller and a button to download the store locations. When the button is clicked, we will call the downloadStoreLocations function and pass it a completion handler:

// Function to handle button click

@IBAction func downloadButtonClicked(_ sender: UIButton) {
    let zipCode = zipCodeTextField.text ?? ""
    
    if !zipCode.isEmpty {
        downloadStoreLocations { [weak self] stores, error in
            // Display the store locations on the map view
            guard let self = self else { return }
            addMarkers(toView: mapView)
            
            // Sort and display store locations by distance from user's location
            if let stores = stores {
                stores.sort { (store1, store2) -> Bool in
                    let distance1 = calculateDistance(from: CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194), to: store1.location)
                    let distance2 = calculateDistance(from: CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194), to: store2.location)
                    
                    return distance1 < distance2
                }
                
                // Add markers for sorted locations on the map view
                addMarkers(toView: mapView)
            } else if let error = error {
                print("Error downloading store locations:", error)
            }
        }
    } else {
        print("Please enter a zip code.")
    }
}

Conclusion

In this blog post, we explored how to create a store locator for an iOS application using Google Maps. We discussed the requirements of the project and implemented the necessary functions to download and display store locations on the map view.


Last modified on 2024-08-19