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?

学習80日目

Last updated at Posted at 2025-08-22

テーマ

reactでgooglemapを実装する(マーカーの表示)

前提

• ruby on railsで個人開発
• react導入済
• google maps api 導入済
• 該当部分以外省略

内容

viewの記述

app/views/hoges/_form.html.erb

<%= form_with model: @hoge do |form| %>
  <div id='map_area'></div>
<% end %>
<%= javascript_pack_tag 'application' %>

jsxの記述

app/javascript/components/DisplayMap.jsx

import React, { useRef, useEffect, useState } from "react";
import { Wrapper } from "@googlemaps/react-wrapper";

const apiKey = 'your_api_key'

function MyMap() {
  const ref = useRef(null);
  const [map, setMap] = useState();

  useEffect(() => {
    if (ref.current && !map) {
      setMap(
        new window.google.maps.Map(ref.current, {
          center: { lat: 35.681236, lng: 139.767125 }, // 東京駅
          zoom: 15,
        })
      );
    }
  }, [ref, map]);

  useEffect(() => {
    if (map) {
      new window.google.maps.Marker({
        position: { lat: 35.681236, lng: 139.767125 },
        map,
        title: "東京駅",
      });
    }
  }, [map]);

  return <div ref={ref} style={{ width: "100%", height: "100%" }} />;
}

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

export default DisplayMap;

app/javascript/packs/application.js

import React from "react"
import { createRoot } from "react-dom/client";
import Hoge from "components/DisplayMap"
  const root = createRoot(document.getElementById("map_area"))
  if (root) {
    root.render(<DisplayMap />)
  }

コメント

マーカーを移動させた場合の処理や、フォームのhidden_fieldにlatとlngをセットさせるような実装も試したい。

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?