I’d like to use URL parameters (specifically ?find= and ?show=) in a map I’m building using the JS API.
Seems like this should be fairly standard (maybe even worthy of a pre-made widget?) but I’m not finding a current solution (lots of old posts using previous versions of js or the WAB, etc.).
For ?find= I have a points layer that I would like to query / pan / zoom to (e.g., ?find=CB, which would zoom the map to the Chemistry Building (CB).
For ?show= I have about 10 layers that I would like to have the option of turning on (e.g., ?show=parking, which would turn On the parking layer).
Anyone have any code samples of how to do this? Or able to direct me to a tutorial that would help?
(Or suggestions as to a better way to give users the ability to link directly to their desired map state?)
thanks in advance,
~stefan
Solved! Go to Solution.
This functionality is already built into the browser.
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
const params = new URLSearchParams(window.location.search)
const myParams = {}
for (let key of params.keys()) {
myParams[key] = params.get(key)
}
We also have a util in the API that can help too.
https://developers.arcgis.com/javascript/latest/api-reference/esri-core-urlUtils.html#urlToObject
const { query } = urlUtils.urlToObject(window.location.href)
Now you can use your URL parameters to write a query or navigate to a coordinate, create definition expressions, whatever floats your boat.
This functionality is already built into the browser.
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
const params = new URLSearchParams(window.location.search)
const myParams = {}
for (let key of params.keys()) {
myParams[key] = params.get(key)
}
We also have a util in the API that can help too.
https://developers.arcgis.com/javascript/latest/api-reference/esri-core-urlUtils.html#urlToObject
const { query } = urlUtils.urlToObject(window.location.href)
Now you can use your URL parameters to write a query or navigate to a coordinate, create definition expressions, whatever floats your boat.
Thanks ReneRubalcava !
I was trying to figure out the urlUtils last night..., but it's working now.
Any advice or recommendation for using urlUtils vs. URLSearchParams in the browser?
~stefan
Since you're already using the API, urlUtils would probably be the simplest route.
Thanks.
@ReneRubalcava - Follow-up question: The urlUtils is working great when there is a parameter added to the URL, but the map won't load if there is not a URL parameter. Is there a check/test that can deal with the default URL (without a parameter)?
FOLLOW-UP SOLUTION (also from @ReneRubalcava ) to the follow-up question on how to handle cases where there is not a URL parameter: use query? instead of just query in the const statement:
const { query } = urlUtils.urlToObject(window.location.href) ;
const myUrlParm = query?.find;
Thanks Rene