Rails에서 게시 한 내용을 GoogleMap에 마커로 표시하는 방법
15579 단어 MySQLRailsMacGoogleMapsAPI루비
소개
전세계의 절경을 투고할 수 있는 앱을 만들 수 있습니다.
지도 표시 방법은 GoogleMapsAPI를 사용했습니다.
게시한 내용에서 자동으로 경도와 위도를 가져와 GoogleMapsAPI 지도에 표시합니다.
완성형은 이런 느낌

환경
목차
GoogleMaps KEY 획득
(구글 계정에 로그인 한 후 시작하십시오)
먼저 Google Map Platform에서 KEY를 얻습니다.

사용해보기를 선택.

모두 선택하고 계속.
프로젝트 이름은 무엇이든 좋지만 이번에는 MyProject 선택
결제 방법을 입력합니다.
top 페이지로 이동하므로 아래쪽의 Maps Platfom을 선택

Maps JavaScript API를 선택하고 사용을 누릅니다.


화면에 있는 API 및 서비스 자격 증명

자격 증명 만들기를 선택하여 API를 만듭니다.
화면에 나오는 것이 API 키이므로 저장하십시오. (필요한 경우 키를 제한하십시오)
간단한 앱을 만들고 googlemap을 앱에 표시
앱 이름은 여기에서 gmap입니다.
여기 부분은 자신의 앱 이름이어야합니다.
먼저 앱의 병아리와 데이터베이스 디자인
터미널에서
rails _5.2.3_ new gmap -d mysql
cd gmap
rails g controller maps
rails db:create
rails db:migrate
erb가 되어 있으므로 haml로 변환합니다.
여기는 선택 사항이며 괜찮습니다.
※ erb를 haml로 쉽게 바꾸는 사이트입니다.
Gemfile
gem "haml-rails", ">= 1.0", '<= 2.0.1'
bundel install
rails haml:erb2haml
지도 표시
rails5.2 이상이므로 이번에는 credentials를 사용합니다.
routes.rb
Rails.application.routes.draw do
root to: "maps#index"
end
views/maps/index.html.haml
%div{:style => "width: 100%;"}
#map{:style => "width: 100%; height: 100vh;"}
:javascript
function initMap(){
let map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
%script{:src => "https://maps.googleapis.com/maps/api/js?key=#{Rails.application.credentials[:GOOGLE_MAP_KEY]}&callback=initMap"}
방금 전의 API 키를 credentials로 숨겨 둡니다.
터미널에서
EDITOR="vi" bin/rails credentials:edit
GOOGLE_MAP_KEY: MyAPIKey
MyAPIKey 부분은 이전에 얻은 key를 입력하십시오.
이것으로 일단 맵 표시가 생겼다고 생각합니다!

게시 기능 만들기 경도, 위도 취득
우선 게시 기능을 만들기 위해 posts view와 controller,model을 만듭니다.
rails g scaffold posts name:string description:string latitude:float longitude:float
rake db:migrate
표시를 gmaps4rails의 gem을 사용하여 표시하는 방법으로 변경합니다.
Gemfile
gem 'gmaps4rails'
underscore, gmaps/google을 applicaton.js에 추가합니다.
//= require underscore //追加
//= require gmaps/google //追加
//= require_tree .
app/assets/javascripts/underscore.js 만들기
여기 의 내용을 전부 copipe
views/maps/index.html.haml
%div{:style => "width: 100%;"}
#map{:style => "width: 100%; height: 100vh;"}
:javascript
handler = Gmaps.build('Google');
handler.buildMap({
provider: {mapTypeId: 'hybrid'},
internal: {id: 'map'}
},
function(){
markers = handler.addMarkers(#{raw @hash.to_json})
handler.bounds.extendWith(markers);
handler.fitMapToBounds();
handler.getMap().setCenter(new google.maps.LatLng(35.681298, 139.7640582));
handler.getMap().setZoom(4);
});
provider: {mapTypeId: 'hybrid'} 부분에서 맵 유형을 변경할 수 있습니다.
아무것도 없으면 첫 번째 유형입니다.
다른 유형은 아래를 참조하십시오.
ROADMAP 도로나 건물 등이 표시되는 지도입니다
SATELLITE 위성 사진을 사용한지도입니다.
HYBRID ROADMAP과 SATELLITE의 복합지도
TERRAIN 지형 정보를 사용한 지도입니다
application에 key를 옮겨 어디서나 사용할 수 있도록 합니다.
application.html.haml
!!!
%html
%head
%meta{:content => "text/html; charset=UTF-8", "http-equiv" => "Content-Type"}/
%title Gmap
= csrf_meta_tags
= csp_meta_tag
= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload'
= javascript_include_tag 'application', 'data-turbolinks-track': 'reload'
%script{:src => "//maps.google.com/maps/api/js?key=#{Rails.application.credentials[:GOOGLE_MAP_KEY]}"}
%script{:src => "//cdn.rawgit.com/mahnunchik/markerclustererplus/master/dist/markerclusterer.min.js"}
= yield
컨트롤러에 게시한 위치에 마커가 서 있습니다.
maps_controller.rb
class MapsController < ApplicationController
def index
@posts = Post.all
@hash = Gmaps4rails.build_markers(@post) do |post, marker|
marker.lat post.latitude
marker.lng post.longitude
marker.infowindow post.description
end
end
end
marker.infowindow post.description에 표시하고 싶은 열을 바꾸면 표시 내용을 바꿀 수 있습니다.
이번은 description으로 합니다.
이제 마커가 서 있습니다.
그리고는 신규 투고로 경도, 위도를 취득할 수 있도록 합니다
gem 'geocoder'
post.rb
class Post < ApplicationRecord
geocoded_by :name
after_validation :geocode
end
이름의 컬럼명으로 경도와 위도를 취득할 수 있게 되었기 때문에
그리고는 송신할 때 불필요한 컬럼을 지워 둡니다.
posts/_form.html.haml
.field
= f.label :name
= f.text_field :name
.field
= f.label :description
= f.text_field :description
.field
= f.label :latitude
= f.text_field :latitude
.field
= f.label :longitude
= f.text_field :longitude
.actions
= f.submit 'Save'
의 latitude 및 longitude 항목을 지웁니다.
이것으로 완성입니다!
마지막으로
잘못된 곳이 있으면 알려주세요 ...
Reference
이 문제에 관하여(Rails에서 게시 한 내용을 GoogleMap에 마커로 표시하는 방법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://qiita.com/rails14024548/items/49535c94459879d814b2
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
Reference
이 문제에 관하여(Rails에서 게시 한 내용을 GoogleMap에 마커로 표시하는 방법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/rails14024548/items/49535c94459879d814b2텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)