Q&A
DBに保存した 住所からgoogle map 表示させる機能の実装をしています。
経度緯度は住所からselfで所得するプログラムを組んでいます。
下記のgemを使用しています
gemfile
1gem 'geocoder' 2gem 'gmaps4rails'
rails g gmaps4rails:copy_js コマンドでgmaps_google.jsファイル所得済みです。
application.html.hamlにてgmaps_google.js使用できる記載入れてます。
ファイル名application.html.haml %head %meta{:content => "text/html; charset=UTF-8", "http-equiv" => "Content-Type"}/ %title FavoriteFoodShare = csrf_meta_tags = csp_meta_tag = stylesheet_link_tag 'application', media: 'all' = javascript_include_tag 'application' %script(src="//maps.google.com/maps/api/js?v=3.23") %script(src="//cdn.rawgit.com/mahnunchik/markerclustererplus/master/dist/markerclusterer.min.js") %script(src="//cdn.rawgit.com/printercu/google-maps-utility-library-v3-read-only/master/infobox/src/infobox_packed.js" type="text/javascript") %script(src="/javascripts/gmaps_google.js") %body = render "layouts/notifications" = yield
住所を入力してcreateアクションが動いた際に
undefined method `[]' for nil:NilClassのエラーが出ます
下記のコードが違うと指摘されます。
self.latitude = response["results"][0]["geometry"]["location"]["lat"]
self.longitude = response["results"][0]["geometry"]["location"]["lng"]
master_keyの中にgoogle_map_apiという変数にapi_key入れています。
すみませんがご教授お願いします
ファイル名post.rb class Post < ApplicationRecord mount_uploader :image, ImageUploader belongs_to :user geocoded_by :address after_validation :geocode private def geocode uri = URI.escape("https://maps.googleapis.com/maps/api/geocode/json?address="+self.address.gsub(" ", "")+"&key=google_map_api") res = HTTP.get(uri).to_s response = JSON.parse(res) self.latitude = response["results"][0]["geometry"]["location"]["lat"] self.longitude = response["results"][0]["geometry"]["location"]["lng"] end end
ファイル名 posts_controller.rb def create @post = Post.new(post_params) if @post.save redirect_to root_path, notice: "出品完了やで!!!" else render :new, alert: '出品できませんでした' end end private def post_params params.require(:post).permit(:image, :meals, :description, :text, :address, :latitude, :longitude).merge(user_id: current_user.id) end
回答1件
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
2020/01/31 04:59