LoginSignup
6
2

SvelteKitでURLクエリパラメーターの操作をする

Posted at

これは MIERUNE AdventCalendar 2023 23日目の記事です。
昨日は @Guarneri001 さんによる Rustで点群データからGeoTiffを作成する でした。

クエリパラメーターをセットしたい場合

import { page } from '$app/stores';

const urlSearchParams = $page.url.searchParams;
urlSearchParams.set('lat', map.getCenter().lat.toString());
urlSearchParams.set('lng', map.getCenter().lng.toString());
urlSearchParams.set('zoom', map.getZoom().toString());

history.replaceState(history.state, '', $page.url);
  • ポイントは最後の行のhistory.stateを書き換える点
  • コレがないと書き換わってくれない
  • なんか他に良い方法があるかもしれない

クエリパラメーターを取得したい場合

import { page } from '$app/stores';

const urlSearchParams = $page.url.searchParams;
const lat = Number(urlSearchParams.get('lat')) ?? 35.681;
const lng = Number(urlSearchParams.get('lng')) ?? 137.767;
const zoom = Number(urlSearchParams.get('zoom')) ?? 7;
  • $page.data.qでも取得できるっぽいですが、値が入っていない時の事を考えるとurlSearchParams.getの方が扱いやすいと思います

スクリーンショット 2023-10-25 7.53.12.png

明日は@satoshi7190さんの記事です!お楽しみにー

6
2
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
6
2