<?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"><channel><title><![CDATA[AndrewC - Azure Tinkering]]></title><description><![CDATA[AndrewC - Azure Tinkering]]></description><link>https://blog.circumblue.com</link><generator>RSS for Node</generator><lastBuildDate>Sat, 07 Nov 2026 13:24:49 GMT</lastBuildDate><atom:link href="https://blog.circumblue.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Live location ingestion and mapping]]></title><description><![CDATA[Using Azure IOT Hub & Service Bus]]></description><link>https://blog.circumblue.com/live-location-ingestion-and-mapping</link><guid isPermaLink="true">https://blog.circumblue.com/live-location-ingestion-and-mapping</guid><category><![CDATA[Azure]]></category><category><![CDATA[Azure Maps]]></category><category><![CDATA[Bing Maps]]></category><category><![CDATA[maps]]></category><category><![CDATA[maps in javaScript]]></category><dc:creator><![CDATA[AndrewC]]></dc:creator><pubDate>Fri, 06 Oct 2023 00:06:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1696550645329/fa01b463-d5db-45ce-b987-4020efca7fd3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the first article in this series (<a target="_blank" href="https://blog.circumblue.com/building-map-based-apps-the-camino">Building map based apps - The Camino</a>), the data being sent to Azure was a jpeg image that happened to have geospatial information attached. For that use case it worked well, but it was not designed for high-volume or low-latency scenarios.</p>
<p>So let's change it a bit and make a real-time tracking/mapping solution. The basic architecture is shown here.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696546427564/075ba690-1ecf-45e3-91b6-f7885798ffb7.png" alt class="image--center mx-auto" /></p>
<p>The only real difference between this approach and the photo capture solution is replacing the blob storage account with an IOT Hub and Service Bus.</p>
<p>The mobile client is using this package <a target="_blank" href="https://github.com/gktval/Maui-GeolocatorPlugin">Maui-GeolocatorPlugin</a> (James Montemagno/Travis Yeik) to subscribe to location changes on the device.</p>
<p>When a location change is detected, a few lines of code send the metadata to Azure IOT Hub :</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">SendIOTMessage2</span>(<span class="hljs-params">DateTimeOffset dt,<span class="hljs-keyword">double</span> longitude,<span class="hljs-keyword">double</span> latitude, <span class="hljs-keyword">double</span> altitude</span>)</span>
{
   DeviceClient client = DeviceClient.CreateFromConnectionString(ConnString, TransportType.Http1);

   String dataBuffer = <span class="hljs-keyword">string</span>.Format(<span class="hljs-string">"{{\"Longitude\":\"{0}\",\"Latitude\":\"{1}\",\"Altitude\":\"{2}\",\"Timestamp\":\"{3}\"}}"</span>, longitude,latitude,altitude,dt);

   <span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> msg = <span class="hljs-keyword">new</span> Message(Encoding.UTF8.GetBytes(dataBuffer));
   <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">await</span> client.SendEventAsync(msg).ConfigureAwait(<span class="hljs-literal">false</span>);
   }
   <span class="hljs-keyword">catch</span> (Exception ex) {
      txtLongitude.Text = <span class="hljs-string">"Error in IOT"</span>;
      <span class="hljs-comment">//deal with this.</span>
   }
}
</code></pre>
<p>In this case as I'm using an IOT Hub, so each device needs to be enrolled and will have a connection string similar to :</p>
<p><em>"HostName=myiothubname.azure-devices.net; DeviceId=device1;SharedAccessKey=XXX34jh5g3j4hg5j3h4g5j3hg43jhgXXX="</em></p>
<p>An IOT Hub provides two way messaging and a host of other features, but a simple Event Hub <em>could</em> be used if these are not needed or device enrollment is overkill.</p>
<p>The IOT Hub is using simple message routing to drop each update into a Service Bus queue :</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696549119443/9b8185bf-63bb-47ad-9bf0-afd2acf52387.png" alt class="image--center mx-auto" /></p>
<p>From there, an Azure Function is triggered that adds a record to the SQL table :</p>
<pre><code class="lang-csharp"><span class="hljs-meta">#r "Newtonsoft.Json"</span>
<span class="hljs-keyword">using</span> System;
<span class="hljs-keyword">using</span> System.Threading.Tasks;
<span class="hljs-keyword">using</span> Newtonsoft.Json;
<span class="hljs-keyword">using</span> Microsoft.Data.SqlClient;

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Run</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> myQueueItem, ILogger log</span>)</span>
{

    <span class="hljs-keyword">dynamic</span> json = JsonConvert.DeserializeObject(myQueueItem);
    <span class="hljs-keyword">string</span> altitude = json[<span class="hljs-string">"Altitude"</span>];
    <span class="hljs-keyword">string</span> longitude = json[<span class="hljs-string">"Longitude"</span>];
    <span class="hljs-keyword">string</span> latitude = json[<span class="hljs-string">"Latitude"</span>];
    DateTime ts = json[<span class="hljs-string">"Timestamp"</span>];
    <span class="hljs-keyword">string</span> format = <span class="hljs-string">"yyyy-MM-dd HH:mm:ss"</span>;

    <span class="hljs-comment">//Important - add data validation and error handling</span>

    SqlConnection sqlConnection1 = <span class="hljs-keyword">new</span> SqlConnection(Connstring);
    SqlCommand cmd = <span class="hljs-keyword">new</span> SqlCommand();
    log.LogInformation(ts.ToString(format));
    cmd.CommandText = <span class="hljs-string">"insert into locations (latitude,longitude,altitude,ts) VALUES ("</span> + latitude + <span class="hljs-string">","</span> + longitude + <span class="hljs-string">","</span> + altitude + <span class="hljs-string">",'"</span> + ts.ToString(format) + <span class="hljs-string">"')"</span>;

    cmd.Connection = sqlConnection1;

    sqlConnection1.Open();
    cmd.ExecuteNonQuery();
    sqlConnection1.Close();
    <span class="hljs-keyword">return</span>;
}
</code></pre>
<p>The rest of the solution is essentially unchanged from <a target="_blank" href="https://blog.circumblue.com/building-map-based-apps-the-camino">Building map based apps - The Camino</a>.</p>
<p>A second function listens on a HTTP endpoint and can return a date range or the last X data points. The results are returned as JSON, ready to be mapped :</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696549685028/fc2a8bad-c598-41e0-95df-ccf068336f93.png" alt class="image--center mx-auto" /></p>
<p>The client side HTML &amp; JS is largely unchanged:</p>
<pre><code class="lang-javascript"> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">GetLocationsTrack</span>(<span class="hljs-params"></span>) </span>{
     <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">reqListener</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">var</span> myObj = <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-built_in">this</span>.responseText);
           DrawTrack(myObj);
           SetView(myObj);
        }

      <span class="hljs-keyword">var</span> oReq = <span class="hljs-keyword">new</span> XMLHttpRequest();
      oReq.addEventListener(<span class="hljs-string">"load"</span>, reqListener);
      url = <span class="hljs-string">"https://myfunctionurl.azurewebsites.net/api/GetLocations?code=ReplaceWithYourCode==&amp;count=450"</span>;
      oReq.open(<span class="hljs-string">"GET"</span>, url);
      oReq.send();
}
</code></pre>
<p>The net result of this is a relatively precise location track looking something like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696550350378/f2a30056-d10f-48b2-bbb3-27a098876536.png" alt class="image--center mx-auto" /></p>
<p>Typically less than 1 second for a message to flow through the pipeline and be visible on a refreshed map.</p>
<p>As always, please note: <a target="_blank" href="https://blog.circumblue.com/general-coding-disclaimer">General disclaimer and notes on coding style, structure and security.</a></p>
]]></content:encoded></item><item><title><![CDATA[Building Map Based Apps - The Camino Part 3]]></title><description><![CDATA[Bringing it together as a map Continuing on from Building Map Based Apps - The Camino Part 2 (circumblue.com) At this point we have : Photos stored on an…]]></description><link>https://blog.circumblue.com/building-map-based-apps-the-camino-part-3</link><guid isPermaLink="true">https://blog.circumblue.com/building-map-based-apps-the-camino-part-3</guid><category><![CDATA[Azure]]></category><category><![CDATA[Azure Maps]]></category><category><![CDATA[Bing Maps]]></category><category><![CDATA[maps]]></category><dc:creator><![CDATA[AndrewC]]></dc:creator><pubDate>Sun, 01 Oct 2023 21:44:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1696190377842/6b02d9e4-8811-46fd-a221-115f9c855d82.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Bringing it together as a map</p>
<p>Continuing on from <a target="_blank" href="https://blog.circumblue.com/building-map-based-apps-the-camino-part-2">Building Map Based Apps - The Camino Part 2 (</a><a target="_blank" href="http://circumblue.com">circumblue.com</a><a target="_blank" href="https://blog.circumblue.com/building-map-based-apps-the-camino-part-2">)</a></p>
<p>At this point we have :</p>
<ul>
<li><p>Photos stored on an Azure Blob storage account as JPEGs</p>
</li>
<li><p>A unique SQL record for each photo with longitude, latitude, date and the filename.</p>
</li>
</ul>
<p>That's all we need to start on the front end.</p>
<h3 id="heading-querying-the-metadata-another-azure-function">Querying the metadata - Another Azure function</h3>
<p>We need a method for a user (or more specifically their browser) to get a list of the unique locations. Directly querying SQL from a browser is not a good plan, so let's proxy that with an Azure function.</p>
<p>This is the main body of the function with the HTTP trigger. Note this also provides the ability to pass a date range to restrict the time period of the photos shown.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">GetAllImages</span>
{
    [<span class="hljs-meta">FunctionName(<span class="hljs-meta-string">"GetAllImages"</span>)</span>]
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">async</span> Task&lt;IActionResult&gt; <span class="hljs-title">Run</span>(<span class="hljs-params">
        [HttpTrigger(AuthorizationLevel.Function, <span class="hljs-string">"get"</span>, <span class="hljs-string">"post"</span>, Route = <span class="hljs-literal">null</span></span>)] HttpRequest req,
        ILogger log)</span>
    {
        <span class="hljs-keyword">string</span> datelower = req.Query[<span class="hljs-string">"datelower"</span>];
        <span class="hljs-keyword">string</span> dateupper = req.Query[<span class="hljs-string">"dateupper"</span>];
        DateTime l = DateTime.Parse(datelower);
        DateTime h = DateTime.Parse(dateupper);

        String responseMessage = ReadDatabase(l,h);
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> OkObjectResult(responseMessage);
     }
}
</code></pre>
<p>Querying the database is done in a similar way to inserting the record.</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> String <span class="hljs-title">ReadDatabase</span>(<span class="hljs-params">DateTime l , DateTime h</span>)</span>
{
   String Connstring = Environment.GetEnvironmentVariable(<span class="hljs-string">"SQLConnString"</span>);
   <span class="hljs-keyword">string</span> format = <span class="hljs-string">"yyyy-MM-dd HH:mm:ss"</span>;
   <span class="hljs-keyword">string</span> queryString = <span class="hljs-string">"SELECT * from photolocations where photodate &gt; '"</span> 
        + l.ToString(format) + <span class="hljs-string">"' and photodate &lt; '"</span> + h.ToString(format) 
        + <span class="hljs-string">"' order by photodate DESC FOR JSON AUTO"</span>;

   String result = <span class="hljs-string">""</span>;
   <span class="hljs-keyword">using</span> (SqlConnection connection = <span class="hljs-keyword">new</span> SqlConnection(Connstring)) {
      SqlCommand command = <span class="hljs-keyword">new</span> SqlCommand(queryString, connection);
      connection.Open();
      SqlDataReader reader = command.ExecuteReader();
      <span class="hljs-keyword">try</span> {
         <span class="hljs-keyword">while</span> (reader.Read()) {
            result = result + reader[<span class="hljs-number">0</span>];
         }
      }
      <span class="hljs-keyword">finally</span> {
         reader.Close();
      }
   }
   <span class="hljs-keyword">return</span> result;
}
</code></pre>
<p>The little bit of magic on the end of the query string "<em>order by photodate DESC FOR JSON AUTO"</em> does two things :</p>
<ul>
<li><p>The records are returned in chronological order, so the front end can simply draw a line between each one and show the path taken.</p>
</li>
<li><p>FOR JSON AUTO structures the return output in a way that the client can process with little further parsing.</p>
</li>
</ul>
<p>The return results look like this :</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696191515671/657689a1-8d6a-4ffd-8ae6-0fd87b48f3b6.png" alt class="image--center mx-auto" /></p>
<p>Once published, the function will wait quietly (and at $0) for requests.</p>
<h3 id="heading-finally-the-map-itself">Finally, the map itself</h3>
<p>The basic HTML structure of the web page is :</p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>WalkWithMe<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"utf-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text/javascript'</span> <span class="hljs-attr">src</span>=<span class="hljs-string">'https://www.bing.com/api/maps/mapcontrol?callback=GetMap&amp;key=REPLACEWITHYOURKEY'</span> <span class="hljs-attr">async</span> <span class="hljs-attr">defer</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="xml">
    <span class="hljs-comment">&lt;!-- Map rendering code to be added here --&gt;</span>
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">body</span> <span class="hljs-attr">bgcolor</span>=<span class="hljs-string">"#333333"</span> <span class="hljs-attr">text</span>=<span class="hljs-string">"white"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myMap"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"width: auto; height:100%;margin-right:300px"</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"right"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"width: 300px;float: right;"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"date"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"lowerdate"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"lowerdate"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"2023-01-01"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"date"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"upperdate"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"upperdate"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"2023-12-12"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>In this case I am using BING maps. Check here: <a target="_blank" href="https://blog.circumblue.com/building-map-based-apps-and-websites">Building map based apps and websites</a> for the basic structure of the HTML if using Azure og Google Maps.</p>
<p>The HTML above creates the page, loads in the bing map rendering engine and call the Javascript function <em>GetMap</em> once it is loaded.</p>
<p>The <em>GetMap</em> function:</p>
<ul>
<li><p>Creates the map with a default centre point (more on the view later).</p>
</li>
<li><p>Adds two layers to the map to hold the points and the lines.</p>
</li>
<li><p>Calls <em>CreateBox</em> to set up a floating placeholder for the images</p>
</li>
<li><p>Then populates all this with a call to <em>GetPhotoLocationsWithTrack</em></p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">GetMap</span>(<span class="hljs-params"></span>) </span>{
   map = <span class="hljs-keyword">new</span> Microsoft.Maps.Map(<span class="hljs-string">'#myMap'</span>, { <span class="hljs-attr">center</span>: <span class="hljs-keyword">new</span> Microsoft.Maps.Location(<span class="hljs-number">-37.82</span>, <span class="hljs-number">144.95</span>) });

   photolayer = <span class="hljs-keyword">new</span> Microsoft.Maps.Layer();
   map.layers.insert(photolayer);
   tracklayer = <span class="hljs-keyword">new</span> Microsoft.Maps.Layer();
   map.layers.insert(tracklayer);
   photolayer.setVisible(<span class="hljs-number">1</span>);
   CreateBox();
   GetPhotoLocationsWithTrack();
}
</code></pre>
<p>The <em>GetXXX</em> function handles the call to Azure :</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">GetPhotoLocationsWithTrack</span>(<span class="hljs-params"></span>) </span>{
   <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">reqListener</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">var</span> myObj = <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-built_in">this</span>.responseText);
      AddImages(myObj);
      DrawTrack(myObj);
      SetView(myObj);
   }

   <span class="hljs-keyword">var</span> input = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"lowerdate"</span>).value;
   <span class="hljs-keyword">var</span> datelower = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(input);
   input = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"upperdate"</span>).value;
   <span class="hljs-keyword">var</span> dateupper = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(input);

   <span class="hljs-keyword">var</span> oReq = <span class="hljs-keyword">new</span> XMLHttpRequest();
   oReq.addEventListener(<span class="hljs-string">"load"</span>, reqListener);
   url = <span class="hljs-string">"https://walkwithme.azurewebsites.net/api/GetAllImages?code=ReplaceWithYourFunctionCode&amp;datelower="</span> + datelower.toJSON() + <span class="hljs-string">"&amp;dateupper="</span> + dateupper.toJSON();

    oReq.open(<span class="hljs-string">"GET"</span>, url);
    oReq.send();
}
</code></pre>
<p>After this call, the <em>myObj</em> variable has a representation of the data returned by the Azure function that is ready to use.</p>
<p>The track (red line) is added with :</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">DrawTrack</span>(<span class="hljs-params">obj</span>) </span>{
   tracklayer.clear();
   <span class="hljs-keyword">var</span> coords = [];

   <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> key <span class="hljs-keyword">in</span> obj) {
      <span class="hljs-keyword">var</span> unit = obj[key];
      <span class="hljs-keyword">if</span> (unit.hasOwnProperty(<span class="hljs-string">'latitude'</span>)) {
         <span class="hljs-keyword">if</span> (unit.latitude != <span class="hljs-number">0</span>) {
            point = <span class="hljs-keyword">new</span> Microsoft.Maps.Location(unit.latitude, unit.longitude);
            coords.push(point);
         }
      }
   }

   <span class="hljs-keyword">var</span> line = <span class="hljs-keyword">new</span> Microsoft.Maps.Polyline(coords, {<span class="hljs-attr">strokeColor</span>: <span class="hljs-string">'red'</span>,<span class="hljs-attr">strokeThickness</span>: <span class="hljs-number">3</span> });
   tracklayer.add(line);
}
</code></pre>
<p>As the Azure function returns the points in chronological order, I do not need to do any special sorting or processing. Simply drawing a line from first point to last and adding to the map layer generates this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696194830969/98a0c9c3-d621-416f-9ae2-e3664d4f34b8.png" alt class="image--center mx-auto" /></p>
<p>The points images are setup with the functions below. <em>AddImages</em> simply iterates through each point in the JSON. <em>AddImage</em> then takes that point and :</p>
<ul>
<li><p>Adds a pin to the map at that coordinate</p>
</li>
<li><p>Adds a piece of metadata to the pin holding the filename of the image</p>
</li>
<li><p>Sets up two event handlers that fire when the mouse hovers over the pin and then leaves it.</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">AddImage</span>(<span class="hljs-params">filename, hlong, hlat</span>) </span>{
   <span class="hljs-keyword">var</span> loc = <span class="hljs-keyword">new</span> Microsoft.Maps.Location(hlat, hlong);
   <span class="hljs-keyword">var</span> pin = <span class="hljs-keyword">new</span> Microsoft.Maps.Pushpin(loc, {<span class="hljs-attr">anchor</span>: <span class="hljs-keyword">new</span> Microsoft.Maps.Point(<span class="hljs-number">10</span>, <span class="hljs-number">10</span>)});
      pin.metadata = {
         <span class="hljs-attr">filename</span>: filename
      };

      Microsoft.Maps.Events.addHandler(pin, <span class="hljs-string">'mouseover'</span>, ImageClicked);
      Microsoft.Maps.Events.addHandler(pin, <span class="hljs-string">'mouseout'</span>, ImageLeft);
      photolayer.add(pin);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">AddImages</span>(<span class="hljs-params">obj</span>) </span>{
   photolayer.clear();
   photocount = <span class="hljs-number">0</span>;

   <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> key <span class="hljs-keyword">in</span> obj) {
      <span class="hljs-keyword">var</span> unit = obj[key];
      <span class="hljs-keyword">if</span> (unit.hasOwnProperty(<span class="hljs-string">'latitude'</span>)) {
         AddImage(unit.filename, unit.longitude, unit.latitude);
         photocount = photocount + <span class="hljs-number">1</span>;
      }
   }
}
</code></pre>
<p>Finally, the image popups are handled with the event handlers below. The image filename, which was stored as a piece of metadata in the pin is simply added to the blob storage root path to generate a full URL. This image is then loaded and displayed as a fixed size.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ImageClicked</span>(<span class="hljs-params">e</span>) </span>{
   <span class="hljs-keyword">var</span> infoboxTemplate = <span class="hljs-string">'&lt;div class="customInfobox"&gt;&lt;div class="title"&gt;&lt;/div&gt;&lt;img src="{filepath}" width="300"&gt;&lt;/div&gt;'</span>;
   <span class="hljs-keyword">if</span> (e.target.metadata) {
      <span class="hljs-comment">//Set the infobox options with the metadata of the pushpin.</span>
      html = infoboxTemplate.replace(<span class="hljs-string">'{filepath}'</span>, <span class="hljs-string">"https://mystorageaccount.blob.core.windows.net/images/"</span> + e.target.metadata.filename)
      infobox.setOptions({
         <span class="hljs-attr">location</span>: e.target.getLocation(),
         <span class="hljs-attr">title</span>: e.target.metadata.filename,
         <span class="hljs-attr">description</span>: e.target.metadata.filename,
         <span class="hljs-attr">visible</span>: <span class="hljs-literal">true</span>,
         <span class="hljs-attr">htmlContent</span>: html
      });
   }
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ImageLeft</span>(<span class="hljs-params">e</span>) </span>{
   infobox.setOptions({
       <span class="hljs-attr">visible</span>: <span class="hljs-literal">false</span>
   });
}
</code></pre>
<p>Finally, some crude enumeration works out the range of coordinates being displayed and auto-resizes the map so that they all fit.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">SetView</span>(<span class="hljs-params">obj</span>) </span>{
   <span class="hljs-keyword">var</span> minlong = <span class="hljs-number">180</span>
   <span class="hljs-keyword">var</span> minlat = <span class="hljs-number">180</span>
   <span class="hljs-keyword">var</span> maxlong = <span class="hljs-number">-180</span>
   <span class="hljs-keyword">var</span> maxlat = <span class="hljs-number">-180</span>

   <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> key <span class="hljs-keyword">in</span> obj) {
      <span class="hljs-keyword">var</span> unit = obj[key];
      <span class="hljs-keyword">if</span> (unit.hasOwnProperty(<span class="hljs-string">'latitude'</span>)) {
         <span class="hljs-keyword">if</span> (unit.latitude &gt; maxlat) { maxlat = unit.latitude }
         <span class="hljs-keyword">if</span> (unit.latitude &lt; minlat) { minlat = unit.latitude }
         <span class="hljs-keyword">if</span> (unit.longitude &gt; maxlong) { maxlong = unit.longitude }
         <span class="hljs-keyword">if</span> (unit.longitude &lt; minlong) { minlong = unit.longitude }
      }
   }

   <span class="hljs-keyword">var</span> rect = Microsoft.Maps.LocationRect.fromEdges(maxlat, minlong, minlat, maxlong)
   map.setView({ <span class="hljs-attr">bounds</span>: rect });
}
</code></pre>
<p>The final result of all this is:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696195942427/9cdf1f41-cfa1-4842-98e5-889d531f9c8c.png" alt class="image--center mx-auto" /></p>
<p>What next? Going forward I'll be adding :</p>
<ul>
<li><p>The ability of the client to define a 'trip' and each point is tagged with this.</p>
</li>
<li><p>The map webpage itself will then let individual trips be selected and shown.</p>
</li>
<li><p>Adding a user login mechanism and more security to the Azure functions and back ends.</p>
</li>
<li><p>The same solution using Azure and Google Maps. (and maybe OpenStreetMaps).</p>
</li>
<li><p>Exploring different back end architectures and storage.</p>
</li>
</ul>
<p><strong>Summary</strong></p>
<p>The goal of this was not a fancy UI/HTML/Javascript. Nor was it necessarily the most elegant code.</p>
<p>Rather the simplicity of the code and architecture was designed to show how straightforward yet powerful a cloud (Azure) based and event-driven architecture can be be for this type of application.</p>
]]></content:encoded></item><item><title><![CDATA[Building Map Based Apps - The Camino Part 2]]></title><description><![CDATA[Capturing the location and photos]]></description><link>https://blog.circumblue.com/building-map-based-apps-the-camino-part-2</link><guid isPermaLink="true">https://blog.circumblue.com/building-map-based-apps-the-camino-part-2</guid><category><![CDATA[Azure]]></category><category><![CDATA[maps]]></category><category><![CDATA[Azure Maps]]></category><category><![CDATA[Bing Maps]]></category><dc:creator><![CDATA[AndrewC]]></dc:creator><pubDate>Sat, 30 Sep 2023 00:27:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1696015756070/f6516c41-76f4-48b0-8f4c-400e460646af.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Continuing on from : <a target="_blank" href="https://blog.circumblue.com/building-map-based-apps-the-camino">Building map based apps - The Camino</a></p>
<p>I needed a simple app on my phone that would enable me to take a photo and upload it to storage (if connectivity was available) OR select photos that I took during the day and upload them in batches once I had reached my accommodation.</p>
<p>Enter a simple .NET MAUI application:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696018040964/e2da2074-98a2-479b-9d02-42a60e6ef97b.png" alt class="image--center mx-auto" /></p>
<p>The <em>Check Location</em> button was really just there to wake up the GPS and force it to take a reading before the photo. As I did not have a local SIM and was relying on WiFi, the GPS sometimes needed some encouragement.</p>
<p>The code for this was simple and well documented (<a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/maui/platform-integration/device/geolocation?tabs=android">Geolocation - .NET MAUI | Microsoft Learn</a>).</p>
<pre><code class="lang-csharp">   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">GetCurrentLocation</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">try</span>
        {
            _isCheckingLocation = <span class="hljs-literal">true</span>;
            GeolocationRequest request = <span class="hljs-keyword">new</span> GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(<span class="hljs-number">10</span>));
            _cancelTokenSource = <span class="hljs-keyword">new</span> CancellationTokenSource();
            Location location = <span class="hljs-keyword">await</span> Geolocation.Default.GetLocationAsync(request, _cancelTokenSource.Token);

            txtLongitude.Text = <span class="hljs-string">"Longitude : "</span> + location.Longitude;
            txtLatitude.Text = <span class="hljs-string">"Latitude : "</span> + location.Latitude;
            txtAltitude.Text = <span class="hljs-string">"Altitude : "</span> + location.Altitude;

        }
        <span class="hljs-keyword">catch</span> (Exception ex)
        {
            txtLongitude.Text = <span class="hljs-string">"Error"</span>;
            txtLatitude.Text = <span class="hljs-string">"Error"</span>;
            txtAltitude.Text = <span class="hljs-string">"Error"</span>;
        }
        <span class="hljs-keyword">finally</span>
        {
            _isCheckingLocation = <span class="hljs-literal">false</span>;
        }
    }
</code></pre>
<p>Then to take a photo :</p>
<pre><code class="lang-csharp">  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">void</span> <span class="hljs-title">TakePhoto</span>(<span class="hljs-params"><span class="hljs-keyword">object</span> sender, EventArgs e</span>)</span>
    {
        txtResult.Text = <span class="hljs-string">""</span>;
        <span class="hljs-comment">//force phone to update location.</span>
        <span class="hljs-keyword">await</span> GetCurrentLocation();

        <span class="hljs-keyword">if</span> (MediaPicker.Default.IsCaptureSupported)
        {
            FileResult photo = <span class="hljs-keyword">await</span> MediaPicker.Default.CapturePhotoAsync();
            <span class="hljs-keyword">if</span> (photo != <span class="hljs-literal">null</span>)
            {
                txtResult.Text = <span class="hljs-string">"Uploading"</span>;                         
                <span class="hljs-comment">// upload the file to Azure Storage</span>
                <span class="hljs-keyword">await</span> UploadFromFileAsync(photo.FullPath);
                txtResult.Text = <span class="hljs-string">"Upload Complete :"</span> + photo.FileName;
            }
        }
    }
</code></pre>
<p>A similar mechanism to pick an existing photo from the gallery and upload it:</p>
<pre><code class="lang-csharp">   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Upload</span>(<span class="hljs-params"><span class="hljs-keyword">object</span> sender, EventArgs e</span>)</span>
    {
        <span class="hljs-comment">//await GetCurrentLocation();</span>
        txtResult.Text = <span class="hljs-string">""</span>;
        <span class="hljs-keyword">if</span> (MediaPicker.Default.IsCaptureSupported)
        {
            FileResult photo = <span class="hljs-keyword">await</span> MediaPicker.Default.PickPhotoAsync();
            <span class="hljs-keyword">if</span> (photo != <span class="hljs-literal">null</span>)
            {
                txtResult.Text = <span class="hljs-string">"Uploading"</span>;
                <span class="hljs-keyword">await</span> UploadFromFileAsync(photo.FullPath);
                txtResult.Text = <span class="hljs-string">"Upload Complete :"</span> + photo.FileName;
            }
        }
    }
</code></pre>
<p>with the only difference being the use of <em>PickPhotoAsync</em> vs. <em>CapturePhotoAsync.</em></p>
<p>For the upload to Azure storage :</p>
<pre><code class="lang-csharp">  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">UploadFromFileAsync</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> localFilePath</span>)</span>
    {
        Uri container_uri = <span class="hljs-keyword">new</span> Uri(BlobSASURL);
        BlobContainerClient bc = <span class="hljs-keyword">new</span> BlobContainerClient(container_uri);

        <span class="hljs-keyword">string</span> fileName = Path.GetFileName(localFilePath);
        BlobClient blobClient = bc.GetBlobClient(fileName);
        <span class="hljs-keyword">try</span>
        {
            BlobContentInfo r = <span class="hljs-keyword">await</span> blobClient.UploadAsync(localFilePath, <span class="hljs-literal">true</span>);
        } <span class="hljs-keyword">catch</span>(Exception e) {
            txtResult.Text = e.Message;
        };  
    }
</code></pre>
<p>Issuing and managing blob access keys can be a chicken and egg situation, and a more comprehensive solution would probably go via an API gateway and avoid direct access to the storage account at all. But for my needs, this worked fine.</p>
<p>I created a Shared Access Signature (<em>BlobSASURL</em> above) that had <em>create</em> rights on the container and nothing else. This means that new files could be uploaded, but nothing existing could be read or changed.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696029951766/344c6f59-1633-4e05-b5b9-4168c0bb2b2e.png" alt class="image--center mx-auto" /></p>
<p>With this app deployed to my phone, I can snap away, with or without connectivity. At the end of each day, I selected the more interesting or representative photos and uploaded them. They appeared on the storage account like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696030742388/7c6718f3-4a79-418e-8cc8-3e6295197134.png" alt class="image--center mx-auto" /></p>
<p>Several easy enhancements here would allow :</p>
<ul>
<li><p>Tagging each photo with a short description or other metadata.</p>
</li>
<li><p>Enabling different trips or events which would then be selectable and displayed on separate maps.</p>
</li>
<li><p>Multi user separation. While the approach above would work for multiple users, all data would be shown on the same map. This may/may not be what is needed.</p>
</li>
</ul>
<h3 id="heading-processing-the-image-with-an-azure-function">Processing the image with an Azure function</h3>
<p>An Azure function with a blob trigger then took care of processing the image and pulling out all the data required to display it on the map.</p>
<p>The basic function :</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">BlobTrigger</span>
    {
        [<span class="hljs-meta">FunctionName(<span class="hljs-meta-string">"BlobTrigger"</span>)</span>]
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Run</span>(<span class="hljs-params">[BlobTrigger(<span class="hljs-string">"images/{name}"</span>, Connection = <span class="hljs-string">"connstring"</span></span>)] Stream myBlob, <span class="hljs-keyword">string</span> name, ILogger log)</span>
        {
            <span class="hljs-keyword">double</span> latitude = <span class="hljs-number">0</span>, longitude = <span class="hljs-number">0</span>;
            DateTime imagedate = DateTime.Now;
            <span class="hljs-keyword">string</span> locationText = GetCoordinate(myBlob, log, <span class="hljs-keyword">ref</span> latitude, <span class="hljs-keyword">ref</span> longitude, <span class="hljs-keyword">ref</span> imagedate);

            SaveToDatabase(name, latitude, longitude,imagedate);
        }
</code></pre>
<p>When deployed, this is executed every time a new file appears. The code calls <em>GetCoordinate</em> to pull out the EXIF data and then <em>SaveToDatabase</em> to store to SQL.</p>
<p>The longitude and latitude are automatically added to the image and stored in the Exchangeable Image File Format (EXIF) part of the jpeg file. More info : <a target="_blank" href="https://cartographicperspectives.org/index.php/journal/article/view/cp75-pagett/html">EXIF and Coordinates | Cartographic Perspectives</a></p>
<p>Using the ExigLib package by <a target="_blank" href="https://www.codeproject.com/Articles/36342/ExifLib-A-Fast-Exif-Data-Extractor-for-NET">Simon McKenzie</a> gives us this code :</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">string</span> <span class="hljs-title">GetCoordinate</span>(<span class="hljs-params">Stream image, ILogger log, <span class="hljs-keyword">ref</span> <span class="hljs-keyword">double</span> latitude, <span class="hljs-keyword">ref</span> <span class="hljs-keyword">double</span> longitude, <span class="hljs-keyword">ref</span> DateTime imagedate</span>)</span>
{
   log.LogInformation(<span class="hljs-string">"Extract location information"</span>);
   ExifReader exifReader = <span class="hljs-keyword">new</span> ExifReader(image);
   exifReader.GetTagValue(ExifTags.DateTime, <span class="hljs-keyword">out</span> imagedate);

   <span class="hljs-keyword">double</span>[] latitudeComponents, longitudeComponents;
   String latref, longref;

   exifReader.GetTagValue(ExifTags.GPSLatitude, <span class="hljs-keyword">out</span> latitudeComponents);
   exifReader.GetTagValue(ExifTags.GPSLatitudeRef, <span class="hljs-keyword">out</span> latref);
   exifReader.GetTagValue(ExifTags.GPSLongitude, <span class="hljs-keyword">out</span> longitudeComponents);
   exifReader.GetTagValue(ExifTags.GPSLongitudeRef, <span class="hljs-keyword">out</span> longref);

   <span class="hljs-keyword">string</span> location = <span class="hljs-keyword">string</span>.Empty;
   latitude = <span class="hljs-number">0</span>;
   longitude = <span class="hljs-number">0</span>;

   <span class="hljs-keyword">if</span> (latitudeComponents == <span class="hljs-literal">null</span> || longitudeComponents == <span class="hljs-literal">null</span>) {
       location = <span class="hljs-string">"No location data"</span>;
   } <span class="hljs-keyword">else</span> {
       latitude = latitudeComponents[<span class="hljs-number">0</span>] + latitudeComponents[<span class="hljs-number">1</span>] / <span class="hljs-number">60</span> + latitudeComponents[<span class="hljs-number">2</span>] / <span class="hljs-number">3600</span>;
       <span class="hljs-keyword">if</span> (latref == <span class="hljs-string">"S"</span>) { latitude = -latitude; }
       longitude = longitudeComponents[<span class="hljs-number">0</span>] + longitudeComponents[<span class="hljs-number">1</span>] / <span class="hljs-number">60</span> + longitudeComponents[<span class="hljs-number">2</span>] / <span class="hljs-number">3600</span>;
       <span class="hljs-keyword">if</span> (longref == <span class="hljs-string">"W"</span>) { longitude = -longitude; }
       location = <span class="hljs-string">$"Latitude: '<span class="hljs-subst">{latitude}</span>' | Longitude: '<span class="hljs-subst">{longitude}</span>'"</span>;
   }

    <span class="hljs-keyword">return</span> location;
}
</code></pre>
<p>Not the most elegant of code but some fiddling is required to convert DMS into decimal and South or West into negatives.</p>
<p>Finally, a simple routine to add a row to the SQL table for each photo:</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">SaveToDatabase</span>(<span class="hljs-params">String filename, <span class="hljs-keyword">double</span> latitude, <span class="hljs-keyword">double</span> longitude, DateTime imagedate</span>)</span>
{
   String Connstring = Environment.GetEnvironmentVariable(<span class="hljs-string">"SQLConnString"</span>);
   System.Data.SqlClient.SqlConnection sqlConnection1 = <span class="hljs-keyword">new</span> System.Data.SqlClient.SqlConnection(Connstring);
   <span class="hljs-keyword">string</span> format = <span class="hljs-string">"yyyy-MM-dd HH:mm:ss"</span>;

   System.Data.SqlClient.SqlCommand cmd = <span class="hljs-keyword">new</span> System.Data.SqlClient.SqlCommand();
   cmd.CommandType = System.Data.CommandType.Text;
   cmd.CommandText = <span class="hljs-string">"INSERT photolocations (Filename, Latitude, Longitude, photodate) VALUES ('"</span> + filename + <span class="hljs-string">"',"</span> + latitude + <span class="hljs-string">","</span> + longitude + <span class="hljs-string">",'"</span> + imagedate.ToString(format) + <span class="hljs-string">"')"</span>;
   cmd.Connection = sqlConnection1;

   sqlConnection1.Open();
   cmd.ExecuteNonQuery();
   sqlConnection1.Close();
   <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Very simple old-school way of working with SQL - and will be replaced with Cosmos as part of an upcoming project.</p>
<p>Note that the JPEG images themselves stay on the storage account and SQL contains only metadata.</p>
<h3 id="heading-summary">Summary</h3>
<p>At this point we have a mobile application taking photos, geotagging them and uploading them to cloud storage. The photos are then processed to pull out GPS locations and a unique row is added to SQL with date/time/long/lat/filename.</p>
<p>This is everything that is needed to start on the front end.</p>
<p>Continued here: <a target="_blank" href="https://blog.circumblue.com/building-map-based-apps-the-camino-part-3">Building Map Based Apps - The Camino Part 3</a></p>
]]></content:encoded></item><item><title><![CDATA[Building map based apps - The Camino]]></title><description><![CDATA[Architecture of a full map based solution.]]></description><link>https://blog.circumblue.com/building-map-based-apps-the-camino</link><guid isPermaLink="true">https://blog.circumblue.com/building-map-based-apps-the-camino</guid><category><![CDATA[Azure]]></category><category><![CDATA[maps]]></category><category><![CDATA[Mapping]]></category><dc:creator><![CDATA[AndrewC]]></dc:creator><pubDate>Fri, 29 Sep 2023 02:28:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1695954816929/37baa869-cb2d-44aa-b786-8d5f233e44fe.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A few months ago I walked the Camino de Santiago from St. Jean Pied de Port in France to Santiago de Compostela in Spain - around 750km over 5 weeks. I wanted a way for my family to track progress and to be able to share photos.</p>
<p>I know there are plenty of existing ways to do this, but I (<em>a</em>) wanted to build something and (<em>b</em>) expected to be offline most of the day so I needed something that would work in a disconnected/semi-connected mode.</p>
<p>I had several requirements :</p>
<ul>
<li><p>Would allow me to take photos offline while walking and upload them later when connectivity is available.</p>
</li>
<li><p>Longitude and Latitude are extracted automatically from photos.</p>
</li>
<li><p>The solution should be low cost (near $0) to run and low maintenance.</p>
</li>
<li><p>Something I could build in a day or two (as I left it to the last minute)</p>
</li>
</ul>
<p>This is what was built:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695952153923/0153d04a-e2ce-494e-b737-85bd13f432b4.png" alt class="image--center mx-auto" /></p>
<ol>
<li><p>A very simple .Net MAUI application on my phone. Allows a picture to be taken in real-time OR selected from existing images.</p>
</li>
<li><p>The JPEG is sent to a blob storage account. This is typically a ~4MB file per image so needs fair bandwidth.</p>
</li>
<li><p>An Azure function is triggered by the presence of a new file. The function extracts the longitude and latitude from the photo EXIF properties and stores them in a SQL table along with the date/time and filename.</p>
</li>
<li><p>A static web app hosts the html/javascript.</p>
</li>
<li><p>The javascript makes an API call to a second Azure function which queries the database and returns an ordered list of (long/lat/date/time/filename) in JSON format.</p>
</li>
<li><p>This is added as a new layer on Bing Maps with a line showing the route and dots showing where photos were taken.</p>
</li>
<li><p>Hovering over a dot loads the JPEG from blob storage and displays it as a popup.</p>
</li>
</ol>
<p>The result looked like this :</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695953208015/68aa2876-49e2-43b5-ad68-c392e30c754f.png" alt class="image--center mx-auto" /></p>
<p>In particular :</p>
<ul>
<li><p>It took only a few seconds from taking/uploading a photo to it being on the map and visible.</p>
</li>
<li><p>The overall solution is loosely coupled and modularised. Any failure (e.g. of the Azure function) would simply mean that the photos queue up on the storage account and are processed in bulk when the function comes back.</p>
</li>
<li><p>It also means architectural components and languages can be readily changed. I prefer to code in C#, so Azure functions and .Net MAUI enable that. But switching the mobile client to Swift/Java or the database from SQL to Cosmos would be invisible to the rest of the solution.</p>
</li>
<li><p>Nearly everything is serverless or zero cost except the SQL database which costs a few dollars a month. There were cheaper options available than SQL - but did I mention I was in a hurry? - so I went with what I knew.</p>
</li>
</ul>
<p>While the selection of any specific component here is subjective and an equivalent solution could be built with entirely different pieces (e.g. Swift/EventGrid/LogicApps/Cosmos/Kubernetes) the basic pattern is fairly common when using a cloud based architecture.</p>
<p>Example : <a target="_blank" href="https://learn.microsoft.com/en-us/azure/architecture/ai-ml/architecture/intelligent-apps-image-processing">Image classification on Azure - Azure Architecture Center | Microsoft Learn</a></p>
<p>Next up : The .NET MAUI app and blob storage in <a target="_blank" href="https://blog.circumblue.com/building-map-based-apps-the-camino-part-2">Building Map Based Apps - The Camino Part 2</a></p>
]]></content:encoded></item><item><title><![CDATA[Building map based apps and websites.]]></title><description><![CDATA[Building geospatial apps and websites using Azure, Bing or Google maps.]]></description><link>https://blog.circumblue.com/building-map-based-apps-and-websites</link><guid isPermaLink="true">https://blog.circumblue.com/building-map-based-apps-and-websites</guid><category><![CDATA[Azure]]></category><category><![CDATA[maps in javaScript]]></category><category><![CDATA[maps]]></category><dc:creator><![CDATA[AndrewC]]></dc:creator><pubDate>Thu, 28 Sep 2023 04:19:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1695868382855/73d680d3-f6f8-4c3f-b09e-3cae9386ba36.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I've always had an affinity for maps, mapping and associated activities (Orienteering, Rogaining, Geocaching). There is just something about distilling so much real-world information down to a few lines and squiggles on a page.</p>
<p>At work this meant that customer queries, demos and tender responses for Azure and Bing maps tended to come to me. I found over the years that there was significant confusion over which ecosystem to use, whether to buy vs. build, and the relationship (or not) between the map visuals in the browser and the backend infrastructure and data that powers it.</p>
<p>The goal of this series of posts is to talk through these choices and architectures, build some apps and see where the road leads :-)</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">🗺</div>
<div data-node-type="callout-text">In this and subsequent articles, I will generally talk about Azure Maps to keep the language simple - but in most cases, the concepts apply equally to all the common mapping platforms.</div>
</div>

<h3 id="heading-why-is-this-needed">Why is this needed?</h3>
<p>The major mapping platforms all have fantastic demos and documentation detailing how to <em>display</em> the maps and draw icons, lines and layers on them.</p>
<p>For example: <a target="_blank" href="https://samples.bingmapsportal.com/">Bing Maps Samples (</a><a target="_blank" href="http://bingmapsportal.com">bingmapsportal.com</a><a target="_blank" href="https://samples.bingmapsportal.com/">)</a> has hundreds of working code snippets to completely control look of the the front end. The other platforms have similar samples available.</p>
<p>However, in nearly all these examples, the data that is being displayed on the map is static and hardcoded into the demo or pulled from a simple CSV file. Full end-to-end examples where geospatial data is captured, stored, processed and then displayed are few.</p>
<h3 id="heading-build-vs-buy">Build vs Buy</h3>
<p>I have had many customer conversations that went along the lines of :</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💬</div>
<div data-node-type="callout-text">"<em>Can Azure Maps do ABC?". "Ok, what about XYZ". "Good, can it do DEF"</em></div>
</div>

<p>The answer to nearly every question is "yes" - because it is a development platform that you can code up to do nearly anything. The dark side of that answer is that you <em>have</em> to code up everything. Out of the box, all you get is an empty map on a screen. So the discussion becomes more about:</p>
<ul>
<li><p>Do you have people with the right coding skills?</p>
</li>
<li><p>Do you have the budget?</p>
</li>
<li><p>How long do you have?</p>
</li>
</ul>
<p>While building a data driven mapping solution is not particularly complex, every additional feature adds time and cost and needs to be maintained. I've been in some discussions where the customer had a fantastic vision, but not the means to execute.</p>
<p>The alternative is to buy an off-the-shelf GIS (Geographic Information System) such as ArcGIS or similar and learn how to use it. These types of products have rich functionality and are often extensible - but you need to evaluate whether they have the features you need and integrate with your existing systems or data.</p>
<p>A balanced sweet spot seems to be in map generation vs. consumption. If you have professional cartographers, mining engineers and so on that spend all day working with this data, then they probably need professional tools. But if the data they generate is displayed and consumed by hundreds, thousands or millions of others then this is where Bing/Google/Azure maps come into their own with high scale and low cost.</p>
<h3 id="heading-which-platform-should-i-choose">Which platform should I choose?</h3>
<p>OK, you have decided to build. Should you choose Google Maps, Bing Maps, Azure Maps or other?</p>
<p>My 2c - It really doesn't matter. All three work pretty much the same way and have the same basic features and development approach.</p>
<p>The HTML &amp; Javascript below is for Azure Maps along with the resulting web page.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
     <span class="hljs-comment">&lt;!-- Add references to the Atlas Map control JavaScript and CSS files. --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.css"</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
        <span class="hljs-keyword">var</span> map;
        <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">GetMap</span>(<span class="hljs-params"></span>) </span>{
            <span class="hljs-comment">//Initialize a map instance.</span>
            map = <span class="hljs-keyword">new</span> atlas.Map(<span class="hljs-string">'myMap'</span>, {<span class="hljs-attr">center</span>: [<span class="hljs-number">144.95</span>, <span class="hljs-number">-37.8</span>], <span class="hljs-attr">zoom</span>: <span class="hljs-number">12</span>,
                <span class="hljs-attr">authOptions</span>: {
                    <span class="hljs-attr">authType</span>: <span class="hljs-string">'subscriptionKey'</span>,
                    <span class="hljs-attr">subscriptionKey</span>: <span class="hljs-string">'ReplaceWithYourKey'</span>
                }
            });
        }
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">body</span> <span class="hljs-attr">onload</span>=<span class="hljs-string">"GetMap()"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">'myMap'</span> <span class="hljs-attr">style</span>=<span class="hljs-string">'width: 100vw; height: 100vh;'</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695871168189/e5767170-fa7f-450e-9cd3-eda97793915c.png" alt class="image--center mx-auto" /></p>
<p>This code and image is for Bing Maps:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">'myMap'</span> <span class="hljs-attr">style</span>=<span class="hljs-string">'width: 100vw; height: 100vh;'</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text/javascript'</span>&gt;</span><span class="javascript">
        <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loadMapScenario</span>(<span class="hljs-params"></span>) </span>{
            <span class="hljs-keyword">var</span> map = <span class="hljs-keyword">new</span> Microsoft.Maps.Map(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'myMap'</span>), { });
            map.setView({
                <span class="hljs-attr">center</span>: <span class="hljs-keyword">new</span> Microsoft.Maps.Location(<span class="hljs-number">-37.8</span>,<span class="hljs-number">144.95</span>),
                <span class="hljs-attr">zoom</span>: <span class="hljs-number">12</span>
            });
        }
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text/javascript'</span> <span class="hljs-attr">src</span>=<span class="hljs-string">'https://www.bing.com/api/maps/mapcontrol?key=ReplaceWithYourKey&amp;callback=loadMapScenario'</span> <span class="hljs-attr">async</span> <span class="hljs-attr">defer</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695871762547/34de3f0e-62f7-40a8-bf93-6d09605cfa8d.png" alt class="image--center mx-auto" /></p>
<p>This final code block and website is using Google Maps:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://polyfill.io/v3/polyfill.min.js?features=default"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://maps.googleapis.com/maps/api/js?key=ReplaceWithYourKey&amp;callback=initMap&amp;libraries=&amp;v=weekly"</span> <span class="hljs-attr">defer</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
      <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">initMap</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">const</span> myLatLng = {
          <span class="hljs-attr">lat</span>: <span class="hljs-number">-37.8</span>, <span class="hljs-attr">lng</span>: <span class="hljs-number">144.95</span>
        };
        <span class="hljs-keyword">const</span> map = <span class="hljs-keyword">new</span> google.maps.Map(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"gmp-map"</span>), {
          <span class="hljs-attr">zoom</span>: <span class="hljs-number">12</span>, <span class="hljs-attr">center</span>: myLatLng, <span class="hljs-attr">fullscreenControl</span>: <span class="hljs-literal">false</span>,
          <span class="hljs-attr">zoomControl</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">streetViewControl</span>: <span class="hljs-literal">false</span>
        });
      }
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"gmp-map"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695874399041/979719d1-6bb2-4621-a69e-cdcada274221.png" alt class="image--center mx-auto" /></p>
<p>In each case :</p>
<ul>
<li><p>The javascript library for the map engine is loaded.</p>
</li>
<li><p>A map object is created with longitude, latitude and other parameters.</p>
</li>
<li><p>A &lt;div&gt; is created in the HTML to display the map.</p>
</li>
</ul>
<p>As we add more advanced elements later on we will see that the basic approach of markers and layers is fairly similar between all three platforms.</p>
<p>So - what should you choose given they all work similarly? I'd suggest starting with the one whose visual aesthetics you like best OR the one best integrated with your current cloud provider. Start overlaying your data and see how it looks and performs. In the early stages, it is very quick to move to one of the other providers (see the similarity of each code snip above) if you find you need to switch.</p>
<p>My personal experiences :</p>
<ul>
<li><p>Google Maps tends to be attractive and fast but can get very cluttered with restaurants, shops and other data taking away from what I am trying to display.</p>
</li>
<li><p>Azure Maps are well integrated into the rest of the Azure ecosystem and support Azure AD authentication, but can be slower and the richness of the map data can be lacking in places.</p>
</li>
<li><p>Bing Maps sits between the other two. The map data is richer than Azure Maps but not as cluttered as Google. However, it is not as well integrated into the rest of the Azure/Microsoft ecosystem.</p>
</li>
</ul>
<h3 id="heading-what-about-openstreetmap">What about OpenStreetMap?</h3>
<p>OpenStreetMap is another mapping choice that has all the same types of capabilities as Azure/Google/Bing. The key difference is that I would describe OpenStreetMap as an open ecosystem rather than a platform. The map tiles themselves are freely available, but you need to either host them yourself or find a hoster. Similarly, several different APIs can be used to display and manipulate them. This provides significant flexibility but also means there is no single canonical approach.</p>
<p>Having said that though, this series will be about the back-end geospatial data capture, storage and processing, all of which will work just as well with an OpenStreetMap front end.</p>
<h3 id="heading-what-next">What next?</h3>
<p>Next, we will walk through a full application and associated architecture here: <a target="_blank" href="https://blog.circumblue.com/building-map-based-apps-the-camino">Building map based apps - The Camino</a></p>
]]></content:encoded></item></channel></rss>