I know that we need to use a unique API key to access the Google Geocoding API.I am using the Rails Geocoder Gem in my application and found out that it uses the Google Geocoding API.I was unable to find any configuration files that define the API keys to access the Google API.How does the Geocoder gem access the Google API's.
Geocoder.configure(
:lookup => :google_premier,
:api_key => [ 'GOOGLE_CRYPTO_KEY', 'GOOGLE_CLIENT_ID', 'GOOGLE_CHANNEL' ],
:timeout => 5,
:units => :km,
)
https://github.com/alexreisner/geocoder
Here is one more link : http://hankstoever.com/posts/11-Pro-Tips-for-Using-Geocoder-with-Rails
under
Some common configuration options are:
You should look into this answer : Does Geocoder gem work with google API key?
It says:
Geocoder supports Google api keys for Google Premier accounts only.
But you can use the Client-Side framework to do that, instead of putting it on the server
https://developers.google.com/maps/articles/geocodestrat
I wrote something like that a few days back in ruby, if it helps :
require 'net/http'
require "resolv-replace.rb"
require 'json'
url = URI("https://maps.googleapis.com/maps/api/geocode/json")
puts "enter country code"
c_code = gets
puts "enter zip code "
zip = gets
url.query= URI.encode_www_form({ address: "#{c_code.chomp}+#{zip.chomp}" })
res = Net::HTTP::get_response(url)
json_data = res.body if res.is_a?(Net::HTTPSuccess)
data = JSON.parse(json_data)
p data
Related
I want to get access to a user's contact list with the google contacts API.
I've managed to get the token and refresh token and I'm now trying to use then on my rails server.
The google-api-client gem seems to be the way to go but I could not find which discovered_api to use. Greg Baugues provides a great tuto to get the gmail API working. The general request seems to look like
client = Google::APIClient.new
client.authorization.access_token = user_token
service = client.discovered_api('gmail')
result = client.execute(
:api_method => service.users.labels.list,
:parameters => {'userId' => 'me'},
:headers => {'Content-Type' => 'application/json'})
pp JSON.parse(result.body)
But I could not find how to query it for contacts. Running
client.discovered_apis.each do |gapi|
puts "#{gapi.title} \t #{gapi.id} \t #{gapi.preferred} \n"
end
(from here) shows now API related to contacts and I'm wondering if this is implemented in the alpha version of the gem...
As mentioned by #abraham, the Google contact API is not supported by the discovery API. Here is how I did it in ruby from the access token using the gems google_contacts_api and oauth2 (thanks to Rael Gugelmin Cunha for pointing them to me):
client = OAuth2::Client.new(client_id, client_secret, site: url)
token = OAuth2::AccessToken.new(client, access_token)
google_contacts_user = GoogleContactsApi::User.new(token)
contacts = google_contacts_user.contacts
There might be some more elegant way to do it but this works :)
The Google Contacts API is on Google's older GData API standard and is not supported by the discovery API. There is a pretty extensive guide for plain Ruby and a helper gem. Retrieving all contacts doesn't provide a Ruby sample but the Python sample should translate pretty easily.
def PrintAllContacts(gd_client):
feed = gd_client.GetContacts()
for i, entry in enumerate(feed.entry):
print '\n%s %s' % (i+1, entry.name.full_name.text)
if entry.content:
print ' %s' % (entry.content.text)
# Display the primary email address for the contact.
for email in entry.email:
if email.primary and email.primary == 'true':
print ' %s' % (email.address)
I am using google-api-client gem to post message to google plus when a user logs in my application with his google plus credentials.
Below is my code.
require 'google/api_client'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/installed_app'
keypath = Rails.root.join('config','poo-02a507f45ab4.p12').to_s
key = Google::APIClient::KeyUtils.load_from_pkcs12(keypath, 'notasecret')
client = Google::APIClient.new(
:application_name => 'my app',
:application_version => '1.0.0'
)
urlshortener = client.discovered_api('urlshortener', 'v1')
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => ['https://www.googleapis.com/auth/prediction','https://www.googleapis.com/auth/plus.stream.write','https://www.googleapis.com/auth/plus.login','https://www.googleapis.com/auth/urlshortener','https://www.googleapis.com/auth/plus.circles.write'],
:issuer => 'id#developer.gserviceaccount.com',
:signing_key => key)
client.authorization.fetch_access_token!
batch = Google::APIClient::BatchRequest.new do |result|
puts result.data
end
batch.add(:api_method => urlshortener.url.insert,:body_object => { 'longUrl' => 'https://www.facebook.co.in' })
client.execute(batch)
While trying this code its giving below error.
{\n \"domain\": \"usageLimits\",\n \"reason\": \"accessNotConfigured\",\n \"message\": \"Access Not Configured. The API is not enabled for your project, or there is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your configuration.\",\n
I have enabled google + API and contacts API in developers console.
Please help me to solve this problem.
The problem you are having is that you are using a service account.
The Google OAuth 2.0 system supports server-to-server interactions such as those between a web application and a Google service. This scenario is called a service account, which is an account that belongs to your application instead of to an individual end user. Your application calls Google APIs on behalf of the service account, so users aren't directly involved.
If you want to post on behalf of a user you will need to be using Oauth2, then you will be able to authenticate the user.
Update:
So that you are aware it is not possible to post to a users Google+ time line. the best you can do is post something called moments which isn't really the same thing. An issue request was made for this in 2011 I think they have yet to add this feature.
I'm trying to access the Google Webmaster Tools API with the ruby client:
webmaster_tools_api = client.discovered_api('webmasters', 'v3')
result = client.execute(
:api_method => webmaster_tools_api.sites.example.com.urlCrawlErrorsCounts.query,
)
The API method I am trying to access uses the siteurl in the method name. This won't work because the syntax conflicts.
Is there a way to access API method names that include URLs?
results = client.execute(
api_method: webmaster_tools_api.urlcrawlerrorscounts.query,
parameters: { 'siteUrl' => 'example.com' }
)
(Google's API docs are terrible so it's not surprising you couldn't find this.)
I am using ruby geocoder gem for my project and as the project is growing I am starting to look into connecting to the Google API key. After adding this to the project:
Geocoder.configure do |config|
# geocoding service (see below for supported options):
config.lookup = :google
# to use an API key:
config.api_key = 'my_key'
# geocoding service request timeout, in seconds (default 3):
config.timeout = 5
end
I get Google Geocoding API error: request denied. when I start the application. From reading around, it seems like others switch over to yahoo if they choose to continue using the gem. Can I configure the gem to work with google api key? Mainly, I would like to keep an eye out for the amount of daily queries to avoid going over the limit.
Geocoder supports Google api keys for Google Premier accounts only.
Its found here in the readme on github: https://github.com/alexreisner/geocoder#google-google-google_premier
If you have a Google Premier api key you just need to put this in an intializer:
# config/initializers/geocoder.rb
Geocoder.configure(:lookup => :google_premier, :api_key => "...")
And your Geocoder will use your premier key.
I had this issue today and managed to solve it by setting use_https e.g.
Geocoder.configure(
timeout: 15,
api_key: "YOUR_KEY",
use_https: true
)
create a file: config/initializers/geocoder.rb and setup like this:
Geocoder.configure(
lookup: :google_premier,
api_key: ['api_key', 'client_id', 'client_id_type'],
)
Geocoder works fine with the free tier of their Map API. However, to make it work I had to register a key using this page specifically.
https://console.developers.google.com/flows/enableapi?apiid=geocoding_backend&keyType=SERVER_SIDE
And set up the configuration
# config/initializers/geocoder.rb
Geocoder.configure(
api_key: 'KEY_HERE',
use_https: true
)
By default Geocoder uses Google's geocoding API to fetch coordinates and street addresses. So, I think that a Google API key should work on the initializer.
I hope this work for you.
Geocoder.configure(
# geocoding service
lookup: :google,
# geocoding service request timeout (in seconds)
timeout: 3,
# default units
units: :km
)
This work for me. You can call API from rails console with geocoder doc at http://www.rubygeocoder.com/ than call it from view /my_map/show.html.erb replace address or city etc with <%= #place.address %>
If anyone is still looking at this, for some reason the Google API changed and Geocoder no longer works with the standard config file. However, you can simply not use the Geocoder gem for geocoding and reverse geocoding (don't use Geocoder.search) and use any http request gem to directly call the google api, as of this moment using RestClient the api call would be
response = RestClient.get 'https://maps.googleapis.com/maps/api/geocode/json?address=' + sanitized_query + '&key=' + your_key
where sanitized query can be either an address like Cupertino, CA or a lat=x, lng=y string for geocoding or reverse geocoding. It is not necessary to get a Google premier account.
I was wondering if anyone could provide an example of how to pull products from the Google Shopping API using a GAN publisher ID and ruby (google-api-ruby-client). I'm gathering you need to authenticate using oauth. The documentation is very sparse so any help would be much appreciated.
Basic usage of the shopping API with the client is easy.
require 'google/api_client'
client = Google::APIClient.new
client.authorization = nil
shopping = client.discovered_api("shopping", "v1")
result = client.execute(:api_method => shopping.products.list,
:parameters => { "source" => "public" })
To query by GAN publisher ID, you need to be authenticated as you're aware. You can use OAuth 2 for that. You can see a sample of that for the ruby client at http://code.google.com/p/google-api-ruby-client/wiki/OAuth2. The scope to use for shopping is:
https://www.googleapis.com/auth/shoppingapi
You can use the APIs explorer to try this out pretty quickly:
http://code.google.com/apis/explorer/#_s=shopping&_v=v1&_m=products.list
With version 0.9.11 is even easier
require 'google/apis/content_v2'
def list_products
content_for_shopping = Google::Apis::ContentV2::ShoppingContentService.new
content_for_shopping.authorization = get_authorization(%w(https://www.googleapis.com/auth/content))
content_for_shopping.authorization.fetch_access_token!
content_for_shopping.list_products(ENV['GOOGLE_MERCHANT_CENTER_ID'])
end
def get_authorization(scopes)
cert_path = Gem.loaded_specs['google-api-client'].full_gem_path + '/lib/cacerts.pem'
ENV['SSL_CERT_FILE'] = cert_path
authorization = Google::Auth.get_application_default(scopes)
# Clone and set the subject
auth_client = authorization.dup
return auth_client
end