<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Zifan W on Medium]]></title>
        <description><![CDATA[Stories by Zifan W on Medium]]></description>
        <link>https://medium.com/@zifanw9?source=rss-a2bb36f3f884------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*xLnL-MZmhmC6mL7r</url>
            <title>Stories by Zifan W on Medium</title>
            <link>https://medium.com/@zifanw9?source=rss-a2bb36f3f884------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 13:57:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zifanw9/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Can we add pie charts as a map layer? And how does a pie chart layer work?]]></title>
            <link>https://medium.com/@zifanw9/can-we-add-pie-charts-as-a-map-layer-and-how-does-a-pie-chart-layer-work-8a431d336ad4?source=rss-a2bb36f3f884------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a431d336ad4</guid>
            <category><![CDATA[mapping]]></category>
            <category><![CDATA[mapbox]]></category>
            <category><![CDATA[cartography]]></category>
            <category><![CDATA[demographics]]></category>
            <category><![CDATA[gis]]></category>
            <dc:creator><![CDATA[Zifan W]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 00:51:42 GMT</pubDate>
            <atom:updated>2026-11-19T00:51:42.274Z</atom:updated>
            <content:encoded><![CDATA[<p>Yes. The <a href="https://github.com/zwang-geog/maplibre-gl-pie-charts">maplibre-gl-pie-charts</a> package adds a pie or donut chart layer to a MapLibre GL JS or Mapbox GL JS map. This article explains when a map needs one pie chart per feature, and then how that layer is drawn.</p><p>Imagine households grouped into three income categories: under $60,000, $60,000 to $100,000, and over $100,000. Households from all three categories can live in the same census tract, and a country contains many tracts. In the census table, each tract is a row, or feature, and each income category is a column, or attribute. Each cell is the number of households in that tract and that category.</p><p>A choropleth paints each tract one color, and that color has to come from a single number. Coloring by the household count of one income category leaves the other categories off the map. Coloring by whichever category has the most households, a dominance map, does consider every category, but only the winner is drawn. A tract split about evenly then looks the same as a tract where one category has almost all of the households. Drawing a separate choropleth for each category can show every count, but the reader has to compare across maps.</p><p>A pie chart fits when those columns are parts of one whole: all households in the tract. Each category becomes a slice, and the angle of the slice is that category’s share of the tract total. A pie chart layer draws one chart for each feature, placed at a point that represents the feature. For a polygon such as a census tract, that point is often the centroid. The map then shows every category’s share in each tract, and how the mix changes from place to place: where one income group dominates, where two groups have similar shares, and where that pattern shifts.</p><p>Mapping features as pie charts has long been part of ArcGIS Desktop, and the ArcGIS Maps SDK for JavaScript has offered the same kind of layer for some time. What was missing was an open-source layer in the <em>MapLibre</em> and <em>Mapbox</em> ecosystem. Next I will explain how <em>maplibre-gl-pie-charts</em> draws that layer.</p><p>MapLibre GL JS and Mapbox GL JS both offer a custom layer interface, where we can write our own WebGL program that draws features on the GPU for efficient rendering. My WebGL program has <strong>one vertex shader</strong> and <strong>one fragment shader</strong>.</p><p><strong>The vertex shader decides where to draw. It works with two inputs — where the chart sits, and how large it is.</strong></p><p>The chart sits at the feature’s longitude and latitude, supplied from the data source. The package converts that position to Web Mercator internally and normalizes both coordinates to a range from 0 to 1.</p><p>The chart size is based on the <em>radius</em> option that you pass in. It can be specified as one radius for every chart, or as an array of monotonically increasing [<em>total</em>, <em>radius</em>] pairs. Each pair in the array is referred to as a radius step, with index starting from 0, and it serves as lookup table: given a feature, sum all its categories’ values, and compare that sum with the <em>total</em> of each pair to determine the <em>radius</em> used to draw a pie chart for this feature.</p><p><strong>The vertex shader</strong> projects each feature’s position onto the screen, and <strong>places a square</strong> centered around that anchor point. The chart size or radius is the square’s half-width. The chart size is in pixels, so the chart stays the same size on screen as the map zooms.</p><p><strong>The fragment shader decides the color of each pixel in that square</strong>.</p><p>Some pixels are inside the square but outside the pie’s circle (i.e., distance to the square’s center is larger than the specified chart radius), they are left transparent.</p><p>A pixel inside the circle has an angle, measured clockwise from the top, and that angle is used to determine the slice that the pixel falls within. This needs <strong>an additional input that answers how the circle is divided</strong>. This input is derived from the data source’s attributes; users need to specify the list of attributes for computing each slice’s share via the <em>slices</em> option of the package.</p><p>For each feature, the package computes the sum of all attributes specified in <em>slices</em> list and divides each individual attribute value by this sum to get each slice’s share. However, rather than storing those shares directly, the package stores a running total from 0 to 1. For example, under $60,000 income category has a slice share of 0.2, $60,000-$100,000 has a slice share of 0.3, and over $100,000 has a slice share of 0.5. The running totals of each category will be 0.2, 0.5, and 1.0 respectively. Such running totals storage is more convenient for angle comparison. <strong>The fragment shader walks those running totals until it passes the pixel’s angle, to determine the slice corresponding to that pixel, and thus color the pixel accordingly</strong>.</p><p>In addition to simply rendering each feature as a pie chart, users might be interested in filtering features based on a particular attribute’s share. For example, only showing pie charts for census tracts with <em>≥ 30%</em> households having <em>income above $100,000</em>. The ≥ is known as an <em>operator</em>, and other possible operators include ==, &gt;, ≤, and &lt;. The <em>30%</em> — when written as a fraction like <em>0.3</em> — is referred as <em>number </em>in the context of filtering condition, and it is a <em>share threshold</em> that users want to impose as a lower or upper bound. The <em>income above $100,000</em> corresponds to an attribute or category in the data source; while the user specifies the name of attribute that they would like the filter to base on, the package needs to look up each feature’s value of this particular attribute, and compares this <em>actual share</em> of the feature with the <em>share threshold</em>.</p><p>The package already packs each feature’s center, radius step, and running totals into one record, and copies every record into a single buffer on the GPU. Therefore, a client-side filter implementation can rely on this GPU buffer without another copy of the data on CPU.</p><p>The comparison runs in the vertex shader. However, a shader cannot take the comparison as the user wrote it; it cannot read an operator such as “greater than” or an attribute name. It only receives numbers, so a direct comparison has to be encoded before it is sent to the shader. The package turns each filtering condition into three numbers.</p><p>Each operator becomes a small integer: == is 1, &gt; is 2, ≥ is 3, &lt; is 4, and ≤ is 5. The <em>number</em> representing the share threshold stays as given.</p><p>Since all attributes corresponding to slices have their names given by the <em>slices</em> array, the package looks up a given attribute name in this <em>slices</em> array and gets its index (starting from 0).</p><p>Then, all three components of a filter condition are in numeric format and can be passed to the vertex shader as input. The vertex shader performs logical checks, and if the condition is not met, it can position the chart off canvas so it is not visible to the end users.</p><p>Pie charts on map features have long been available in ArcGIS. <strong><em>maplibre-gl-pie-charts</em></strong> fills the gap in the MapLibre and Mapbox ecosystem: an open-source layer that draws one pie chart for each feature, on the GPU, from the category values already on that feature.</p><p>That layer is an alternative to painting each place with a single color. A choropleth has to drop every category but one, or keep only the category that wins. A pie chart keeps the whole mix in one view, and the map shows how that mix changes from place to place. The same pattern shows up in demographic data, such as households by income or residents by educational attainment; in political science, such as votes received by each candidate; and in land management, such as the area of each land use or land cover type inside an administrative boundary.</p><p>This article followed a solid pie and a single share threshold. The package also supports drawing the same charts as donuts, leaving a hole in the center of each chart. Filters can go beyond one condition: all requires every condition to hold, and any requires only one of them, so several conditions can be merged into one filter.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a431d336ad4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Viewport-dependent wind visualization for Mapbox GL and MapLibre]]></title>
            <link>https://medium.com/@zifanw9/viewport-dependent-wind-visualization-for-mapbox-gl-and-maplibre-ecb8356d65a8?source=rss-a2bb36f3f884------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecb8356d65a8</guid>
            <category><![CDATA[mapbox]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[gis]]></category>
            <category><![CDATA[maplibre]]></category>
            <category><![CDATA[webgl]]></category>
            <dc:creator><![CDATA[Zifan W]]></dc:creator>
            <pubDate>Mon, 19 Oct 2026 07:30:44 GMT</pubDate>
            <atom:updated>2026-10-19T07:30:44.451Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://www.npmjs.com/package/mapbox-exif-layer"><em>mapbox-exif-layer</em></a> v1.5.0’s <em>NewParticleMotion</em> class keeps wind particles inside both the data extent and the map viewport, so a pan or zoom into calmer wind still leaves enough particles to read the flow. This article explains why the classic <em>ParticleMotion</em> class, which ignores the viewport, can leave a city or a neighborhood nearly empty, how <em>NewParticleMotion</em> places and resets particles from the padded viewport, and three characteristics that make that animation succeed: a robust random number generator, a zoom-dependent particle count, and a uniform tail length.</p><h3>The classic: particles distribution is independent of map viewport</h3><p>The classic <em>ParticleMotion</em> layer class of <a href="https://www.npmjs.com/package/mapbox-exif-layer"><em>mapbox-exif-layer</em></a> package distributes particles across the entire data extent (when using a NOAA GFS forecast, that is the whole world). When users zoom in to a small geographic area such as a neighborhood or a city, few particles, or none, may be present there.</p><figure><img alt="With ParticleMotion layer class, zoom into an area with relatively low wind tends to have few or no wind particles visible, depending on if the particle representing the simulated air mass just moves to the area or not at the time." src="https://cdn-images-1.medium.com/max/875/1*HT7Il2e3L9rUa_2uKhKFsw.png" /><figcaption>With ParticleMotion layer class, zoom into an area with relatively low wind tends to have few or no wind particles visible, depending on if the particle representing the simulated air mass just moves to the area or not at the time.</figcaption></figure><p>Why are there so few particles when zooming in to certain areas? Imagine that each particle represents a mass of air, and real-world wind represents the movement of masses of air over a period of time. A particle motion layer on a web map essentially is simulating the position of each particle or air mass on each update, about every 50 ms by default, and the new position of the particle at the next update is determined by the relative west-east (u-component) and south-north (v-component) velocities [<a href="https://medium.com/@zifanw9/a-low-cost-custom-wind-particle-motion-layer-in-mapbox-gl-js-9a51978e3ffb">1</a>]. Over time, the simulated particle positions tend to be concentrated in high-wind areas such as cyclones, atmospheric rivers, or over ocean; conversely, few or no particle will be present in areas with calmer wind.</p><p>Furthermore, <em>mapbox-exif-layer</em> package also implements a particle position reset logic that if an area has wind speed below 1.5 miles per hour, a particle reaching that area has its position reset to a random location. That logic is critical in preventing particles from becoming trapped in extremely low-wind areas (the air is mostly still), but the side effect is a more exaggerated contrast in particle count between high and low wind areas.</p><h3>The new: viewport-dependent particle distribution</h3><p>A web map showing parcel, building, or road level details typically needs zoom level 15 or higher, and such a web map usually corresponds to urban land areas with low wind speed. If a wind particle layer is to be added as an overlay to those other layers, at least some particles are always needed to depict wind patterns in the current map viewport. The classic <em>ParticleMotion</em> layer class might be inadequate here, and <em>NewParticleMotion</em> layer class is introduced to address this inadequacy.</p><p><em>NewParticleMotion</em> layer class incorporates map viewport in distributing and resetting particles in following two ways:</p><ol><li>When the layer is initially added to the map, or when a <em>moveend</em> map event is fired, all active particles’ positions are placed at random inside the viewport plus an 8% pad, and kept inside the data extent. Mapbox and MapLibre fire <em>moveend</em> when a pan or zoom finishes. During the gesture the positions are not reset, so a zoom-out stays clumped until <em>moveend</em>.</li><li>After the particle position for the next update is computed, if the newly computed position is outside the viewport plus that 8% pad, the particle is placed at random inside that padded viewport and kept inside the data extent, in addition to the usual reset rules outlined in [<a href="https://medium.com/@zifanw9/a-low-cost-custom-wind-particle-motion-layer-in-mapbox-gl-js-9a51978e3ffb">1</a>].</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*jD-MtDtzGc8TVp62X1Sl8w.png" /><figcaption>With NewParticleMotion layer class, zoom into an area with relatively low wind usually still displays sufficient particles to depict the general wind pattern by resetting particle positions to be within or near the viewport extent, rather than solely relying on the timing of simulated movements of air masses.</figcaption></figure><h3>The importance of a robust random number generator</h3><p>Resetting a particle’s position needs a random number, and WebGL shader programs have no native random number generator. A hash built in the shader therefore needs an input with two properties. It should be unique for each particle, and it should change from one position reset to the next.</p><p>Unique seeds keep particles from resetting to the same position. Hashing a particle’s current position does not provide that uniqueness. Wind patterns such as atmospheric rivers and cyclones pack particles close together, so those live positions leave the hash too little precision to tell the particles apart. An extreme example is a viewport-dependent reset, where every particle position is placed inside the viewport after the map pans or zooms. Zooming into a small area then packs all of them into that small region. Hashing those current positions produces duplicate seeds. After zooming back out, particles that share a seed receive the same new position and stack on top of each other. The number of particles held in the buffer stays the same. Repeating the zoom leaves fewer and fewer of them appearing to move on the map.</p><p>The hash input also has to change between resets, so a particle’s reset position differs from one time to the next. A constant seed does not provide that variability. When a particle moves outside the padded viewport, it is placed back inside that viewport and inside the data extent, for example a country-level forecast. A constant seed produces the same random number, and the same reset position, every time. Between resets the particle still follows the wind. What should vary is where it reappears.</p><p>Vladimir Agafonkin describes why wind particle animation needs a robust random number generator in [<a href="https://medium.com/mapbox/how-i-built-a-wind-map-with-webgl-b63022b5537f">2</a>]. <em>mapbox-exif-layer</em> v1.5.0 is characterized by an enhanced hashing strategy that prevents particles from collapsing. Each particle keeps the grid position it was given at the start, including a small jitter, as a stable seed. The seed is stored and hashed when a random number is needed, so particles that later meet can still be sent to different places. Every position update also supplies a new random value. The new position is the hash of the stable seed mixed with that value, so successive resets land in different places. The decision to reset still hashes the particle’s live position mixed with the same new random value.</p><h3>The importance of zoom-dependent particle count</h3><p>When visualizing wind, large-scale features such as cyclones and atmospheric rivers carry a great deal of visual weight and catch the eye. They show best at a small zoom level: about 2 or 3 for a global pattern, and about 4 or 5 for a large country. A viewport covering that much area needs a large number of particles to depict them, for example about 30,000 for the world and about 10,000 for a large country.</p><p>At zoom level 15 and above, the map is mainly for urban features such as roads and buildings, and the wind is supplemental. Crowding thousands, or tens of thousands, of particles into that viewport obscures the features the reader came to see. Most weather forecasts are also coarser than the map by then. A NOAA GFS grid of 0.25 degrees is coarser than the map by about zoom 12, and a NOAA NAM CONUS nest of 5 km by about zoom 14. Thousands of particles in a high-zoom viewport then share nearly the same direction and speed, and they no longer show a weather pattern.</p><p>Rather than using one constant particle count for the padded viewport, the <em>NewParticleMotion</em> class in <em>mapbox-exif-layer</em> treats the count as a function of zoom. The smaller the zoom level, the more particles are needed, and the larger the zoom level, the fewer particles are needed. That function balances depicting the wind pattern in enough detail against leaving the other map layers unobstructed.</p><p>The position buffers and the age buffers (see the WebGL buffers in [<a href="https://medium.com/@zifanw9/a-low-cost-custom-wind-particle-motion-layer-in-mapbox-gl-js-9a51978e3ffb">1</a>]) are initialized to the maximum count the zoom function can return. A <em>liveCount</em> value is adjusted after each moveend. The shader draws only that many particles.</p><h3>The importance of a uniform tail length</h3><p><em>mapbox-exif-layer</em> has long drawn a tail for each wind particle. The tail is a few trailing dots, three by default, sitting upwind of the main particle, the head.</p><p>The classic <em>ParticleMotion</em> class places those dots a step back that depends on the head’s wind speed, so the tail length follows the wind speed. A longer tail makes speed easier to read, and that is useful for a wind pattern in a small area. At a low zoom level, a global pattern looks different. Calmer inland wind shrinks the tail toward a dot, and the head moves so slowly that it looks still. The wind direction becomes hard to read.</p><p><em>NewParticleMotion</em> uses a uniform tail length so that direction in those calmer areas stays legible when the view is zoomed out. A slow particle and a fast one draw the same streak. The streak shows direction, and the particle color shows wind speed.</p><p><em>mapbox-exif-layer</em>’s NewParticleMotion class is an open-source wind layer for Mapbox GL and MapLibre GL: particles stay in the current view, the count follows zoom, and every tail has the same length. That is the picture offered by Mapbox&#39;s raster-particle layer and by commercial wind layers such as Xweather.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecb8356d65a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying and Rebuilding a Digital Letter-Writing App as a Tool Instead of Platform — The Story…]]></title>
            <link>https://medium.com/@zifanw9/why-i-migrated-a-digital-letter-writing-app-from-aws-to-supabase-platform-vs-tool-f29eafcd758f?source=rss-a2bb36f3f884------2</link>
            <guid isPermaLink="false">https://medium.com/p/f29eafcd758f</guid>
            <category><![CDATA[relationships]]></category>
            <category><![CDATA[digital-minimalism]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[product-management]]></category>
            <dc:creator><![CDATA[Zifan W]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 03:53:03 GMT</pubDate>
            <atom:updated>2026-08-26T03:10:14.335Z</atom:updated>
            <content:encoded><![CDATA[<h3>Simplifying and Rebuilding a Digital Letter-Writing App as a Tool Instead of Platform — The Story of Lingerlet</h3><p>Three days ago, I had a fully working AWS stack for <a href="https://lingerlet.com/"><em>Lingerlet</em> </a>— a digital letter-writing app for people who already know each other. VPC, ECS, RDS, Cognito, WAF — the works. Then I threw most of it away and rebuilt the product on Supabase in the past three days. This isn’t a story about AWS being bad or Supabase being magic. It’s about a product choice mistake that I made: I had been building a platform when what I actually needed was a tool.</p><figure><img alt="A screenshot of the draft digital letter page of Lingerlet" src="https://cdn-images-1.medium.com/max/1024/1*6evLTHc9bdFhNapqwZ-AYw.png" /><figcaption>A screenshot of the draft digital letter page of Lingerlet</figcaption></figure><h3><strong>What product characteristics are really needed?</strong></h3><p>As a digital letter-writing app, it should reflect the real-world<br>experience of writing and receiving a letter. Breaking that experience<br>down, two distinct sets of characteristics emerge.</p><p>✅ The letter itself:</p><ul><li>Handwritten-style fonts</li><li>A physical paper look</li><li>Letter-sized paper dimensions</li></ul><p>❓The envelope that carries it:</p><ul><li>From and To addresses</li><li>Stamp in the corner</li><li>A postmark (e.g., a wavy-line cancellation mark, a circular date stamp)</li></ul><p>When I migrated to Supabase, I kept everything in the first list and<br>dropped everything in the second. That wasn’t an arbitrary<br>choice — the envelope-related features are exactly the ones<br>that require a persistent platform to make sense.</p><h3><strong>The pain of maintaining a persistent platform</strong></h3><p>❌ <strong>A virtual address system, just to protect privacy</strong></p><p>Putting <em>“From” and “To” addresses</em> on a digital envelope means users can’t just use their real-world addresses — that would leak physical location and enable identity takeover. So the only real option is a <em>virtual address system</em>: users create an address inside the app, and add their contacts’ virtual addresses to an in-app address book. That’s a lot of setup just to produce a nicely formatted letter and share it with family or friends. First-time users, after signing up, are often left wondering what to do next — before they’ve even written a word.</p><p>❌ <strong>A two-sided requirement that kills adoption</strong></p><p>Worse, if someone wants to write to a specific person, that person needs an account too. This single requirement is enough to make most people abandon the idea entirely — not because the app is bad, but because few, if any, of the people they’d actually want to write to are already using it. A letter-writing app with no one to write to is just an empty room.</p><p>❌ <strong>A stamp collection nobody asked for</strong></p><p>Some users might enjoy collecting digital stamps, sure. But writing and receiving a digital letter doesn’t actually need a stamp system to work — what matters is the content, and how it feels to read. A collection mechanic is a nice-to-have bolted onto the core experience, not something the experience depends on.</p><h3>Writing digital letters as a Tool, Not a platform</h3><p>✅ <strong>Drafting &amp; exporting should be free, unlimited, and require no sign-in</strong></p><p>Not every part of the experience needs sign-in, and drafting a letter is the clearest example. A user should be able to open the app, start typing, and see their words rendered in a <strong>handwritten font </strong>on a <strong>paper-textured background</strong> — immediately.</p><p>There’s no reason to gate this behind a login. <strong>Drafting and exporting a letter as a PDF happens entirely in the browser</strong>: the rendering, the pagination, the font — all client-side. No server call, no database write, no account required.</p><p>✅ <strong>Making the letter shareable, without becoming a platform</strong></p><p>Once a letter is written, the next question is how it reaches the person it’s for — and this is where it would have been easy to fall back into platform thinking. Instead, I designed two deliberately separate paths.</p><p><strong>The first is pure export: the writer saves the letter as a PDF</strong>, either downloading it directly or, on devices that support it, using the browser’s <em>navigator.share</em> API to send it straight through Mail, Messages, or AirDrop. This is entirely client-side — no sign-in, unlimited use, and <em>Lingerlet</em> never sees the file or knows it was sent.</p><p><strong>The second is a shareable link</strong>. After signing in with Google, a writer can generate a link to the letter’s content, along with the paper and font styles they chose. They can send that link through whatever channel they prefer — text, email, chat, anything. The recipient opens it and signs in with the Google account matching the Gmail address the writer specified when creating the link, and that’s what unlocks the letter for them.</p><p>Two paths, same underlying principle: the app never inserts itself between the writer and however they’d naturally reach someone. It just makes sure the version of the letter they receive still looks like a letter.</p><h3>What this means for the backend</h3><p>The old, platform-shaped version needed a real backend to match its ambitions. A virtual address system, a stamp gallery, a record of stamps each user had collected — each of those needed its own database tables. On top of that, something had to run all the queries, manage self-signed access and refresh tokens, keep drafts in sync, handle deletion of drafts and received mail, and take on the long-term responsibility of storing every received letter securely.</p><p>That’s a real commitment — not just in engineering time, but in ongoing cost. Running that stack reliably on AWS came out to at least a few hundred dollars a year, for a product that didn’t even have a way to charge anyone yet.</p><p>The new, tool-shaped version of <em>Lingerlet</em> needs almost none of that. The only thing worth persisting is the letter content itself, and only when a writer chooses to generate a shareable link — one table. I can shrink that responsibility further by enforcing a retention window, say 90 days, rather than promising to store anything indefinitely. There’s no address system to maintain, no token rotation logic to write, no long-term custody of anyone’s data to take on.</p><p>Supabase turned out to be a near-perfect fit for what was left: managed Postgres with row-level security doing the access-control work I used to write by hand, and an auth flow I didn’t have to build myself.</p><h3>Where Lingerlet Stands Today</h3><p>Lingerlet is now a free tool for writing a digital letter that actually looks and feels like one — handwritten fonts, paper texture, proper pagination — with no sign-in required to draft or export it. If you want to send it to someone, export it as a PDF and share it however you already would, or generate a link (one Google sign-in) and send that instead. No pen-pal matching, no address book, no account you have to maintain. Just a letter, written for someone you already know. Try it at <a href="https://lingerlet.com/">lingerlet.com</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*INxiGlfz2yCgfhgQVACxwQ.png" /><figcaption>A screenshot of the view digital letter page (shareable link after opening): Save PDF and audio functionalities included</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FpPoprlBM_c4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpPoprlBM_c4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FpPoprlBM_c4%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/32a63ddbab32468580e2382424e0b0f3/href">https://medium.com/media/32a63ddbab32468580e2382424e0b0f3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f29eafcd758f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Assessing packages for mapping wind as particle motion layer in MapLibre]]></title>
            <link>https://medium.com/@zifanw9/assessing-packages-for-mapping-wind-as-particle-motion-layer-in-maplibre-2ec8db9aea33?source=rss-a2bb36f3f884------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ec8db9aea33</guid>
            <category><![CDATA[wind]]></category>
            <category><![CDATA[web-mapping]]></category>
            <category><![CDATA[gis]]></category>
            <category><![CDATA[maplibre]]></category>
            <category><![CDATA[mapbox]]></category>
            <dc:creator><![CDATA[Zifan W]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 00:49:17 GMT</pubDate>
            <atom:updated>2026-07-07T01:51:37.912Z</atom:updated>
            <content:encoded><![CDATA[<p>There are three open-source packages for adding wind particle animation layer in maplibre-gl: <em>mapbox-exif-layer</em>, <em>maplibre-gl-wind</em>, and <em>@sakitam-gis/maplibre-wind</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*jGvu561Oo11vOsC8_1wi8g.png" /><figcaption>A comparison table of mapbox-exif-layer, maplibre-gl-wind, and sakitam-gis/maplibre-wind packages, see the <a href="https://github.com/zwang-geog/mapbox-exif-layer/blob/main/comparison-all-wind-layer-package.csv">structured csv</a></figcaption></figure><p><em>@sakitam-gis/maplibre-wind</em> does not work on MapLibre v5 due to compatibility issues, and its particle colors do not vary by speed values. Furthermore, on mobile devices’ browsers, the <em>@sakitam-gis/maplibre-wind</em> layers might not show up [<a href="https://github.com/sakitam-fdd/wind-layer/issues/276">1</a>][<a href="https://github.com/sakitam-fdd/wind-layer/issues/191">2</a>]. On the other hand, the other two packages are MapLibre v5 compatible and varying particle colors by speed; <em>mapbox-exif-layer</em> in particular utilizes Mapbox/MapLibre custom layer interface that shares the same WebGL context lifecycle, same camera, same frame as the basemap, making it the most mobile device browser friendly among the three packages.</p><p><em>mapbox-exif-layer </em>is the only package that supports MapLibre globe projection. Both <em>mapbox-exif-layer</em> and <em>sakitam-gis/maplibre-wind</em> claim to support GeoTIFF as input source.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w14qxWX_9O-Fi9WZ59gvVg.png" /><figcaption>mapbox-exif-layer: Particles are colored by speed. Each main particle is followed by smaller trailing particles whose size decays along the path, which makes wind direction easy to read and ties overall tail length to wind speed.</figcaption></figure><figure><img alt="maplibre-gl-wind: Particles are colored by speed. Line width is adjustable, but there is no true tail implementation — motion reads as fast-moving dashes rather than continuous trails." src="https://cdn-images-1.medium.com/max/1024/1*crHa6ANBhge-kg5vxgkESQ.png" /><figcaption>maplibre-gl-wind: Particles are colored by speed. Line width is adjustable, but there is no true tail implementation — motion reads as fast-moving dashes rather than continuous trails.</figcaption></figure><figure><img alt="@sakitam-gis/maplibre-wind: Particles use a uniform color regardless of wind speed. A trailing effect is implemented, so motion reads as streaks rather than isolated dashes." src="https://cdn-images-1.medium.com/max/1024/1*2_0xLf2KZtfHGi7HXyy7gg.png" /><figcaption>@sakitam-gis/maplibre-wind: Particles use a uniform color regardless of wind speed. A trailing effect is implemented, so motion reads as streaks rather than isolated dashes.</figcaption></figure><p>As the screenshots show, <em>mapbox-exif-layer</em> delivers the strongest visuals: speed-based coloring and decaying tails make both direction and intensity easy to read at a glance.</p><p>It also preserves finer-scale structure better than <em>@sakitam-gis/maplibre-wind</em>. For example, the S-shaped atmospheric river northeast of Crownpoint appears in both <em>mapbox-exif-layer</em> and <em>maplibre-gl-wind</em>, but is smoothed away in <em>@sakitam-gis/maplibre-wind</em>, which tends to generalize local flow into broader, less faithful patterns.</p><p>Relative to <em>maplibre-gl-wind</em>, <em>mapbox-exif-layer</em> uses a slower, more deliberate particle update (by default, physics is decoupled from display refresh). That calmer motion makes it easier to track individual streamlines and interpret small-scale features, whereas <em>maplibre-gl-wind</em> can feel rushed — especially on high-refresh displays — because animation is tied more closely to the render loop.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FSLPBfteIbRE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSLPBfteIbRE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FSLPBfteIbRE%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3876ae751107fae49ce4400964e87b91/href">https://medium.com/media/3876ae751107fae49ce4400964e87b91/href</a></iframe><p>Despite the name, <em>mapbox-exif-layer</em> is not limited to Mapbox or EXIF JPEGs. Its ParticleMotion layer targets wind-style flow visualization on both mapbox-gl and maplibre-gl, and its SmoothRaster layer is suited to smooth scalar fields such as temperature—without the blocky look of raw grid cells.</p><p>Recent releases have broadened that scope: MapLibre v5 and globe projection (v1.2.1+), experimental GeoTIFF support (v1.3.1+), and generic PNG/JPEG inputs with optional EXIF ImageDescription for velocity metadata. Compared with <em>maplibre-gl-wind</em>, two practical differences stand out:</p><ol><li><strong>Image format and no-data</strong>. <em>mapbox-exif-layer</em> can encode NA cells in the B-band, so both JPEG and PNG work in production pipelines. <em>maplibre-gl-wind</em> stores no-data in the PNG alpha channel, which effectively limits you to PNG.</li><li><strong>How min/max normalization is defined.</strong> Continuous wind or temperature must be scaled to 0–255 before encoding. You can fix that range in two ways:</li></ol><ul><li>(1) <em>Dataset-independent </em>— use a typical physical range you care about (e.g. u/v wind components in −50 to 50 m/s, or temperature in −50 to 50 °C), regardless of this timestep’s actual extremes. In <em>mapbox-exif-layer</em>, pass velocityRange (ParticleMotion) or scalarValueRange (SmoothRaster) as a [min, max] array in the constructor.**</li><li>(2) <em>Dataset-dependent</em> — normalize using this file’s actual min and max. That improves precision when the range is narrower than your global bounds, and it preserves unusual extremes when they exceed typical limits. For that path, use an EXIF-enabled JPEG and store per-band min/max in ImageDescription (encoding rules are documented on the <a href="https://github.com/zwang-geog/mapbox-exif-layer/blob/main/docs/jpeg-source.md#method-2-dynamic-dataset-dependent-minmax-values">site</a>). Credit to <a href="https://github.com/sakitam-fdd/wind-layer/tree/master/packages/mapbox-gl">sakitam-fdd/wind-layer</a> for the original EXIF approach.</li></ul><p><em>maplibre-gl-wind </em>does not offer the EXIF path; imageUnscale is fixed in the constructor. <em>mapbox-exif-layer</em> (v1.3.2+) supports both fixed ranges and self-describing JPEGs, so you can choose per dataset and per layer type.</p><p>For wind on Mapbox or MapLibre, <em>mapbox-exif-layer</em> is my recommendation. Though as a disclaimer, I am the author of this package; it is the many issues in <em>@sakitam-gis/mapbox-wind</em> (and its twin <em>maplibre-wind</em>) that motivate me to develop my own package, and <em>maplibre-gl-wind</em> did not exist when I developed <em>mapbox-exif-layer</em>. I found that AI cannot accurately describe the trade-off among those wind packages, it only gives recommendations based on buzz words like “1 million particles”, “GPU accelerated”, “wind” without actually knowing the actual implementations nor final products; that is why I decide to give an assessment myself.</p><p>The alternatives are worth knowing — <em>maplibre-gl-wind</em> for a quick deck.gl experiment, <em>@sakitam-gis/maplibre-wind</em> if you are pinned to MapLibre v3 and accept its trade-offs — but if you care about aesthetics, fidelity, and setSource method that is useful in time-slider apps, <em>mapbox-exif-layer</em> is the clear choice.</p><p>Learn more at <a href="https://www.mapbox-exif-layer.com/">www.mapbox-exif-layer.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ec8db9aea33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Teaching AI to Read a Map: Lessons from Building a Wildfire Situational Awareness Agent]]></title>
            <link>https://medium.com/@zifanw9/teaching-ai-to-read-a-map-lessons-from-building-a-wildfire-situational-awareness-agent-448ae11e6a1f?source=rss-a2bb36f3f884------2</link>
            <guid isPermaLink="false">https://medium.com/p/448ae11e6a1f</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[mapbox]]></category>
            <category><![CDATA[gis]]></category>
            <dc:creator><![CDATA[Zifan W]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 15:33:20 GMT</pubDate>
            <atom:updated>2026-06-08T15:33:20.334Z</atom:updated>
            <content:encoded><![CDATA[<p>On May 8, 2026, I released a conversational AI agent, or chatbot, to the official interactive web app of University of California, Santa Barbara Wildfire Resilience Initiative: <a href="http://www.webapp.wri.ucsb.edu/">www.webapp.wri.ucsb.edu</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FWaYHFFMLknA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DWaYHFFMLknA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FWaYHFFMLknA%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/359bf3fa1f91f4779421bc09a6f99046/href">https://medium.com/media/359bf3fa1f91f4779421bc09a6f99046/href</a></iframe><p>The chatbot is equipped with knowledge about each layer’s description, symbology, and possible user interactions. It is also <strong>capable to interact with the map via zooming, panning, changing the basemap, or toggling layers</strong>. By calling the tool that captures map canvas screenshot, AI model <strong>can read and interpret the map screenshot to provide context-aware answers</strong>.</p><p>The goal of having a chatbot is to help users <strong>navigate and better understand 20+ map layers</strong>, and it is not for replacing human decision-making or human analysis. The chatbot is powered by Google <a href="https://ai.google.dev/gemini-api/docs/interactions/interactions-overview?ua=chat#javascript_2">Gemini Interactions API</a>. At the time I write this article, the chatbot uses Gemini 3.5 Flash with the chatbot version released on May 27.</p><p>In this article, I will provide a technical discussion on how the chatbot underlying the WRI web app works. It should be acknowledged that many enterprises have developed their map or spatial analysis agents: ESRI [ <a href="https://www.esri.com/arcgis-blog/products/js-api-arcgis/announcements/arcgis-maps-sdk-for-javascript-whats-new-in-5-0">1</a> ] [ <a href="https://www.esri.com/en-us/software-engineering/blog/articles/ai-orchestration-in-the-browser">2</a> ] [ <a href="https://www.linkedin.com/posts/jimenezortegaraul_most-developers-assume-ai-orchestration-belongs-share-7468004916700295169-PaEf/?utm_source=share&amp;utm_medium=member_desktop&amp;rcm=ACoAACUvPSABraxlXSxjkwnbWAF6ZpGkHsesCnY">3</a> ], CARTO [ <a href="https://carto.com/ai-agents/">4</a> ], Foursquare [ <a href="https://foursquare.com/products/spatial-desktop/">5</a> ], Google Maps [ <a href="https://blog.google/products-and-platforms/products/maps/ask-maps-immersive-navigation/">6</a> ] and Google Earth [ <a href="https://developers.google.com/maps/documentation/earth/gemini/overview">7</a> ].</p><h3>Client-side function calling loop</h3><p>To enable the AI agent to interact with the map, I developed a set of JavaScript functions for manipulating the map. Each function corresponds to a custom tool that the AI agent can call.</p><p>Unlike typical chatbot tools that query databases or call internal APIs, <strong>map manipulation tools must run in the browser because only the client has direct access to the Mapbox</strong> (or similar) map instance and its state. Therefore, I make the function calling loop within the front-end application code instead of server-side. Basically, when a user types and sends a message to the chatbot, the AI model may choose to return simple text response (no tool call) or to call one or more tools for map manipulation (with optional text response as well). If the AI model makes any tool call, the client-side will invoke the JavaScript functions corresponding to the called tools and send the function results back to the AI model. This process continues until either the AI model returns only text response without any tool call or the pre-defined maximum number of rounds is reached.</p><p>Even though I write the function calling loop as client-side code, I still need a backend proxy service. The backend proxy service serves as a middleware between the client-side and the Gemini API (or any other AI provider’s API). <strong>The backend proxy service is essential for two reasons: 1. the API key should never be exposed in client-side code for security reasons, and alternative authentication methods also require a backend setup; 2. browser can block CORS pre-flight response if the front-end code tries communicate directly with the Gemini API.</strong> Additionally, I choose to inject system instructions and tool definitions to the request body in the backend proxy service; that prevents direct exposure of such information to the client-side code, and avoids sending the same information repeatedly between the client and the backend proxy. Luckily, Google Gemini Interactions API manages the chat history internally, so I do not need to manage the chat history in my front-end nor backend proxy service. <strong>I choose Go for the proxy service</strong> because it can append to request JSON in-place, avoiding full object copies that would cause memory spikes when requests include base64-encoded map screenshots.</p><p>While currently I have not implemented any server-side tool for the chatbot, I think that <strong>a client-side function calling loop still has potential to execute server-side tools</strong>. There are two potential approaches. First, the client-side can fetch from an API endpoint (e.g., active wildfires, current weather) and forward the API response as the tool result to the AI model. Second, it is possible to create a custom function that spawns a sub-agent that runs function calling loop on server side and equipped with server-side tools; this subagent can be spawn up with SSE instead of POST request to support long-running server side tasks. However, a server-side function calling loop is absolutely needed is when users are likely to close the browser before the final response from AI model is returned; it is not my use case which I expect my web app users to constantly engage with the interactive map.</p><h3>Tools for zooming and panning the map</h3><p>While the WRI web app offers several tools for AI to use, I would like to share the details of two different tools specifically for zooming and panning.</p><p><strong>The first tool supports panning and/or zooming the current map viewport by relative increments</strong>, and it consists of 3 parameters: <em>x_change</em> for west-east (longitude) pan increment, <em>y_change </em>for south-north (latitude) pan increment, <em>zoom_change</em> for the amount to add to the current zoom level<em>.</em> Note that pan increments are in a normalized scale between -1 and 1, with 1 moving the center east or north by half of the current viewport width or height, and -1 moving the center west or south by half of the current viewport width or height. This tool is specifically designed for user instructions such as “<em>panning the map a bit to the left/right/up/down</em>” or “<em>zooming in/out a bit</em>.”</p><p>When I was prototyping the tools set, I found that the first tool is not robust when I instruct the AI agent to zoom to a specific neighborhood or area shown on the map canvas; its first attempt often cannot zoom to the requested area, and it may repeatedly takes screenshots and pan the maps that, from the user’s perspective: is this AI crazy, can it just stop?</p><p>I decided to develop a <strong>second tool that fits the map bounds to a rectangle area</strong>. In common GIS desktop software including ArcGIS Pro or QGIS, users can select the zoom in tool and long press the mouse to draw a rectangle on the map canvas and zoom in to that area, so my second tool is analogue to this idea.</p><p>When I originally design the second tool, I assumed a Cartesian coordinate with the map center as (0,0), top-left of map viewport as (-1,1), and bottom-right as (1,-1), and I assumed four parameters <em>minX</em>, <em>maxY</em>, <em>maxX</em>, <em>minY</em>. However, I am unsatisfied with the parameter description written by Cursor. For example, for <em>maxY</em>, it wrote “<em>Normalized y of the target top-left corner (top edge). In this coordinate frame, -1 is top and +1 is bottom</em>,” while -1 really implied that the current bottom edge becomes the top edge of the updated viewport, and +1 implied that the current top edge remains as the top edge of the updated viewport. I then asked Gemini to propose revisions on the parameter description, but none of the proposal make me satisfied. I then took a step back, asked Gemini why Cursor initially wrote description like that, and Gemini suggested that it might defaulted to image coordinates, whose y-axis increases from top to bottom (the opposite as geographic coordinate system). Eventually, Gemini convinced me to adopt a image coordinate system instead; no confusion when AI models wrote parameter descriptions anymore.</p><p>Hence, <strong>the second tool assumes an image-style coordinates </strong>with (0,0) corresponding to the top-left of the viewport and (1000, 1000) corresponding to the bottom-right of the viewport; the tool has four parameters: <em>left </em>for X of the rectangle’s left (west) edge, <em>top </em>for Y of the rectangle’s top (north) edge, <em>right </em>for X of the rectangle’s right (east) edge, <em>bottom </em>for Y of the rectangle’s bottom (south) edge. Each parameter supports a range between -500 and 1500 so it is possible to zoom to a neighborhood near the current viewport’s edge.</p><p>The final design of the second tool is intuitive: given a map screenshot, clip it to an area that the AI agent wants, and the map will just zoom to that “clipped” area. I found that this map-bounds-fitting tool is more effective in zooming to specific area or neighborhood in the map viewport, compared with the first tool with relative-increment-based pan and zoom.</p><h3>Nuances on asking the AI agent to zoom on the map</h3><p>Even with the two tools for zooming and panning the map, AI can still show interesting (or perhaps annoying) behavior.</p><p>For example, I have <strong>appended map states information</strong> including current zoom level and active layers <strong>at the end of user-typed message</strong> to reduce the overhead of additional tool-calling to retrieve those information. <strong>In my earliest experiments, the current map center was also appended</strong>; my system instructions has a step-by-step tool-calling example with wording such as “<em>take map screenshots only when users ask to read or interpret the map</em>.” I asked the AI agent to zoom to an area (e.g., Isla Vista). Gemini-3-flash-preview worked fine without problem, but when I switched to use Gemini-3.5-flash, <strong>the AI agent did not take any map screenshot and just started zooming and panning the map</strong>; after a few rounds of panning, the map extent <strong>ended up on the ocean</strong>. I asked the AI agent how it determined where to pan, and it said that <strong>it had internal knowledge of the place’s coordinates </strong>and it had the map center information (which can also obtained by tool calling). Hence, it sounded like <strong>it did not bother to check the ground truth of what was actually showing on the map</strong> (it ignores my system instruction instructing to reference the map and not making assumptions). Eventually I decided to take multiple actions including: (1) remove the map center information that is appended to the user input, (2) remove the tool calling examples provided in the system instruction, and use tool descriptions to suggest recommended chain of tool calls (including taking screenshot before zooming to a specific neighborhood), (3) add system instruction of ensuring the map view fits the user’s focus.</p><p>In fact, are you curious why I did not mention a tool for zooming to a specific geographic coordinate (lat/long)? I just did not make such a tool. In my opinion, coordinates are just numbers. <strong>When I pans or zooms the map, I do not need to know the coordinates of where I should zoom to; I only look at the map viewport, decide if I should zoom in or out, pan left or right</strong>. I can make decisions by <strong>solely referencing to the place or road labels, the prominent spatial patterns</strong>. That is basic map reading. <strong>Providing current map center coordinates or providing a direct tool for zooming to a specific coordinate does not necessarily provide benefits and can confuse the model</strong>. Another example would be that the model can try to do Google Maps search for the location of Isla Vista to determine the coordinates to zoom to, while I would just look at the map and zoom the map accordingly.</p><h3>Active vs visible layers: when AI confidently lies about what it sees</h3><p>The WRI web app has 3 active layers when initially opening the web page: evacuation (road LineStrings), hydrant spacing (points), and structure access (polygons). However, an active layer does not mean that is visible in the current map viewport. For example, the structure access polygons have a min zoom of 12, meaning that users have to zoom sufficient in to see those polygons; polygons are not visible with the initial map extent, even though the layer itself is active.</p><p>In the earliest version of the chatbot, I only supplied active layers information (does not take zoom level into account) to the chatbot, and I asked what it can observe from the map. It said it can “see” the structure access polygons even though “the polygons are tiny and hard to see” — it was hallucinating with confidence, assuming point features (i.e., hydrants in my case) to be the polygons features, and made the incorrect interpretation of the map when multiple layers were displayed.</p><p>I decided to write a function that checks the current map zoom level against each of my active layers’ expected zoom ranges (min zoom is mandatory, and max zoom is optional and only set for some layers), and I supplemented this active layers within visibility range information whenever the active layers information is supplied to the AI model.</p><p>Additionally, I wrote layer visibility guidelines in system instruction to warn the AI model that layer visibility is affected by zoom range, layer extent, and data availability within viewport (e.g., certain areas may not have buildings or hydrants; live fuel moisture layer only has cell values in the wildland areas).</p><p>While I have taken various steps to assist the AI model to correctly interpret the map, the model behavior is stochastic and there is no guarantee that the model will always interpret the map correctly.</p><p>For readers who are interested in knowing how I make the AI model “see” the map canvas, I write a tool that adds a one-time event listener on render event, and the event triggers Mapbox’s getCanvas().toBlob method; a repaint is triggered to fire the render event. The image blob is converted to base64 format and pass as the data in function result.</p><p>Building this agent taught me that making AI interact with maps is fundamentally different from typical chatbot tools. Maps are visual, spatial, and stateful — the AI can’t just query a database and return an answer. It has to <em>look</em>, <em>reason</em>, and <em>act</em>, just like a human would.</p><p>If you’re building a map agent, I’d love to hear what challenges you’ve run into. And if you’ve used an enterprise AI map tool — Esri, Google, or otherwise — I’m curious how it compares to what I’ve built here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BPjQctMJ6r-hKjPyRkZeLg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=448ae11e6a1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Want to know the adjacent points on road network and measure spacing? Try AdjFind]]></title>
            <link>https://medium.com/@zifanw9/want-to-know-the-adjacent-points-on-road-network-and-measure-spacing-try-adjfind-e28f63341b2a?source=rss-a2bb36f3f884------2</link>
            <guid isPermaLink="false">https://medium.com/p/e28f63341b2a</guid>
            <category><![CDATA[spacing]]></category>
            <category><![CDATA[adjacencies]]></category>
            <category><![CDATA[neighboring-points]]></category>
            <category><![CDATA[fire-code]]></category>
            <category><![CDATA[transportation-networks]]></category>
            <dc:creator><![CDATA[Zifan W]]></dc:creator>
            <pubDate>Fri, 03 Oct 2025 02:59:41 GMT</pubDate>
            <atom:updated>2025-10-03T02:59:41.974Z</atom:updated>
            <content:encoded><![CDATA[<p>Consider a point dataset that can be mapped in the geographic space. For each point, we may want to know its neighboring points. The classic technique will be <em>k-nearest neighbor query</em> where <em>k</em> is a positive integer number such as 1, 2, or more; the query returns up to the user-defined amount of points that have the smallest Euclidean (straight-line) distances to the given point. Such a technique does not take road network into account, but in the real world travel happens along the road network; points that are deemed as nearest in Euclidean distance often are not true nearest in network distance. To get the <em>k-nearest</em> points in the network distance, one possibility will be computing the<em> distance matrix</em> using the point dataset and the road network, and extract the <em>k+1</em> columns (one extra column that has the same point as origin and destination) with the smallest distance values for each row.</p><p>However, <strong>the neighboring points identified by <em>k-nearest neighbor query</em> or <em>distance matrix</em> really are proximity-based rather than adjacency-based</strong>. The figure below illustrates the difference: the black outline depicts land parcel boundaries, and blue polygons are single-family housing. For building 3, building 2 is to its left, and building 4 is to its right; buildings 2 and 4 are adjacent to building 3. However, building 1 is closer (or have same distance) to building 3 compared with building 4; <em>2-nearest neighbor query</em> likely will return polygon 1 and 2. Therefore, there is a subtle difference between the results of proximity-based techniques and the expectations of a true adjacency-based technique.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6GLpFGzR1N6CnYiRB3ufCg.png" /><figcaption>Figure 1</figcaption></figure><p>While proximity-based techniques are suitable for neighbor-identifications in most applications, adjacency-based techniques are still needed in certain applications. <em>Spatial predicates such as touches or intersects</em> can be used to determine adjacency relationship among polygons. In the figure above, the parcel where building 3 is located touches the parcels corresponding to building 2 and 4. However, for a dataset with non-duplicate points, directly applying spatial predicates will not work because there is always a positive amount of distance between any pair of points. Some GIS analysts might use buffer operation to convert points to polygons and then apply spatial predicates. There are three limitations of buffering the points: (i) it is often challenging to tell the appropriate buffer distance to set for the buffer operation; (ii) the neighboring points identified by buffer becomes coverage-based rather than adjacency-based (i.e., all the points within a distance threshold value will be considered as neighbors); (iii) buffering is an Euclidean-distance based operation that does not consider road network.</p><p>So far, I mention 3 similar and often interchangeable words: proximity, coverage, and adjacency. They can all be used to <strong>answer one question: what are the neighboring points of a given point? </strong>Those 3 words can be differentiated by how the concept of “neighbor” is defined.</p><ol><li>A point is the neighbor of another point if it is <strong>the closest one or few points</strong>. I tend to use <em>proximity</em> (think about k-nearest neighbor query) to reference such applications.</li><li>A point is the neighbor of another point if it is <strong>within a distance threshold from the other point</strong>. I tend to use <em>coverage</em> (think about buffer + intersects) to reference such applications.</li><li>A point is the neighbor of another point if <strong>the shortest path between them is no longer than the shortest path to any other point in that travel direction</strong>. I tend to use <em>adjacency</em> to reference such applications. This concept is closely related to spacing (example will be <a href="https://up.codes/viewer/california/ca-fire-code-2022/chapter/C/fire-hydrant-locations-and-distribution#C103">hydrant spacing</a> regulations), and it is not well-studied until recently by <a href="https://onlinelibrary.wiley.com/doi/10.1111/tgis.13255">Figueroa et al. (2024)</a>.</li></ol><p>In this article, I will take a deep dive into the third application category. While the focus will be point dataset rather than polygon dataset, I want to start with the Figure 1 that I discuss earlier. Assuming building 3 is the source, and we try to find its adjacent neighbors. If going straight to the left, we reach building 2. If continue going left, we can reach building 1 but the shortest path to building 1 is longer than the shortest path to building 2. Therefore, for this particular direction, building 2 is the adjacent neighbor while building 1 is not. There is another direction in which we can explore, which is to the right, and we can reach building 4, an adjacent neighbor in right-ward direction.</p><p><a href="https://onlinelibrary.wiley.com/doi/10.1111/tgis.13255">Figueroa et al. (2024)</a> states the same approach in a more technical way. Imagine that we have computed the shortest paths from a source hydrant point to all other hydrant points in the dataset, “if an edge on a path from hydrant <em>i</em> to hydrant <em>l</em> is closer to a hydrant other than <em>i</em>, the path is discarded, and the candidate neighbor is excluded.” In fact, this article as well as the <a href="https://github.com/zwang-geog/AdjFind">AdjFind </a>neighboring-points mode are stemmed from <a href="https://onlinelibrary.wiley.com/doi/10.1111/tgis.13255">Figueroa et al. (2024)</a>; for any future academic literature that plan to cite the related works, please cite <a href="https://onlinelibrary.wiley.com/doi/10.1111/tgis.13255">Figueroa et al. (2024)</a> accordingly.</p><p>The following figures should illustrate the concept more clearly. Imagine a point that is snapped to the middle of a west-east-oriented road line-string. <strong>There are two possible directions of travel along the road line-string: going left or going right. If going left, as soon as the shortest path to another point is found, the search in the left direction can terminate.</strong> Basically, rather than calculating the paths to all other points and discarding paths to non-adjacent points, revising the path algorithm itself will be an more efficient approach. <strong>Similarly, another run of the specialized path algorithm going right</strong> <strong>will give us the second adjacent neighbor.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*Au1tm6SqhR9DY17uvrMtGQ.png" /><figcaption>Figure 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*orp1rPVAuu4xYXszPFOJcg.png" /><figcaption>Figure 3</figcaption></figure><p><strong>If the point is located very close to the road intersection, its possible travel directions may not be limited to just two since it effectively can be treated as at the intersection</strong> (<a href="https://onlinelibrary.wiley.com/doi/10.1111/tgis.13255">Figueroa et al. (2024)</a>). The following figures illustrate that left-direction can be further split to left-left, left-up, and left-down directions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-5ZmpzFpAMcFzkufeBcPA.png" /><figcaption>Figure 4</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RpG429Op-aIBRH7EfuYFXA.png" /><figcaption>Figure 5</figcaption></figure><p><a href="https://github.com/zwang-geog/AdjFind">AdjFind</a> is a C++ command line application that is capable to identify adjacent point neighbors and the corresponding spacing distances. If the application problem that you try to solve defines the concept of neighbor in the same way as <a href="https://github.com/zwang-geog/AdjFind">AdjFind</a>, you got a readily available tool to use now! If you like this work, please star or fork the GitHub repository.</p><p>If you are interested in knowing more about the capability of AdjFind, feel free to read my <a href="https://medium.com/@zifanw9/still-measuring-proximity-using-point-buffers-try-this-new-tool-2a0e5cb7f5c8">previous article</a>.</p><p>If you want to learn the path algorithm used in the neighboring-points mode of AdjFind, please read the following section.</p><p>The path algorithm assumes a weighted graph constructed in the same manner as the <em>Constructing graph with points snapped</em> section of my <a href="https://medium.com/@zifanw9/still-measuring-proximity-using-point-buffers-try-this-new-tool-2a0e5cb7f5c8">previous article</a>. It is a variant of Dijkstra algorithm with following key differences:</p><ol><li>The termination criteria is: <strong>the current vertex</strong> (the vertex that is just finalized or labeled) <strong>has a vertex type of point</strong> (the graph vertices created from input data’s road intersections will have type intersection, while graph vertices that correspond to the input point dataset will have type point) and <strong>is not the source vertex</strong> (source vertex will always have type point because the overall algorithm loops through each point sourced from the point dataset). This ensures that no further branching as soon as another point vertex is reached.</li><li>An extra vector <em>edges_to_exclude</em> is introduced. In the code block that iterates through each outgoing edges (or connected vertices) of the current vertex, if the outgoing edge is in the <em>edges_to_exclude </em>vector, it will continue to next iteration instead of adding the corresponding connected vertex to the priority queue. Visually, this parameter serves like the forbidden symbols in figure 2 and 4; for example, if I want to find the adjacent neighbor to the left, I will add the edge on the right to the <em>edges_to_exclude</em> vector, so that the path is restricted to go left. I call this strategy as restricted directional search.</li></ol><p>For each point (e.g., hydrant) vertex in the graph, the general flow is like following (the function call refers to the path algorithm described above):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*f9xd2RNg-3dmj3x2TYUBeg.png" /><figcaption>Figure 6</figcaption></figure><p>Note the third decision box (yellow box) addresses the following special situation that has more than one hydrant near the intersection:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/1*5X5BVL2hGnOGoL0hriBUHg.png" /><figcaption>Figure 7</figcaption></figure><p>Hydrant vertex 5 is very close to intersection vertex 4, should it make multiple path algorithm function calls to take upward direction into account? No, because intersection vertex 4 has two hydrant vertices nearby. A single function call that will return a path ended at vertex 6 will be sufficient for the upward direction.</p><p>That is it! Now you know the fundamentals of the algorithms underlying the <a href="https://github.com/zwang-geog/AdjFind">AdjFind</a> neighboring-points mode!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e28f63341b2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Still measuring proximity using point buffers? Try this new tool]]></title>
            <link>https://medium.com/@zifanw9/still-measuring-proximity-using-point-buffers-try-this-new-tool-2a0e5cb7f5c8?source=rss-a2bb36f3f884------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a0e5cb7f5c8</guid>
            <category><![CDATA[gis]]></category>
            <category><![CDATA[proximity]]></category>
            <category><![CDATA[service-area]]></category>
            <category><![CDATA[location-intelligence]]></category>
            <category><![CDATA[transportation-networks]]></category>
            <dc:creator><![CDATA[Zifan W]]></dc:creator>
            <pubDate>Tue, 30 Sep 2025 23:52:47 GMT</pubDate>
            <atom:updated>2025-10-01T00:14:23.419Z</atom:updated>
            <content:encoded><![CDATA[<p>The study of locations is central to geographic information science (GIS): the locations of fire hydrants, shared bike docks, bus stops, just to name a few. One metric to assess whether the locations of something has a “good” spatial distribution is proximity: is the location reasonably close to people who might need it? One example will be fire hydrant, which a building might be required to be within some distance threshold from the nearby hydrant(s). In such an example, fire hydrants can be considered as supply, while buildings or the entire neighborhood can be considered as demand.</p><p>There are two different scales of analysis. One is to measure the distance or travel time between individual demand feature such as buildings (which can have many in an area) and the supply locations (such as hydrants). Examples include distance or travel time matrix calculation (typically measured on road network, but only point-to-point) and nearest-neighbor query (e.g., r-tree query; typically Euclidean or straight-line distance).</p><p>Another scale of analysis is to take an areal-view; demands are assumed to be present continuously through the study area or the road network (in contrast to discrete polygons or points that represent demand locations). The most classic example will be buffer analysis: for each supply location, create a circular polygon with a radius defined by the user, and this analysis really assumes Euclidean or straight-line distance. With such an analysis, people can tell that certain areas are within proximity from certain service facilities (in fact, this is called coverage, emphasizing whether or not demands are within the distance threshold, rather than the actual distance value).</p><p>Buffer is known to have major limitation of not taking network distance into account. There are other examples that take an areal-view while using network distance or travel time: <a href="https://docs.mapbox.com/api/navigation/isochrone/">isochrone tool</a> or <a href="https://pro.arcgis.com/en/pro-app/latest/help/analysis/networks/service-area-analysis-layer.htm">service area analysis tool</a>. Any area within a polygon derived by those tools will have a network travel distance or time that is less than or equal to the user-specified threshold. People can overlay those polygons with the road dataset to tell which portion of the road network are within service standard. However, imagine a road line-string that falls within two different polygons corresponding to different supply locations; a portion of the road line-string might be closer to one supply location and the remaining portion of the road line-string might be closer to the other supply location, but <strong>a simple isochrone tool or service area analysis tool cannot tell the “closest”</strong> (it only answers a if question). Similarly, if a road line-string is outside of the service area polygon (distance greater than the threshold), it does not tell which supply or service location is closest to that line-string.</p><p>I am pleased to share that a command line tool <a href="https://github.com/zwang-geog/AdjFind">AdjFind</a> is now available. It is not a replacement to ArcGIS service area analysis tool, but it can be an alternative.</p><p>Consider following illustrative figure, there are two point features representing supply (e.g., hydrant locations). Some of the road line-strings are colored in red, and they are the portion of the network that is closest to point 1. The remaining road line-strings are colored in blue, meaning they are closest to point 2. This is a visualization of AdjFind road-segmentation mode’s result: a road line-string will be assigned to its closest service point (a.k.a. supply point), and the distance between each of its endpoint to the closest service point will be recorded in the attribute table (not shown here). If a road line-string has a portion closest to point 1 while the other portion closest to point 2, an equilibrium point (distance to either point is equal) along the line-string will be identified, and the original line-string will be split into two new line-strings; <strong>any point on the final output line-string is guaranteed to be closest to its assigned service point</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*SWygpxsanWCo1k7mJ1EI-g.png" /></figure><p>If we not only want to know the closest service point for each road line-string, but also want to know which portion of the network has a distance bracket/category 100–200 etc, it is also possible via road-segmentation mode with distance-breakpoints parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*6DM6UNL3FPDApLg-OfosEQ.png" /></figure><p>In the above illustrative figure, I set distance-breakpoints parameter to 100,200,300, which implies 4 distance brackets: 0–100 (green), 100–200 (yellow), 200–300 (red), and ≥300 (purple). The algorithm performs further splitting on road line-strings in addition to the previous example; that is, if a road line-string has a point with distance to closest supply location the same as any of the breakpoint values, it will be split to two new line-strings at that breakpoint distance. <strong>Any point on the final output line-string except the endpoint is guaranteed to belong to one and only one distinct distance bracket</strong>.</p><p>What advantages does this road segmentation tool offer then?</p><ul><li>Demand may distribute continuously along the road line-strings, and this tool performs segmentations on road line-strings instead of requiring user to create discrete demand points for network-based analysis</li><li>Euclidean distance fails to take road network into account and thus can be inaccurate, and this tool is network-distance based</li><li>Traditional isochrone or service area analysis only tells coverage (an if question) but not true proximity (distance value), but this tool can tell the access distances to the line-string endpoints as well as line-string-level distance bracket</li><li>Isochrone or service area analysis can generate concentric service areas (multiple breakpoints). This tool also gives user control with possibility of specifying multiple distance breakpoints. Additionally, the ability of this tool to tell the closest supply/service point is not restricted by any threshold or cutoff value.</li></ul><p>In this article, I will also detail how <a href="https://github.com/zwang-geog/AdjFind">AdjFind</a> road segmentation algorithm works.</p><p><strong>Constructing graph with points snapped</strong></p><p>The first step is to read the input road line-string dataset. A line-string consists of two or more points, and it may consist of one or more consecutive segments; a segment is just a pair of points. This distinction is important. Each record in the input dataset is expected to be a line-string, but boost geometry only supports r-tree creation for segment but not line-string. Therefore, I initialize an vector for storing road line-strings, and the road r-tree is created such that each segment has corresponding line-string vector position index as well as the segment index for that particular line-string.</p><p>The second step is to read the input point dataset and “snap” each point to closest road line-string. This involves querying the road r-tree to obtain the (Euclidean-distance) closest road line-string, the segment index, and the closest point on the segment by projecting the point to the segment. The snapping information is stored as an unordered map, with road line-string index as key and a vector of the snapped point information as value; this setup addresses the possibility that multiple points are snapped to the same road line-string feature.</p><p>The third step is to create the graph. A graph consists of a set of vertices as well as edges connecting vertices. I use a point r-tree to store graph vertices, and a new vertex will be created if it is not within a distance tolerance threshold (assumed to be 0.01) from any existing vertex. Multiple edges with the same from vertex and to vertex can exist in the graph. To start the graph construction, I loop through the unordered map containing the snapping information. Within the loop, the road line-string will be marked as deleted (i.e., soft delete) since at least one point is snapped to it and its geometry will be replaced by new line-strings. The vector of snapped points will be sorted by segment index first, and the distance between the start of the segment and the snapped point second. Then I have an inner loop to iterate through the sorted snapped points to construct new line-strings with the snapped points taking into account; the new line-strings will be added as edges to the graph (when an edge is created, the corresponding vertices will either be from existing vertices or creating new ones). After looping through the unordered map, all the road line-strings that are not marked as deleted will be added as edges to the graph.</p><p><strong>Populating closest point vertex for all intersection vertex</strong></p><p>When constructing the graph, there are two types of vertices: one is intersection vertex (the input line-strings’ start and end points) and one is point vertex (the locations along the road line-strings where the supply points are snapped to). For any point vertex, its closest supply point is itself.</p><p>For all the intersection vertex though, a shortest path algorithm is needed to determine their closest point vertices. The shortest path algorithm used here is a variant of single-source Dijkstra algorithm. The source will the one of the intersection vertex. There is no fixed target; as soon as a point vertex is finalized/labeled, the path algorithm can stop searching. That finalized point vertex will correspond to the supply point that is closest to the source intersection vertex. In fact, any intermediate vertex traversed in the shortest path will have this same point vertex as its closest point vertex. In other words, after the shortest path is constructed, we can update all the traversed intersection vertices along the path (if the vertex is not updated yet) instead of just the source vertex; there is no need to run the path algorithm for every intersection vertex (but its closest point vertex is still determined by the path algorithm when using another intersection vertex as source).</p><p><strong>Splitting a line-string at equilibrium point</strong></p><p>After the previous steps, the closest point vertex as well as the corresponding distance are known for all vertices in the graph. If both vertices of an edge have the same closest point vertex, there is no need to split that edge. Otherwise, a portion of the edge is closest to one point vertex, while the other portion of the same edge is closest to another point vertex; a splitting step is necessary to ensure the output line-string (whose geometry sourced from the edge) uniquely closest to one point vertex.</p><p>The point on the edge where the split should occur should have the same network distance value to (i) edge’s from-vertex closest point, (ii) edge’s to-vertex closest point. We can setup a simple equation like following, where <em>distance from the from-vertex</em> is the unknown to solve:</p><p><em>from-vertex distance to closest point + distance from the from-vertex = to-vertex distance to closest point + (edge length - distance from the from-vertex)</em></p><p>The unknown can then be expressed with known variables:</p><p><em>distance from the from-vertex = 0.5 * (to-vertex distance to closest point - from-vertex distance to closest point + edge length)</em></p><p>With the distance measured from the edge’s from-vertex calculated by the above formula, it is possible to use boost geometry’s line_interpolate method to get the split point. The original edge entry will be updated with one of the new split edge, and a new edge entry will also be added to the edges vector.</p><p><strong>Optionally splitting a line-string with distance breakpoints</strong></p><p>The step described here is optional and only applies if distance-breakpoints parameter is set. If the parameter is not set (default), the edges from above step will be extracted and written as the output line-string dataset.</p><p>An edge has two vertices, and one of the vertices should be closer to the point vertex than the other vertex; this vertex that is closer to the point vertex, along with whether it is edge’s from-vertex or to-vertex, is stored as an attribute of the edge. The distance from the closest point vertex to this vertex is referred as <em>distance_to_point_vertex</em> here for simplicity.</p><p>In this step, there is an outer loop that iterates through each edge in the graph, and there is an inner loop that iterates through each element in the distance breakpoints vector. If the value obtained by <em>subtracting a distance breakpoint value with the distance_to_point_vertex</em> is non-negative and is smaller than edge length, it is necessary to interpolate along the edge with this value as the interpolation distance. The interpolated points will be used to construct output line-strings so that each output line-string can belong to one and only one distance bracket.</p><p><a href="https://github.com/zwang-geog/AdjFind">AdjFind</a> is a C++ CLI program that you can install via homebrew tap (unfortunately the repo does not meet the popularity requirement of homebrew-core). If you like it, please star or fork the repo. Please also feel free to comment on this article with any question you have related to the algorithm, any bug reporting on GitHub Issues is very welcomed as well.</p><p>I am actively working on making it available via conda-forge; hopefully my PR gets approved.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a0e5cb7f5c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A low-cost custom wind particle motion layer in mapbox-gl-js]]></title>
            <link>https://medium.com/@zifanw9/a-low-cost-custom-wind-particle-motion-layer-in-mapbox-gl-js-9a51978e3ffb?source=rss-a2bb36f3f884------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a51978e3ffb</guid>
            <category><![CDATA[wind]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[webgl]]></category>
            <category><![CDATA[mapping]]></category>
            <category><![CDATA[animation]]></category>
            <dc:creator><![CDATA[Zifan W]]></dc:creator>
            <pubDate>Sun, 03 Aug 2025 01:54:51 GMT</pubDate>
            <atom:updated>2025-08-03T16:56:32.071Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FHLu0Ylhu5x4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHLu0Ylhu5x4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FHLu0Ylhu5x4%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/440819d0a7992d3cb7d0a20c250196dc/href">https://medium.com/media/440819d0a7992d3cb7d0a20c250196dc/href</a></iframe><p>There are existing products of web-based wind visualization, notably <a href="https://earth.nullschool.net/">earth.nullschool.net</a> and <a href="https://www.windy.com/">Windy</a>. For developers who work on making web maps, Mapbox offers raster-array source and <a href="https://docs.mapbox.com/style-spec/reference/layers/#raster-particle">raster-particle</a> style layer that jointly can produce reliable and high-quality particle animation for <a href="https://docs.mapbox.com/mapbox-tiling-service/examples/raster-mts-wind/">wind</a>. Additionally, <a href="https://www.xweather.com/docs/mapsgl/examples/custom-wind-particles">Xweather MapsGL</a> offers the option of adding style-customizable wind particles layer (and many other weather layers) to a mapbox map, and developers do not need to worry about <a href="https://www.xweather.com/docs/mapsgl/getting-started/weather-data">data source</a> issue. Xweather is <a href="https://signup.xweather.com/">subscription-based</a> and also bills on extra usage.</p><p>For my own work though, I need to be able to accommodate custom wind data sources and overlay the wind layer with Mapbox-hosted vector tilesets, so Mapbox’s raster-particle layer is my first choice. Most of my map’s layers have an extent of a US county and need to zoom in to block level to visualize building and road (zoom level at least 12 and preferably 16). However, raster-array source generates tiles for each zoom level within the user defined range, and a zoom level above 10 (even after clippping of dataset extent) can take extremely long time to process (my process job even crashes after a few hours without finishing), consume a lot of compute units, and entail a significant cost. If I only generate tileset up to zoom level 10, the particle looks really coarse (like a blurry box with tails that slowly moves over my other vector layers) when zoom in. Therefore, I cannot afford Mapbox’s built-in raster-particle layer, given my limited budget and data characteristics (display particles at high zoom level, and input raster cell size preferably is small like 5-km instead of 1 degree).</p><p>I turn my attention to open-source solutions such as <a href="https://github.com/onaci/leaflet-velocity">leaflet-velocity</a> and <a href="https://blog.sakitam.com/wind-layer/api/mapbox-wind/">mapbox-wind</a>, and eventually I decide to implement my own wind particle motion layer based on some key ideas that mention in those works.</p><p>My implementation requires storing wind data in JPEG format somewhere that can be downloaded from Internet (e.g., <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/HostingWebsiteOnS3Setup.html#step3-edit-block-public-access">public</a> AWS S3 bucket with proper <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/enabling-cors-examples.html">CORS</a> policy, or as public assets of a static website). If the data needs to be updated daily, the data pipeline can be set up using cloud <a href="https://render.com/docs/cronjobs">cron job</a> service or on a cloud virtual machine.</p><p>I publish my work as a <a href="https://www.npmjs.com/package/mapbox-exif-layer">npm package</a>, and also share my <a href="https://github.com/zwang-geog/mapbox-exif-layer">source code</a>, which has a pipeline folder with necessary scripts to prepare data, as well as a react-demo folder that you can run on your machine.</p><p>In this article, I will give an overview of key ideas of my implementation.</p><h4><strong>1. Displacement in layer extent</strong></h4><p>Particle motion layer can be understood as a layer with points whose positions on the map change over time, instead of stationary like traditional vector layer. A change in position means displacement that has a horizontal component (u-component, or along x-axis) and a vertical component (v-component, or along y-axis).</p><p>The typical wind datasets such as GFS have bands with u-component velocity in m/s and v-component velocity in m/s. <a href="https://blog.mapbox.com/how-i-built-a-wind-map-with-webgl-b63022b5537f">Vladimir Agafonkin</a> proposes to use JPEG image’s R and G bands to store the normalized u- and v-component velocities (normalize means to scale velocities values to range between 0 and 255). Normalization requires minimum and maximum cell values for u- and v-components, <a href="https://github.com/sakitam-fdd/wind-layer/tree/master/packages/mapbox-gl">mapbox-wind</a> proposes to store min/max values as an extra attribute of JPEG image — EXIF, so that all we need is just a single image file.</p><p>When the JPEG image is passed to the layer render program, it is stored as a WebGL texture, and now the r and g bands become in 0–1 range when retrieving value (a “built-in” normalization from 0–255 to 0–1). The shader program can access this velocity texture via <em>u_velocity_texture.</em></p><p>The minimum and maximum cell values of u-component velocity is stored as a 2-element vector of signed floating point numbers in WebGL and denoted as <em>u_value_range_u</em>. Similar, the min and max of v-component is denoted as <em>u_value_range_v</em>.</p><p>In geospatial world, a dataset always has an extent ([minX, maxY, maxX, minY] assumed to be in degrees), and a JPEG file does not store such information. This information needs to be passed as a bounds parameter when adding the layer. The 4 values are stored as a 4-element vector of signed floating point numbers in WebGL, and it is denoted as <em>u_bounds</em>.</p><p>I use bounds to normalize point positions so their x- and y-coordinates have a range of [0,1], and I store the normalized point positions as WebGL buffer.</p><p>With the above mentioned information, we can compute displacement as well as the new point (i.e., particle) position.</p><p>(1) For a point’s current position (denoted as <em>a_position</em>), we need to look up the cell/pixel value that it is located on by sampling the velocity texture.</p><pre>vec4 velocity = texture(u_velocity_texture, a_position);</pre><p>(2) We need to scale the velocities with normalized range 0–1 back to their original range.</p><pre>float u = mix(u_value_range_u[0], u_value_range_u[1], velocity.r);<br>float v = mix(u_value_range_v[0], u_value_range_v[1], velocity.g);</pre><p>(3) The next step is to convert the denormalized velocity unit (assumed to be mph in shader program) to degrees per hour (for consistence with layer extent unit). Note that texture stores values from top to bottom, while point position assumes y-axis increasing from bottom to top; this is a critical detail when converting point position to actual latitude (latitude is need to convert to degrees because the length of a degree of longitude is a function of latitude).</p><pre>float lat = mix(u_bounds[3], u_bounds[1], 1.0 - a_position.y);<br>vec2 degrees = mphToDegreesPerFrame(vec2(u, v), lat);</pre><p>(4) New point positions (in the next hour) is computed by current position plus displacement amount. The point positions are in [0, 1] range, so normalization of degrees to [0,1] range is required to reflect the extent of the layer and used to determine the new position. Animation effect is achieved by mapping point positions from one frame to next frame, typically there are around 60 frames per second. A common practice is to scale the velocity vector with a small fraction number (per hour now becomes per frame) before adding it to the current position; this way will take frame rate into account.</p><pre>vec2 normalizedVelocity = vec2(<br> degrees.x / (u_bounds[2] - u_bounds[0]),<br> degrees.y / (u_bounds[1] - u_bounds[3])<br>);<br>vec2 newPos = a_position + normalizedVelocity * u_speed_factor;</pre><p><strong>2. Position reset mechanism</strong></p><p>After initial new position of a point is computed, we may need to reset this initial position. The reasons for resetting positions can be exceeding layer boundary or preventing degeneration.</p><p>Exceeding layer boundary refers to the point’s new position exceeds [0,1] range that defines the bounds.</p><p>The concept of degeneration is mentioned in some other works on mapping wind particles. Ideally, particles should be distributed across the entire layer extent; in other words, in a sub-area, you should always see some particles present there (even if the particle count is small compared with some other areas). Over time, particles might be all trapped in specific areas, and most other parts of the extent have little to no particles at all; this phenomenon is degeneration.</p><p>There are two main causes of degeneration: circular air flow and extreme low wind speed. Circular air flow mainly is caused by Coriolis effect (Earth’s rotation); visually, particles form a circular pattern, no particle can move out from it while only new particles can move in to it. Examples of circular air flow include hurricanes, typhoons, or low-pressure systems (where you might expect precipitation) in general. Low wind speed means that particles will stuck at a region almost like stationary; examples may include the center of high pressure systems or possibly center of some low pressure systems as well.</p><p>Exceeding layer boundary and low wind speed (my shader program assumes below 1.5 mph as low) are easy to handle:</p><pre>float windSpeed = length(vec2(u, v));<br>if (newPos.x &lt; 0.0 || newPos.x &gt; 1.0 || newPos.y &lt; 0.0 || newPos.y &gt; 1.0 || windSpeed &lt; 1.5) {<br>    shouldReset = true;<br>}</pre><p>To handle degeneration due to circular air flow, I use WebGL buffer to store particle age. Each particle’s age is initialized with a random number between 0 and 100 so that a large number of particles would not be updated at the same time.</p><p>There are two parameters related to <em>ageThreshold</em> (denoted as <em>u_age_threshold</em> in shader program) and <em>maxAge</em> (denoted as <em>u_max_age</em> in shader program). The more particle age exceeds <em>ageThreshold</em>, the more likely for it to be reset. Eventually if particle age exceeds <em>maxAge</em>, it must be reset.</p><pre>float age = a_age + 1.0;<br><br>if (age &gt; u_age_threshold) {<br>    float resetProbability = (age - u_age_threshold) / (u_max_age - u_age_threshold);<br>    if (random(a_position + vec2(u_time * 0.1, age * 0.01)) &lt; resetProbability) {<br>        shouldReset = true;<br>    }<br>}<br><br>if (age &gt; u_max_age) {<br>    shouldReset = true;<br>}</pre><p>There is a <em>setSource</em> method that provides an optional parameter <em>percentParticleWhenSetSource</em> which default to 0.5. This parameter gives an extra opportunity to reset particles positions when the source url (e.g., wind pattern at a different timestamp) is updated, so a new wind particle distribution pattern can be emerged more quickly.</p><p>Lastly, the initial version of the package generates random coordinates in the range [0,1] when <em>shouldReset</em> is true. I do code a <em>generateBoundaryPosition</em> function in the source code, but it is not used since particles might easily go out of bounds in certain wind pattern setups.</p><p><strong>3. Making particle position update GPU-based</strong></p><p>Whether it is mapbox-gl-js library or WebGL code, it relies on GPU for various computation. To maximize the computational speed to allow a smooth user experience, the data transfers between GPU and CPU should be minimized. Therefore, my implementation relies on transform feedback to make particle position update fully GPU-based.</p><p>The WebGL code snippet that I provided in previous two sections are inside a dedicated vertex shader for position update (there is another vertex shader for actual mapping). This position update vertex shader takes current position and age buffers as inputs, and outputs updated position and age buffers. Transform feedback setup is needed to capture the vertex shader outputs and use them as inputs for the next frame.</p><p>First, two sets of buffers for positions and two sets of buffers for ages are needed (those code are inside <em>onAdd</em> method of Mapbox custom layer).</p><pre>this.particleBufferA = createBuffer(gl, positions);<br>this.particleBufferB = createBuffer(gl, positions);<br>this.currentBuffer = this.particleBufferA;<br>this.nextBuffer = this.particleBufferB;<br><br>this.ageBufferA = createBuffer(gl, ages);<br>this.ageBufferB = createBuffer(gl, ages);<br>this.currentAgeBuffer = this.ageBufferA;<br>this.nextAgeBuffer = this.ageBufferB;</pre><p>Next, transform feedback object needs to be created.</p><pre>this.transformFeedback = gl.createTransformFeedback();</pre><p>In Mapbox custom layer <em>render</em> method, output buffers need to be bind to the transform feedback.</p><pre>gl.useProgram(this.updateProgram.program);<br><br>gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, this.transformFeedback);<br>gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, this.nextBuffer);<br>gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 1, this.nextAgeBuffer);</pre><p>It is different from how input buffers are bind:</p><pre>gl.bindBuffer(gl.ARRAY_BUFFER, this.currentBuffer);<br>gl.enableVertexAttribArray(this.updateProgram.a_position);<br>gl.vertexAttribPointer(this.updateProgram.a_position, 2, gl.FLOAT, false, 0, 0);<br><br>gl.bindBuffer(gl.ARRAY_BUFFER, this.currentAgeBuffer);<br>gl.enableVertexAttribArray(this.updateProgram.a_age);<br>gl.vertexAttribPointer(this.updateProgram.a_age, 1, gl.FLOAT, false, 0, 0);</pre><p>Now, it is possible to begin transform feedback, run update position vertex shader, and do any necessary cleanup</p><pre>gl.beginTransformFeedback(gl.POINTS);<br><br>gl.drawArrays(gl.POINTS, 0, this.particleCount);<br><br>gl.endTransformFeedback();<br><br>gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, null);<br>gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, null);<br>gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 1, null);</pre><p>Lastly, because each frame’s output becomes next frame’s input, buffers need to be swapped:</p><pre>[this.currentBuffer, this.nextBuffer] = [this.nextBuffer, this.currentBuffer];<br>[this.currentAgeBuffer, this.nextAgeBuffer] = [this.nextAgeBuffer, this.currentAgeBuffer];</pre><p>Also note that here <em>updateProgram</em> is used. A WebGL program consists of a vertex shader and a fragment shader. The vertex shader of <em>updateProgram</em> is already discussed in the previous sections. The fragment shader in <em>updateProgram</em> does not need to output anything visual because we are just trying to capture new positions and ages; it serves as a placeholder here.</p><p><strong>4. Mapping the positions of particles</strong></p><p>So far I focus on introducing the <em>updateProgram</em> and especially its vertex shader. Now I will introduce rendering step, in which <em>renderProgram</em> is used. The vertex shader of <em>renderProgram</em> is responsible for mapping the new positions of particles.</p><p>The particle position buffer assumes a range [0, 1] relative to the layer extent, so it is necessary to convert it to actual longitude/latitude for further processing so it can eventually overlay with other Mapbox layers.</p><pre>float lng = mix(u_bounds[0], u_bounds[2], currentPos.x);<br>float lat = mix(u_bounds[3], u_bounds[1], 1.0 - currentPos.y);</pre><p>Mapbox has a matrix transformation that takes a web mercator [0, 1] normalized coordinate pair and outputs position used for WebGL rendering (see its <a href="https://docs.mapbox.com/mapbox-gl-js/example/custom-style-layer/">example</a>). This will be the “further processing” that is needed.</p><pre>vec2 mercator = latLngToMercator(vec2(lng, lat));<br>gl_Position = u_matrix * vec4(mercator, 0, 1);</pre><p><strong>5. Coloring the particles</strong></p><p>The fragment shader of <em>renderProgram</em> is responsible for assigning colors to the particles.</p><p>In fact, as a pre-requisite, a colormap needs to be created and stored as a WebGL texture. This involves using the user input parameter <em>color</em> which is an array like <em>[ [Wind speed in mph, [R, G, B]] …] </em>and <em>min-speed,max-speed </em>(denoted as<em> u_speed_range </em>in shader program) stored in EXIF string.</p><p>The colormap is created by first sorting the color array by wind speed. Then it creates 256 discrete stops within the range bounded by <em>min-speed</em> and <em>max-speed</em>. For each stop (a speed value), it identifies its corresponding interval in the color array (e.g., between wind speed 10 mph and 12 mph), and performs an interpolation on R, G, B values (e.g., stop wind speed is 11 mph, 10 mph has RGB values [0, 0, 0], 12 mph has RGB values [100, 100, 100], the interpolated RGB values for this stop will be [50, 50, 50]).</p><p>In the fragment shader, the normalized u- and v-component velocity needs to be retrieved from the velocity texture, and it needs to be scaled to original min/max range. A speed value then can be calculated.</p><pre>vec4 velocity = texture(u_velocity_texture, v_position);<br>float u = mix(u_value_range_u[0], u_value_range_u[1], velocity.r);<br>float v = mix(u_value_range_v[0], u_value_range_v[1], velocity.g);<br>float speed = length(vec2(u, v));</pre><p>Next we need to sample the speed value in color texture. Sampling value from texture will require a normalized value between 0 and 1. Therefore, we need to normalize the speed to [0, 1] range by taking <em>min-speed</em> and <em>max-speed</em> that we use to construct the colormap into account.</p><pre>float normalizedSpeed = (speed - u_speed_range[0]) / (u_speed_range[1] - u_speed_range[0]);<br>vec4 color = texture(u_wind_color, vec2(normalizedSpeed, 0.5));</pre><p>This is the general idea of how coloring of particles work. There are some additional processing in the fragment shader, such as making points’ shape from square to circular, or adding global opacity value; I will omit those details here.</p><p><strong>6. Adding trail offset (a.k.a., tails)</strong></p><p>To draw the main particle and its trail, I create buffer like following:</p><pre>const trailOffsets = new Float32Array(this.trailLength + 1);<br>for (let i = 0; i &lt;= this.trailLength; i++) {<br>    trailOffsets[i] = i; // 0 = main particle, 1,2,3... = trail segments<br>}<br>this.trailOffsetBuffer = createBuffer(gl, trailOffsets);</pre><p>In the <em>render </em>method of Mapbox custom layer, each main particle will be drawn (trailLength+1) times with different offsets.</p><pre>gl.drawArraysInstanced(gl.POINTS, 0, this.particleCount, this.trailLength + 1);</pre><p>In the vertex shader of the <em>renderProgram</em>, besides the updated particle position as input, the trail offset (0, 1, 2, etc.) is also an input. If trail offset is non-zero (i.e., other than the main particle), the trail position will be computed by moving backwards from main particle along its velocity path.</p><pre>if (trailOffset &gt; 0.0) {<br>    currentPos = mainPos - velocity * u_speed_factor * trailOffset * 1.5;<br>}</pre><p>The vertex shader also controls the size of the point. As the trail position increases, the size of the point decreases.</p><pre>float size = trailOffset == 0.0 ? u_point_size : u_point_size * pow(u_trail_size_decay, trailOffset);<br>gl_PointSize = size;</pre><p>That is it! I give a technical walk-through of how I implement mapbox-exif-layer package for wind visualization. The package can also add what I call smooth-raster layers that can be used to display various weather layers such as temperature.</p><p>I hope you learn something from it or or find it to be useful. Any community involvements in further refining this package will be much appreciated!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a51978e3ffb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>