mapbox-gl-jsmaplibre-gl

Mapbox/MapLibre how to use custom hash to show parameters in URL?


Mapbox and MapLibre both provide an option for the map object to show parameters in the URL. Setting this "hash" option to true shows the center (lat, lon), zoom, bearing and pitch information in the URL. It can be set like this:

var map = new mapboxgl.Map({
   // ...
   hash: true
});

In the documentation is stated, that an additional string can be provided to indicate a hash that is parameter based. In my application I have a menu to toggle layers and I would like to put that information within the URL. I cannot find a way how to set this custom hash string. Whenever a toggled layers event is registered, I could easily adapt this string which should then be updated in the URL as well.

I could not find any examples in the documentation and also not in the web.


Solution

  • Passing a string to the hash option doesn't have the purpose to pass additional query strings. It just gives a key to the Mapbox hash so it doesn't overwrite your own additional query strings. You still have to add your own query strings to your url manually.

    If you use

    var map = new mapboxgl.Map({
       // ...
       hash: true
    });
    

    your url will be: http://path/to/my/page.html#2.59/39.26/53.07/-24.1/60

    Now, if you pass a string to hash

    var map = new mapboxgl.Map({
       // ...
       hash: "mapHash"
    });
    

    it'll come out as: http://path/to/my/page.html#mapHash=2.59/39.26/53.07/-24.1/60

    This way, you can add other string parameters and mapbox won't overwrite them. Working example:

    https://codesandbox.io/s/relaxed-glitter-teyb7m?file=/src/App.js:462-477

    When you drag the map, it updates the coordinates. When you click it, it updates the timestamp.

    In the example, try changing the hash to true to see what happens with the url.