LoginSignup
0
5

More than 3 years have passed since last update.

railsでGoogleMapAPIの導入

Last updated at Posted at 2020-05-27

このページのコードでできること

・自分のrailsプロジェクトにGoogleMapを埋め込み、表示させる。
・ページを開いたら地図と、初期値のマーカーを表示させる。
・inputボックスと検索ボタンを用意。
・inputボックスに検索したい場所を入力し、検索ボタンを押すことでその場所の地図を表示。

Maps JavaScript API & Geocoding APIの取得

これら記事にお世話になりました。(参考文献より)

コードを書く前に
Google Maps API を使ってみた
Google MAP 名称から場所を検索・特定する
オリジナルアプリ作成 〜RailsでGoogleMap利用検証〜

コード

postsに記述するとします。
@post.locationは一例です。ご自身のアプリケーションにふさわしい初期値を入れてください。

posts/index.html.erb
<div id='target'></div>

<div class='map-btn'>
<input id="address" type="textbox" value="<%= @post.location %>">
<input type="button" value="検索" onclick="codeAddress()">
<div>

<script src="https://maps.googleapis.com/maps/api/js?key=自分のAPIキー&callback=initMap" async defer></script>

style.scss
#target {
  height: 300px;
  width: 300px;
}

Javascriptの記述

post.js

let map
let geocoder
let centerp = {lat: 33.60639, lng: 130.41806}

function initMap(){
  geocoder = new google.maps.Geocoder()

  map = new google.maps.Map(document.getElementById('target'), {
    center: centerp,
    zoom: 12,
  });

  marker = new google.maps.Marker({
    position: centerp,
    map: map
  });
}

function codeAddress(){
  let inputAddress = document.getElementById('address').value;

  geocoder.geocode( { 'address': inputAddress}, function(results, status) {
    if (status == 'OK') {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
      });
    } else {
      alert('該当する結果がありませんでした:' + status);
    }
  });   
}

参考文献

大変お世話になりました。感謝。

コードを書く前に
[https://qiita.com/nagaseToya/items/e49977efb686ed05eadb]

Google Maps API を使ってみた
[https://qiita.com/Haruka-Ogawa/items/997401a2edcd20e61037]

Google MAP 名称から場所を検索・特定する
[https://qiita.com/yoshi_yast/items/521c1f36306a180f45dd]

オリジナルアプリ作成 〜RailsでGoogleMap利用検証〜
[https://note.com/daddy0055/n/nddbe8da38bbc]

0
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
5