0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

学習79日目

Posted at

内容

reactを用いたgoogle map機能の実装(マップの表示)

前提

• ruby on railsで個人開発中
• react導入済
• googlemaps api導入済

内容

ライブラリのインストール

ターミナル

npm install @googlemaps/react-wrapper

viewでの呼び出し

app/views/hoges/_form.html.erb

<%= form_with model: @hoge do |form| %>
  <%= react_component("hoge") %>
<% end %>

jsxの記述

app/javascript/components/hoge.jsx

import React from 'react';
import { Wrapper, useGoogleMap } from '@googlemaps/react-wrapper';

const apiKey = 'YOUR_API_KEY'; 

function MyMap() {
  const { ref, map } = useGoogleMap();

  if (map) {
    new google.maps.Marker({
      position: { lat: 35.681236, lng: 139.767125 },
      map,
      title: '東京駅',
    });
  }

  return <div ref={ref} style={{ width: '500px', height: '400px' }} />;
}

function hoge() {
  return (
    <Wrapper apiKey={apiKey} libraries={['places']}>
      <MyMap />
    </Wrapper>
  );
}

export default hoge;

※「YOUR_API_KEY」の部分は自分のapiキーを記述する(直接記述するのは危険なので、ENVから呼び出すのが良い)

コメント

今後はマーカーの表示やドラッグ時の処理を実装する。

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?