[go: up one dir, main page]

DEV Community

Rene Rubalcava
Rene Rubalcava

Posted on

Custom bookmarks in your ArcGIS JS API apps

The recent release of the ArcGIS API for JavaScript introduced the Bookmarks widget to support Bookmarks you can create in WebMaps.

It's pretty cool, simple but elegant little widget. Not to mention the fact that if you have users creating bookmarks in WebMaps, it's kind of cool to expose that to them in a custom app.

But, why settle for what you can do with the WebMap. You want bookmarks in your own apps and you want to take advantage of this cool new widget. But wait a second, how you going to persist these bookmarks? Just stick into LocalStorage and don't worry about it.

So how would you do this?

You could create a WebMap with an empty bookmarks array.

const map = new WebMap({
  basemap: "streets",
  bookmarks: []
});
Enter fullscreen mode Exit fullscreen mode

You can use esri/WebMap, since it has the property for bookmarks on it. There's no rule that says you need to initialize a WebMap with a webmap id, you can use it just like esri/Map and provide a basemap and layers.

Now, what you can do is on a button click or some other event, totally up to you, is add a bookmark to the bookmarks collection.

const bookmark = {
  extent: view.extent,
  name: `Bookmark: ${bookmarks.bookmarks.length + 1}`
};
bookmarks.bookmarks.add(bookmark);
Enter fullscreen mode Exit fullscreen mode

I just create the name based on the number of bookmarks that already exist. You could have some UI to let the user provide a custom name or get fancy and do some reverese geocoding to get an address at the center of the extent or city, county, whatever floats your geoboat.

Now I can add that bookmark to local storage.

const rawBookmarks = bookmarks.bookmarks.map(({ active, extent, name, thumbnail }) => ({ active, extent, name, thumbnail }));
const localData = localStorage.setItem(BOOKMARK_KEY, JSON.stringify(rawBookmarks));
Enter fullscreen mode Exit fullscreen mode

To access these stored bookmarks when the app reloads, you can do this.

let existingData = [];
const existingBookmarks = localStorage.getItem(BOOKMARK_KEY);
if (existingBookmarks) {
  existingData = JSON.parse(existingBookmarks);
}
const map = new WebMap({
  basemap: "streets",
  bookmarks: existingData
});
Enter fullscreen mode Exit fullscreen mode

That will persist the bookmarks when your application reloads. Awesome right?!

You can of course add a way to delete a bookmark, or clear all bookmarks, but I'll leave that up to you.

You can have some fun with this in a sample application.

So have fun with it! Don't forget, the tools are there for you to make some awesome apps, you just got put in a little work.

Enjoy and hack away!

Originally published at odoe.net

Top comments (0)