Skip to content

Commit

Permalink
Use edge geolocation to center the map
Browse files Browse the repository at this point in the history
  • Loading branch information
Rupert Redington committed Sep 25, 2024
1 parent b2d6c58 commit 40840ca
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
17 changes: 17 additions & 0 deletions src/middleware.page.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { NextRequest, NextResponse } from 'next/server';

// run only on homepage
export const config = {
matcher: '/',
};

export async function middleware(req: NextRequest) {
const { nextUrl: url, geo } = req;
console.log(geo);
if (!url.searchParams.has('lat') && geo && geo.latitude && geo.longitude) {
url.searchParams.append('lat', geo.latitude);
url.searchParams.append('lng', geo.longitude);
}

return NextResponse.redirect(url);
}
18 changes: 16 additions & 2 deletions src/pages/_app.page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,28 @@ const App = (props) => {
const sharedStatePaths = ['/', '/loos/[id]'];
const key =
sharedStatePaths.indexOf(router.pathname) > -1 ? 'shared' : router.asPath;

const center = useMemo(
() =>
router.query.lat && router.query.lng
? {
lat: parseFloat(router.query.lat as string),
lng: parseFloat(router.query.lng as string),
}
: null,
[router.query],
);

console.log(center);

const renderedMap = useMemo(
() =>
key === 'shared' ? (
<Suspense>
<LooMap minZoom={5} />
<LooMap minZoom={5} {...(center ? { center } : {})} />
</Suspense>
) : undefined,
[key]
[key, center],
);

return (
Expand Down

0 comments on commit 40840ca

Please sign in to comment.