By Kirby ShabagaSeptember 10, 2014

Google Places API and Swift

In case

MKLocalSearchRequest.naturalLanguageQuery 

isn’t meeting your nearby search needs, you may look at using other web services.

One option is the Google Places web service.

I wrote a GooglePlaces class that takes three input arguments (location, radius, and query) and returns an array of MKMapItems.

Two search functions are implemented, one with a callback, and one using delegation.

The examples below show how to search for coffee within 2000 meters of the Space Needle in Seattle, WA.

Google Places search with callback

var location = CLLocationCoordinate2D(latitude: 47.620506, longitude: -122.349277)
var gp = GooglePlaces()
gp.search(location, radius: 2000, query: "coffee") { (items, errorDescription) -> Void in

  println("Result count: \(items!.count)")
    for index in 0..<items!.count {
      println([items![index].name])
    }
}

Google Places search with delegate

var location = CLLocationCoordinate2D(latitude: 47.620506, longitude: -122.349277)
var gp = GooglePlaces()
gp.delegate = self

gp.searchWithDelegate(location, radius: 2000, query: "coffee")

Implement the delegate to process the result set

func googlePlacesSearchResult(items : [MKMapItem]) {
  println("Result count: \(items!.count)")
    for index in 0..<items!.count {
      println([items![index].name])
    }
}

Easy!


Check out more resources on Kirby’s blog, Swift Coder.