Skip to content

Commit

Permalink
Centered map when click on marker
Browse files Browse the repository at this point in the history
  • Loading branch information
jjstnlee committed Oct 26, 2024
1 parent 221d6ec commit 356189e
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 5 deletions.
8 changes: 7 additions & 1 deletion api/maps/AddMarkers.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useState } from 'react';
import { useMap } from '@vis.gl/react-google-maps';
import ProjectModal from '@/components/ProjectModal';
import { Project } from '../../types/schema';
import { MarkerInfoWindow } from './MarkerInfoWindow';
Expand All @@ -11,9 +12,14 @@ export default function AddMarker({
const [selectedProjectId, setSelectedProjectId] = useState<number | null>(
null,
); // track currently open modal
const map = useMap();

const handleMarkerClick = (projectId: number) => {
const handleMarkerClick = (
projectId: number,
position: { lat: number; lng: number },
) => {
setSelectedProjectId(prevId => (prevId === projectId ? null : projectId)); // close modal if same, open if different
map && map.panTo(position); // change center of map to selected marker
};

const closeModal = () => {
Expand Down
7 changes: 5 additions & 2 deletions api/maps/MarkerInfoWindow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@ export const MarkerInfoWindow = ({
projectId: number;
projectName: string;
projectDev: string;
onMarkerClick: (projectId: number) => void;
onMarkerClick: (
projectId: number,
position: { lat: number; lng: number },
) => void;
}) => {
const [markerRef, marker] = useAdvancedMarkerRef();
const [infoWindowShown, setInfoWindowShown] = useState(false);
Expand All @@ -37,7 +40,7 @@ export const MarkerInfoWindow = ({
position={position}
onMouseEnter={handleMarkerEnter}
onMouseLeave={handleClose}
onClick={() => onMarkerClick(projectId)}
onClick={() => onMarkerClick(projectId, position)}
/>

{infoWindowShown && (
Expand Down
4 changes: 2 additions & 2 deletions components/Map/map.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use client';

import { APIProvider, Map as GoogleMap } from '@vis.gl/react-google-maps';
import addMarkers from '../../api/maps/AddMarkers';
import AddMarkers from '../../api/maps/AddMarkers';
import { Project } from '../../types/schema';
import './styles.css';

Expand All @@ -28,7 +28,7 @@ export default function Map(props: { projects: Project[] | null }) {
disableDefaultUI={true}
mapId={mapId}
>
{addMarkers({ projects: props.projects })}
<AddMarkers projects={props.projects} />
</GoogleMap>
</APIProvider>
);
Expand Down

0 comments on commit 356189e

Please sign in to comment.