Giter Site home page Giter Site logo

hkellaway / hnkgoogleplacesautocomplete Goto Github PK

View Code? Open in Web Editor NEW
84.0 9.0 26.0 3.02 MB

[DEPRECATED] Obj-C wrapper for the Google Places Autocomplete API :mag:

Home Page: https://cocoapods.org/pods/HNKGooglePlacesAutocomplete

License: MIT License

Objective-C 95.92% C 2.63% Shell 1.35% Ruby 0.11%

hnkgoogleplacesautocomplete's Introduction

HNKGooglePlacesAutocomplete

CocoaPods Objective-C License CocoaPods Build Status

An Objective-C wrapper for the Google Places Autocomplete API

Background

HNKGooglePlacesAutocomplete is an Objective-C wrapper for the Google Places Autocomplete API. It encapsulates the same core functionality as SPGooglePlacesAutocomplete - autocomplete suggestions and Google Place-to-CLPlacemark translation - with the intention of modernizing the approach.

Improvements include:

  • Modern, vetted pods utilized (AFNetworking, Mantle)
  • Code is well-tested using Kiwi
  • Documentation is thorough
  • Designed for reusability and dissemination with CocoaPods

Communication

  • If you have found a bug, and can provide steps to reliably reproduce it, open an issue.
  • If you have a feature request, open an issue.
  • If you want to contribute, submit a pull request. Pull request should be made against the develop branch.

Dependencies

Mantle

As of version 1.1, HNKGooglePlacesAutocomplete uses Mantle 2.0. If you require Mantle 1.x, version 1.0.1 can be used - however, note that that only version 1.1+ will incorporate new updates.

Getting Started

Installation with CocoaPods

CocoaPods is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries like HNKGooglePlacesAutocomplete in your projects. CocoaPods is the preferred way to incorporate HNKGooglePlacesAutocomplete in your project; if you are unfamiliar with how to install CocoaPods or how create a Podfile, there are many tutorials online.

Podfile

pod "HNKGooglePlacesAutocomplete", "~> 1.1"

API

Docs

The models present in HNKGooglePlacesAutocomplete directly reflect the objects provided by the Google Places Autocomplete API - review that documentation to get a full picture of what data is provided by a Place.

Bear in mind that the CLPlacemark convenience method can also be used to obtain additional location-related information.

Key

HNKGooglePlacesAutocomplete uses the Google Places Autocomplete API. You will need an API key for this service in order to use HNKGooglePlacesAutocomplete.

  • Create a Google Developer account
  • Create a new Project
  • Turn on the Google Places API Web Service
  • Find your API key in your Project's API Credentials

CoreLocation Framework

HNKGooglePlacesAutocomplete makes use of the CoreLocation framework. Make sure this framework is added in your Xcode settings.

Classes

Core Classes

These classes form the core functionality of HNKGooglePlacesAutocomplete

  • HNKGooglePlacesAutocompletePlaceQuery - used to query the API for Place suggestions
  • HNKGooglePlacesAutocompletePlace - Place object returned from a Query

Utilities

  • CLPlacemark+HNKAdditions.h - provides translation from HNKGooglePlacesAutocompletePlace to CLPlacemark

Usage

Setup

Requests cannot be made without first supplying HNKGooglePlacesAutocomplete with your Google Places API Key (see API Key). Once your API key is obtained, you can setup HNKGooglePlacesAutocomplete for use by calling setupSharedQueryWithAPIKey: on HNKGooglePlacesAutocompleteQuery (typically within the AppDelegate):

setupSharedQueryWithAPIKey:

[HNKGooglePlacesAutocompleteQuery setupSharedQueryWithAPIKey:@"YOUR_API_KEY"];

You should replace YOUR_API_KEY with your Google Places API key.

Queries

HNKGooglePlacesAutocompleteQuery is responsible for handling queries for Places. Once Setup is complete, queries can be made to [HNKGooglePlacesAutocopmleteQuery sharedQuery].

fetchPlacesForSearchQuery:completion:

[[HNKGooglePlacesAutocompleteQuery sharedQuery] fetchPlacesForSearchQuery:@"Amoeba" 
	completion:^(NSArray *places, NSError *error)  {
    	if (error) {
        	NSLog(@"ERROR: %@", error);
    	} else {
        	for (HNKGooglePlacesAutocompletePlace *place in places) {
	        	NSLog(@"%@", place);
			}
    	}
    }
];

The completion block provides an array of HNKGooglePlaceAutcompletePlace objects when successful. If not successful, error information can be found in the error object.

Places

HNKGooglePlacesAutocompletePlace objects are returned from Queries and represent the suggested Places for that Query.

CLPlacemark from Place

HNKGooglePlacesAutocomplete comes with a category that facilitates translating HNKGooglePlacesAutocompletePlaces to CLPlacemarks - this is often used when placing pins on a Map. To translate a Place to a CLPlacemark, first include the proper header: #import "CLPlacemark+HNKAdditions.h". Then call as follows:

hnk_placemarkFromGooglePlace:apiKey:completion:

[CLPlacemark hnk_placemarkFromGooglePlace:place
	apiKey:YOUR_API_KEY
  	completion:^(CLPlacemark *placemark, NSString *addressString, NSError *error) {
    	if(error) {
    		NSLog(@"ERROR: %@", error);
    	} else {
    		NSLog(@"PLACEMARK: %@", placemark);
    	}
    }
];

You should replace YOUR_API_KEY with your Google Places API key; hnk_placemarkFromGooglePlace uses your API key to query the Google Place Details API if needed.

For convenience, the API key you provided HNKGooglePlacesAutocompleteQuery during setup is available as a property: [HNKGooglePlacesAutocompleteQuery sharedQuery].apiKey

Advanced Topics

The core functionality needed to use HNKGooglePlacesAutocomplete is described in Setup, Queries, Places, and CLPlacemark from Place. The following sections describe additional topics that may be of use in particular situations.

Errors

Errors returned by HNKGooglePlacesAutocomplete have a domain that starts with com.hnkgoogleplacesautocomplete.

A short description of the error can be found in the error object's localizedDescription property.

If the error has an underlying error, such as an error returned by CLGeocoder, it can be found in the error object's userInfo dictionary, via the NSUnderlyingError key.

Advanced Query Topics

Querying with Optional Parameters

Optional parameters can be used to restrict the results returned by the Google Places API in certain ways.

  • HNKGooglePlacesAutocompleQueryConfig - object used to supply optional parameter values for requests

Configuration properties include:

  • country - the country within which to restrict results; must be a a two character, ISO 3166-1 Alpha-2 compatible country code, such as "fr" for France
  • filter - an HNKGooglePlacesTypeAutocompleteFilter value that restricts results to specific Place Types
  • language - the language in which results should be expressed; must be one of Google's supported domain languages
  • latitude & longitude - the location to which results should be biased
  • offset - how many characters are used in the request
  • searchRadius - the distance in meters within which to bias results
fetchPlacesForSearchQuery:configurationBlock:completion:

In addition to fetchPlacesForSearchQuery:completion:, HNKGooglePlacesAutocompleteQuery provides fetchPlacesForSearchQuery:configurationBlock:completion: to allow optional parameters to be applied to individual Queries.

[[HNKGooglePlacesAutocomplete sharedQuery] fetchPlacesForSearchQuery:@"Amo"
	configurationBlock:(HNKGooglePlacesAutocompleteQueryConfig *config) {
		config.country = @"fr";
        config.filter = HNKGooglePlaceTypeAutocompleteFilterCity;
        config.language = @"pt";
	}
	completion:^(NSArray *places, NSError *error)  { 
		// Completion here 
	}
];

Any or all of the Query Configuration properties can be set in the configurationBlock. If not set, default values will be used.

The example above specifies that the Places returned should be restricted to France, should be cities, and should be listed in Portuguese.

If a certain Query Configuration should be used for every query, then setup should include a Query Configuration, via setupSharedQueryWithAPIKey:configurationBlock:.

Default Query Configuration

Every HNKGooglePlacesAutocompleteQuery has a configuration whether one is explicitly supplied or not.

The default configuration values are:

  • country = nil
  • filter = HNKGooglePlacesTypeAutocompleteFilterAll
  • language = nil
  • latitude and longitude = 0 (Google's way of indicating no location bias)
  • offset = NSNotFound
  • searchRadius = 20000000 (Google's way of indicating no specific search radius)

Advanced Setup Topics

setupSharedQueryWithAPIKey:configurationBlock:

In addition to setupSharedQueryWithAPIKey:, HNKGooglePlacesAutocompleteQuery provides setupSharedQueryWithAPIKey:configurationBlock: to specify optional parameters to be applied to every Query.

[HNKGooglePlacesAutocompleteQuery setupSharedQueryWithAPIKey:@"YOUR_API_KEY"
	configurationBlock:(HNKGooglePlacesAutocompleteQueryConfig *config) {
		config.country = @"jp";
        config.filter = HNKGooglePlaceTypeAutocompleteFilterEstablishment;
        config.language = @"ru";
	}
];

The example above specifies that the Places returned from every Query should be restricted to Japan, should be business establishments, and should be listed in Russian.

Advanced Place Topics

Place Substrings

  • HNKGooglePlacesAutocompletePlaceSubstring

HNKGooglePlacesAutocompletePlace objects have an array of substrings that describe the location of the entered term in the prediction result text - this is useful if the application is to highlight the user's query text in the result Place suggestions.

For example, if a user typed "Amoeba" and a resulting Place suggestion had a name of "Amoeba Music, Telegraph Avenue, Berkeley, CA, United States", the substrings array would contain one entry indicating that the phrase "Amoeba" was in that name from character 0 to 6.

Place Terms

  • HNKGooglePlacesAutocompletePlaceTerm

HNKGooglePlacesAutocompletePlace objects have an array of terms that identify sections of the returned name.

For example, if a user types "Amoeba" and a resulting Place suggestion had a name of "Amoeba Music, Telegraph Avenue, Berkeley, CA, United States", the terms array would contain entries indicating that the name was composed of the terms "Amoeba Music", "Telegraph Avenue", "Berkeley", "CA", and "United States".

Credits

HNKGooglePlacesAutocomplete was created by Harlan Kellaway. It was inspired by SPGooglePlacesAutocomplete.

Thanks to all contributors 🎉

License & Terms

HNKGooglePlacesAutocomplete uses the Google Places API and is bound under Google's Places API Policies.

HNKGooglePlacesAutocomplete is available under the MIT license. See the LICENSE file for more info.

Bitdeli Badge

hnkgoogleplacesautocomplete's People

Contributors

amitaib avatar ben-g avatar bitdeli-chef avatar flippinjoe avatar hkellaway avatar readmecritic avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hnkgoogleplacesautocomplete's Issues

Could not map selected Place

To reproduce - search for Hollister and select Hollister Store, 3rd Street, San Francisco, CA - error shows up saying Could not map selected Place - kCLErrorDomain error 8

Autocompletion table view is hidden under google maps.

Everything works with apple maps,but when I use google maps,table view with autocompletion is hidden under google maps itself. When I change map's frame, table view becomes visible.Harlan can u help,what's wrong here???

Getting error of iP address

Hello friend,

When i am running this project i am getting this error, can you please help me.
Here with attached screenshot of error.

api

abc

Request implement geocode/json

Hello!
Your library use https://maps.googleapis.com/maps/api/place/details/json
But only for coordinates, it's very expensive.

Possible implement that action: https://maps.googleapis.com/maps/api/geocode/json ? Because it's cheaper 3-6 times.

Example request:
https://maps.googleapis.com/maps/api/geocode/json?key=ANY_KEY_WITHOUT_RESTICTION&place_id=ChIJgVFQ9rrskkYR9CuaUrt9wXQ&language=en
Example answer from this service:

   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "76a",
               "short_name" : "76a",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "Paekaare",
               "short_name" : "Paekaare",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Lasnamäe",
               "short_name" : "Lasnamäe",
               "types" : [ "political", "sublocality", "sublocality_level_1" ]
            },
            {
               "long_name" : "Tallinn",
               "short_name" : "Tallinn",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Harju maakond",
               "short_name" : "Harju maakond",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "Estonia",
               "short_name" : "EE",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "13611",
               "short_name" : "13611",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "Paekaare 76a, 13611 Tallinn, Estonia",
         "geometry" : {
            "location" : {
               "lat" : 59.434249,
               "lng" : 24.8286374
            },
            "location_type" : "ROOFTOP",
            "viewport" : {
               "northeast" : {
                  "lat" : 59.4355979802915,
                  "lng" : 24.8299863802915
               },
               "southwest" : {
                  "lat" : 59.4329000197085,
                  "lng" : 24.82728841970849
               }
            }
         },
         "place_id" : "ChIJgVFQ9rrskkYR9CuaUrt9wXQ",
         "types" : [ "street_address" ]
      }
   ],
   "status" : "OK"
}```

Could not fetch Places

  • I have created gooogle api key for ios and enable google places api service-> run project i get error :
    Could not fetch Places. Request denied. They key parameter may be invalid. Does goole places api for ios is current not run

Unable to use when API key is restricted

When we restrict the key we always get error This IP, site or Mobile application is not authorized to use this API key. Request received from IP address (Some IP Address), with empty referer.

ld: library not found for -lAFNetworking

I only get this error when I try and archive my project using your library. Any ideas please? :(

ld: library not found for -lAFNetworking
clang: error: linker command failed with exit code 1 (use -v to see invocation)

How to use specific key for iOS only with the library ?

SInce google has changed places api's. I've created a new key specific to iOS Apps and added bundle identifier of my app on google console. Enabled places,maps etc services. But I'm getting error when using the key. If I use no restrictions it works.

ERROR: Error Domain=com.hnkgoogleplacesautocomplete.query.fetch.error Code=4 "This IP, site or mobile application is not authorized to use this API key. Request received from IP address 49.206.191.33, with empty referer" UserInfo={NSLocalizedDescription=This IP, site or mobile application is not authorized to use this API key. Request received from IP address 49.206.191.33, with empty referer, NSLocalizedFailureReason=This IP, site or mobile application is not authorized to use this API key. Request received from IP address 49.206.191.33, with empty referer}

Getting errors with 1.2.0

I just updated to 1.2 and noticed strange issues with the library and returned results. Downgrading to 1.1.1 seems to fix them
It's Saturday midnight here and I am right before release, so I won't be able to investigate further until next week, but one of the error messages is "Invalid request. The input parameter may be missing."

It's not completely failing, as I am getting some results back, but lack some of the data (like ZIP for example). Again, after downgrade to 1.1.1 everything is OK again.

Support for Afnetworking 3.0

After updated to afnetworking 3.0 the autocomplete stop working, actually the project stop build. Is there any solution for that issue?

Failed to reverse geocode indonesia

Hi,

It fails to reverse geocode Indonesia.
Try searching "kota" and the autocomplete will show depok city indonesia. When we tap on indonesia row it fails to reverse geocode

Update Mantle to 2.0

I'd love to use this within a project I'm working on. I cannot currently integrate this through cocoa pods because the project has multiple pods that use mantle 2.0, and this pod requires 1.5

place id location issue.

Hi.
Thanks for making a nice wrapper library.

I'm using HNKGooglePlacesAutocomplete in my project and I found some issue about place id location.

hnk_placemarkFromGooglePlace: apiKey: completion method use
formatted_address tag for CLGeocoder translation.
But formatted_address have a wrong information sometimes like these examples :

  1. test1
    https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJN1t_tDeuEmsRUsoyG83frY4&key=APIKEY

result : "5, 48 Pirrama Rd, Pyrmont NSW 2009 오스트레일리아"

  1. test2
    https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJq-w0pF-McTUR18S2dS9zdzc&key=APIKEY

result : "대한민국"

So, I get a wrong location with 36.458351, 127.855841 for test2 place id even though its real location is 35.165343, 126.909200.

To solve this issue, I just add a few line of code in CLPlacemark+HNKAdditions

+ (void)hnk_placemarkFromGooglePlace:(HNKGooglePlacesAutocompletePlace *)place
                              apiKey:(NSString *)apiKey
                          completion:(void (^)(CLPlacemark *, NSString *, CLLocation * , NSError *))completion
{
    [self addressForPlace:place
                   apiKey:apiKey
               completion:^(NSString *addressString, CLLocation *placeLocation, NSError *error) {
                         …...
                       [self completeForPlace:place withAddress:addressString andLocation:placeLocation completion:completion];
                   }
               }];
}
+ (void)addressForPlace:(HNKGooglePlacesAutocompletePlace *)place
                 apiKey:(NSString *)apiKey
             completion:(void (^)(NSString *addressString, CLLocation *placeLocation, NSError *error))completion
{
       ….
        [HNKGooglePlacesServer GET:kHNKGooglePlacesServerRequestPathDetails
                        parameters:@{
                                     @"placeid" : place.placeId,
                                     @"key" : apiKey
                                     }
                        completion:^(NSDictionary *JSON, NSError *error) {

                            if (error) {
                                completion(nil, nil, error);
                            } else {

                                NSString *address = JSON[@"result"][@"formatted_address"];

                                // get coordinate info for place id to protect wrong address information.
                                NSNumber *latitude = JSON[@"result"][@"geometry"][@"location"][@"lat"];
                                NSNumber *longitude = JSON[@"result"][@"geometry"][@"location"][@"lng"];

                                CLLocation *location = [[CLLocation alloc] initWithLatitude:[latitude doubleValue] longitude:[longitude doubleValue]];

                                completion(address, location, nil);
                            }
                        }];
    }
}

I solved my problem with this code but it still remain some problem that CLPlacemark coordinate and CLLocation coordinate is not match.
I think it makes some confusion.

So, Would you have a better idea to solve this issue?

CLPlacemark missing important data

Once I have a HNKGooglePlacesAutocompletePlace object, I'm calling hnk_placemarkFromGooglePlace to get the CLPlacemark object.

I was logging the CLPlacemark and could see the data I wanted in the console, but couldn't figure out how to access it. After doing some investigating, it looks like the majority of this data must be part of a private class object or something, any chance I can get some input on this? I realize it's probably something I can't get access to, but I'd still like to know what's actually happening to cause this.

Either way, I need more of the data that is provided in Google's raw JSON response if I can't get access to the data via the CLPlacemark. Is there any alternative you can think of? Any modification I could make to the current codebase fairly easily to get the rest of the data that seems to be hidden away for some reason?

As a last resort I could fork and make sure the raw JSON is passed all the way to the final completion block so I can access what I need and go from there.

Thanks for the input and advice.

Location bias

First off, just wanted to say thanks for putting this library together. Love the fact that it isn't tied to a special controller subclass.

I have a quick question about the location bias settings. The entire reason why I'm using this library is because it wraps the web API instead of the Google Maps / Places iOS SDK which lacks location bias features I need.

Anyways, I was prepared to start looking into how to tweak the location bias settings for this library, but now that I have it setup at a basic level, I realized that it's already doing what I need. As I search for places, it's showing me the results in order of closest to farthest and they're all relevant to my current location.

I haven't provided any location or coordinates data to HNKGooglePlacesAutocomplete or to any Google Maps / Places SDK classes. How is this working?

I can see that there are some default config settings in HNKGooglePlacesAutocompleteQueryConfig but I don't see how those would be giving me the results I'm getting.

Definitely not complaining, as I'm getting the results I need with location bias without any customization, just curious how it's actually working so I can continue to tweak/customize if I need to do more.

Thanks.

Wrong Latitude

Hi,
I am using this hnk_placemarkFromGooglePlace method for getting Latitude and Longitude from CLPlacemark. i am using this to select two location on the map and mapping the distance. Using this i am getting wrong Latitude for one of the location. I tried searching location on Google map on the web and getting wrong address on map.

Could not map selected Place

To reproduce - search for Sjei and select Sjeidinjunis, Utsjoki, Finland - error shows up saying Could not map selected Place - kCLErrorDomain error 8

Error in code

Hi Dear,

I am using this code for google place autocomplete, i have create google API Key and added it to project as static NSString *const kHNKDemoGooglePlacesAutocompleteApiKey = @"AIzaSyCFdaA2ooQWv2jKD9JRlawX6VKtaAeV3G8"; but it give error "This IP, site or mobile application is not authorized to use this API key. Request received from IP address 41.212.226.7 with empty referer". please help me.

Thanks in advanced.

Calculate distance form current location

Hello,
Thanks for making such a nice library. I want to ask a question that Can I calculate distance from my current location to the places that I've searched by using this library? Also, how can I get the selected search place's latitude and longitude?

Thanks,
Nirmit D.

Swift 3.0

How to use it in Swift or is this available in swifT?

HNKGooglePlacesAutocompletePlace Question

Hi,

When I have successfully fetched the places, how do I take the street number, locality and postal code from one of the returned HNKGooglePlacesAutocompletePlace objects?

I can see this object with types, substrings and terms arrays but no simple way of, eg, getting the postal code.

Thanks!

Set QueryConfig location and search radius default to API defaults

"If you do not supply the location and radius, the API will attempt to detect the user's location from their IP address, and will bias the results to that location. If you would prefer to have no location bias, set the location to '0,0' and radius to '20000000' (20 thousand kilometers), to encompass the entire world."

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.