<?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 Leandre Gohy on Medium]]></title>
        <description><![CDATA[Stories by Leandre Gohy on Medium]]></description>
        <link>https://medium.com/@leandregohy?source=rss-a56ee1619588------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*X_PEFKWeObs-L4Bz.</url>
            <title>Stories by Leandre Gohy on Medium</title>
            <link>https://medium.com/@leandregohy?source=rss-a56ee1619588------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 02:59:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@leandregohy/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[How we are geolocalising our stories]]></title>
            <link>https://medium.com/itinari/how-we-are-geolocalising-our-stories-1b278ac9b1cd?source=rss-a56ee1619588------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b278ac9b1cd</guid>
            <category><![CDATA[geolocation]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[travel]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Leandre Gohy]]></dc:creator>
            <pubDate>Fri, 30 Mar 2018 07:57:08 GMT</pubDate>
            <atom:updated>2018-03-30T08:29:10.023Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_PA0LDVS90u9IfP1DTJ0Zw.jpeg" /></figure><p>First some context, <a href="https://www.itinari.com/">itinari</a> is a content platform providing traveling inspirations written by local bloggers and travellers focusing on off the beaten paths locations.</p><p>Each of our stories contains a set of places characterised by a latitude and longitude pair. Our first approach was to compute the barycentre of all the places used in a story and then to reverse geocode it to extract the country it falls in using a GeoJSON maps. This approach is working for 95% of our stories, but it comes short on some edge cases like stories with places spread across multiple countries, when the barycentre falls in an other country or in the ocean. So we decided to think about a better yet more complex way to handle those edge cases and also to add more informations about the location of a story. Our goal was to get the following informations in the best scenario: Continent &gt; Country &gt; Level 1 Administrative Area &gt; City.</p><p><strong>Overview of our algorithm</strong></p><p>A quick overview of our new algorithm, first we retrieve the country code for each places in the story, if each of them are not the same then it means the story’s places are spread over multiple countries, we will then only return the continent (worst case scenario), on the other hand, if each story’s places falls in the same country we will compute the barycentre and retrieve the country code for it. Again if the barycentre country code falls in a different country we stop here and return the continent and the country from the places (since they all fall in the same country).</p><p>Let’s continue, we now reach our best case scenario, all of the story’s places and the barycentre fall in the same country. We should be able to get more precise informations like the Level 1 Administrative Area and the city based on the radius (spread of the places) and the barycentre. To do so we will use the Google Map API.</p><p><strong>How to retrieve the country code from coordinates ?</strong></p><p>Using the GeoJSON maps from the excellent <a href="https://www.npmjs.com/package/@geo-maps/countries-maritime-1m">@geo-maps/countries-maritime-1m</a> package published by Simone “simonepri” Primarosa and the <a href="https://www.npmjs.com/package/which-polygon">which-polygon</a> package published by mapbox.</p><pre>const polygon = require(&#39;which-polygon&#39;)<br>const geoMap = require(&#39;@geo-maps/countries-maritime-10m&#39;)</pre><pre>const geoMapQuery = polygon(geoMap())</pre><pre>const point = [50.85045, 4.34878] // [lat, lng]</pre><pre>// geoMapQuery expects a [lng, lat] array<br>const result = geoMapQuery(point.slice().reverse())<br>console.log(result.A3) // ISO 3166–1 alpha-3</pre><p>As you can notice, it returns the ISO 3166–1 alpha-3 country code, but we will use ISO 3166–1 alpha-2 everywhere else, so we need a way to convert ISO 3166–1 alpha-3 to ISO 3166–1 alpha-2, in order to achieve it we will use the <a href="https://www.npmjs.com/package/i18n-iso-countries">i18n-iso-countries</a> package published by Michael “michaelwittig” Wittig.</p><pre>import {alpha3ToAlpha2} from &#39;i18n-iso-countries&#39;</pre><pre>const alpha2Code = alpha3ToAlpha2(alpha3Code)</pre><p><strong>How to retrieve continent code from country code ?</strong></p><p>This relies on a dictionary lookup, each country code is mapped to a continent code. Such up-to-date <a href="http://country.io/continent.json">dictionary</a> can be found on country.io.</p><pre>import * as countryCodeToContinentCodeTable from &#39;continent.json&#39;</pre><pre>function getContinentCodeFromCountryCode(code: string): string {<br> return countryCodeToContinentCodeTable[code]<br>}</pre><p><strong>How to calculate the barycentre of a set of coordinates ?</strong></p><p>The barycentre (or center of mass) is the means of all the latitudes and longitudes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*Jm7pw81hR5mBUcDY2PIBQA.png" /></figure><p>There’s a really good <a href="https://carto.com/blog/center-of-points/">article</a> from carto about calculating the center of points.</p><pre>function sum(array: number[]): number {<br>  return array.reduce((acc, entry) =&gt; acc + entry)<br>}</pre><pre>function avg(array: number[]): number {<br>  return sum(array) / array.length<br>}</pre><pre>function deg2rad(degrees: number): number {<br>  return degrees * (Math.PI / 180)<br>}</pre><pre>function rad2deg(radians: number): number {<br>  return radians * (180 / Math.PI)<br>}</pre><pre>function barycentre(points: number[][]): number[] {<br>  const zeta = avg(points.map((point) =&gt; Math.sin(deg2rad(point[1]))))<br>  const xi = avg(points.map((point) =&gt; Math.cos(deg2rad(point[1]))))<br>  const avgLng = rad2deg(Math.atan2(zeta, xi))<br>  const avgLat = avg(points.map((point) =&gt; point[0]))<br>  return [avgLat, avgLng]<br>}</pre><p><strong>Algorithm: part 1 (Continent &amp; Country)</strong></p><p>Let’s put it all together, so the first part of our algorithm is to determine the country for each place in the story and the country of the barycentre of all those places.</p><pre>function uniq&lt;T&gt;(value: T, index: number, self: Array&lt;T&gt;): boolean {<br>  return self.indexOf(value) === index<br>}</pre><pre>function getLocation(places: number[][]): string[] {<br>  const placeCountryCodes = places<br>    .map((point) =&gt; geoMapQuery(<br>      point<br>        .slice()<br>        .reverse()<br>    ).A3<br>    )<br>    .sort()<br>    .filter(uniq)</pre><pre>  const countryCode = placeCountryCodes[0]<br>  const continentCode = getContinentCodeFromCountryCode(countryCode)<br> <br>  // if the places are spread across multiple countries<br>  if (placeCountryCodes.length &gt; 1) {<br>    return [continentCode]<br>  }</pre><pre>  const center = barycentre(places)<br>  const centerCountryCode = geoMapQuest(center.slice().reverse())</pre><pre>  // if the barycentre is not in the same country as the places<br>  if (centerCountryCode !== countryCode) {<br>    return [continentCode, countryCode]<br>  }</pre><pre>  // …<br>}</pre><p>The second part of the algorithm will be using the Google Maps API, more specifically the Reverse Geocoding API.</p><p><strong>Google Maps Reverse Geocoding API</strong></p><p>All the documentation about the Google Maps Reverse Geocoding API can be found <a href="https://developers.google.com/maps/documentation/geocoding/intro#ReverseGeocoding">here</a>. What we are really interested in about the Google API is that it returns multiple results from the most specific to the least specific. The means the first result can be as narrow as a specific building, the second one will be as narrow as the street, the third one will be as narrow as the city, and so on until we reach country level. Note that the Google API does not provide the continent even though if you type “Europe” in Google Maps it’s able to tell you it’s a continent.</p><p>Let’s take a look to the response format</p><pre>{<br>  results: [<br>    address_components: [{<br>      long_name: string,<br>      short_name: string,<br>      types: string[],<br>    }],<br>    formatted_address: string,<br>    geometry: {<br>      bounds: {<br>        northeast: { lat: number, lng: number },<br>        southwest: { lat: number, lng: number },<br>      },<br>      location: number[],<br>      location_type: string,<br>      viewport: {<br>        northeast: { lat: number, lng: number },<br>        southwest: { lat: number, lng: number },<br>      },<br>    },<br>    place_id: string,<br>    types: string[],<br>  ],<br>  status: string,<br>}</pre><p>The parts of the results we need are geometry bounds and address components, but first we need to find the result that is the best fit for our story.</p><p>Remember I talked a few times about the spread (radius) of a story and that results from the Google API are ordered from the most specific to the least specific ? Great !</p><p>So for each result we have bounds, which means we can calculate a radius out of it, then we can compare the radius of each result to the radius of our story, as soon as the radius of a result from the Google API is bigger or equal to the radius of our story we can stop searching, we have found the result that is able to provide us the maximum of informations.</p><p><strong>How to calculate the radius of a set of coordinates ?</strong></p><p>This is as easy as searching the farthest point from the barycentre and calculating the distance between the two.</p><pre>const EARTH_RADIUS_IN_METERS = 6371230</pre><pre>function distance(pointA: number[], pointB: number[]): number {<br>  const deltaLat = Math.abs(pointA[0] — pointB[0])<br>  const deltaLng = Math.abs(pointA[1] — pointB[0])<br>  const angleLat = Math.abs(pointA[0] + pointB[0]) / 2<br>  const rY = Math.cos(deg2rad(angleLat)) * EARTH_RADIUS_IN_METERS<br>  const distLat = deg2rad(deltaLat) * EARTH_RADIUS_IN_METERS<br>  const distLng = deg2rad(deltaLng) * rY<br>  const dist = Math.sqrt(distLat * distLat + distLng * distLng)<br>  return dist<br>}</pre><pre>function max(array: number[]): number {<br>  return array.reduce((acc, entry) =&gt; (acc &lt; entry &amp;&amp; entry) || acc)<br>}</pre><pre>function radius(center: number[], points: number[][]): number {<br>  const dists = points.map((point) =&gt; distance(center, point))<br>  return max(dists)<br>}</pre><pre>// ...</pre><pre>const spread = radius(center, points)</pre><p><strong>How to find the closest Google API result ?</strong></p><pre>function getClosestResultByRadius(radius: number, results: any[]): any {<br>  return results.find((result) =&gt; {<br>    const bounds = result.geometry.bounds ||<br>                   result.geometry.viewport<br>    const rr = distance(<br>      [bounds.northeast.lat, bounds.northeast.lng],<br>      [bound.southwest.lat, bounds.southwest.lng]<br>    )<br>    return rr &gt;= radius<br>  })<br>}</pre><pre>// ...</pre><pre>const result = getClosestResultByRadius(spread, results)</pre><p><strong>Algorithm: part 2 (Level 1 Administrative Area &amp; City)</strong></p><p>It’s time to put it all together again and finalise our algorithm, yay !</p><pre>async function getLocation(places: number[][]): string[] {<br>  const placeCountryCodes = places<br>    .map((point) =&gt; geoMapQuery(<br>      point<br>        .slice()<br>        .reverse()<br>      ).A3<br>    )<br>    .sort()<br>    .filter(uniq)</pre><pre>  const countryCode = placeCountryCodes[0]<br>  const continentCode = getContinentCodeFromCountryCode(countryCode)<br> <br>  // if the places are spread across multiple countries<br>  if (placeCountryCodes.length &gt; 1) {<br>    return [continentCode]<br>  }</pre><pre>  const center = barycentre(places)<br>  const centerCountryCode = geoMapQuest(center.slice().reverse())</pre><pre>  // if the barycentre is not in the same country as the places<br>  if (centerCountryCode !== countryCode) {<br>    return [continentCode, countryCode]<br>  }</pre><pre>  const results = await googleMapsService.reverseLookup(center)</pre><pre>  if (!results || results.length &lt;= 0) {<br>    return [continentCode, countryCode]<br>  }</pre><pre>  const spread = radius(center, points)<br>  const result = getClosestResultByRadius(spread, results)</pre><pre>  if (!result) {<br>    return [continentCode, countryCode]<br>  }</pre><pre>  // We are only interested in Level 1 Administrative Area &amp; City (locality)<br>  const components = result.address_components<br>    .filter((component) =&gt; {<br>      return component.types.every((type) =&gt; {<br>        return [<br>          &#39;political&#39;,<br>          &#39;administrative_area_level_1&#39;,<br>          &#39;locality&#39;<br>        ].indexOf(type) !== -1<br>      })<br>    })<br>    .map((component) =&gt; component.long_name)<br>    .reverse()</pre><pre>  return [continentCode, countryCode, ...components]<br>}</pre><p>This is it, we are able to correctly geolocalise our stories based on the places referenced in it and the spread of it. A story with really close places will yield a result down to the city level, a story with places around a country will yield a result down to the country level, a story with places spread across multiple countries will yield a result down to continent level.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b278ac9b1cd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/itinari/how-we-are-geolocalising-our-stories-1b278ac9b1cd">How we are geolocalising our stories</a> was originally published in <a href="https://medium.com/itinari">itinari.travel</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>