LoginSignup
1
4

More than 3 years have passed since last update.

【React】GoogleMapで地図をドラッグして移動した後にMarkerを更新する

Posted at

やりたいこと

GoogleMapと地図のMarker一覧を取得するAPIを組み合わせて、Reactアプリケーションを作ることを想定しています。
その際に、地図の中心地がドラッグで移動された際に、Marker一覧も取得し直して、地図にMarkerの再配置をしたいです。
イメージとしてはドラッグ前が以下のような感じとした場合、
スクリーンショット 2020-04-25 2.51.21.png

ドラッグ後はこのような感じでMarkerも再取得される感じです。
スクリーンショット 2020-04-25 2.52.53.png

前提

サンプルソース

※ reducerやstoreの実装内容は割愛

GoogleMapComponent.js
import React, { useContext } from "react";
import { GoogleApiWrapper, Marker, Map } from "google-maps-react";
import { MapStore } from "../../store/MapStore";

export const GoogleMapComponent = ({ google }) => {
  const { state, dispatch } = useContext(MapStore);
  const location = state.currentLocation;
  var markerList = [];
  // ステートの情報でMarkerを作成
  state.markerList.map((m, i) => {
    return markerList.push(
      <Marker
        key={i}
        title={m.name}
        position={{ lat: m.latitude, lng: m.longitude }}
      />
    );
  });
  // 地図ドラッグ時に走る関数
  const centerMoved = (_, map) => {
    // 変更後の中心を取得
    const center = map.getCenter();
    // APIでのMarker取得処理
    axios
      .get("http://localhost/test", {
        latitude: center.lat(),
        longitude: center.lng(),
      })
      .then((results) => {
        if (results.status === 200) {
          dispatch({
            type: "CHANGE_LOCATION",
            currentLocation: {
              latitude: latitude,
              longitude: longitude,
            },
            markerList: results.data,
          });
        } else {
          // エラー時の処理
        }
      })
      .catch(() => {
        // エラー時の処理
      });
  };
  return (
    <Map
      google={google}
      zoom={15}
      center={{ lat: location.latitude, lng: location.longitude }}
      initialCenter={{ lat: location.latitude, lng: location.longitude }}
      onDragend={centerMoved}
    >
      {markerList}
    </Map>
  );
};

export default GoogleApiWrapper({
  apiKey: process.env.REACT_APP_GOOGLE_MAP_API_KEY,
})(GoogleMapComponent);

1
4
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
1
4