Geolocation in Business Central, where am I? How do I find nearby places?🌎

Identifiquemos la geolocalización como la capacidad para obtener la ubicación geográfica real de un objeto, como un radar, un teléfono móvil o un ordenador conectado a Internet, puede referirse a la consulta de la ubicación, o bien para la consulta real de la ubicación. Se utiliza comúnmente para proporcionar metadatos de la ubicación, objetos y datos de georreferenciación de manera rápida y precisa.

Entre algunas de las ventajas de su utilización, tenemos una optimización en la visualización de los resultados de las búsquedas de servicios basados en la ubicación. Podemos filtrar anuncios o mensajes, que el usuario en base a su ubicación actual, no los necesita. Mejorando la comunicación.

Mejora y perfecciona las operaciones de logística y seguridad, al rastrear y hacer seguimiento en tiempo real de vehículos, personas y mercancías, además de optimizar la gestión de rutas.

Funcionalidad en Business Central

Los siguientes objetos componen el módulo.

La codeunit de «Geolocation» contiene las funciones principales para su uso:

  • SetHighAccuracy: Establece si los datos de ubicación geográfica del dispositivo deben tener el nivel más alto de precisión.
  • RequestGeolocation: Solicita una ubicación geográfica desde el dispositivo del cliente y devuelve si la solicitud fue exitosa.
  • GetGeolocation: Obtiene una ubicación geográfica del dispositivo cliente y la devuelve en los parámetros de longitud y latitud.

Cuando utilizamos esta funcionalidad por primera vez, se nos solicita el permiso para que Business Central trabaje con nuestra ubicación.

La función «RequestGeolocation» de la codeunit 7569 «Geolocation» nos muestra la página siguiente 7568 «Geolocation»

    procedure RequestGeolocation(GeolocationImpl: Codeunit "Geolocation Impl."): Boolean
    begin
        Clear(GeolocationPage);
        GeolocationPage.SetGeolocationImpl(GeolocationImpl);
        GeolocationPage.RunModal();
        if HasGeolocation() then
            exit(true);

        exit(false);
    end;

La función «GetGeolocation» de la codeunit 7569 «Geolocation» nos permite obtener la información de la latitud y longitud.

    procedure GetGeolocation(var Latitude: Decimal; var Longitude: Decimal)
    begin
        if (not HasGeolocation()) then
            Error(LocationNotRetrievedErrorMsg);

        Latitude := CachedLocation.Coordinate.Latitude;
        Longitude := CachedLocation.Coordinate.Longitude;
    end;

Azure Maps

Por lo que, procederé a crear una cuenta de Azure Maps, y trabajaré en este caso, a modo de ejemplo, con la autenticación de «Shared Key Authentication».

Ejemplo en Business Central

En la búsqueda de Business Central encontraremos dos páginas, una de configuración y otra donde se encuentran las opciones de ejemplo:

  • Configuración: Se registra el Api Key que usaremos para conectarnos a Azure Maps y también un lugar de interés que queremos encontrar cerca a donde estamos, ya lo veremos en acción más adelante.
  • Opciones de ejemplo: Obtener la información de la dirección dónde estamos, la imagen del mapa del lugar donde estamos, que lugares de interés (por ejemplo, colegios o bancos) tengo cerca a donde estoy y por último obtener el clima actual del lugar donde estoy.

¿Dónde estoy?

Primero usaremos la funcionalidad de geolocalización de Business Central para obtener la longitud y latitud de lugar donde estamos. Y luego usaremos la siguiente API para obtener una dirección de calle e información de ubicación a partir de coordenadas de latitud y longitud.

GET https://atlas.microsoft.com/search/address/reverse/{format}?api-version=1.0&query={query}

Desde Business Central, tendríamos la siguiente página con los datos principales del API.

¿Dónde estoy? (Imagen del mapa)

Primero usaremos la funcionalidad de geolocalización de Business Central para obtener la longitud y latitud de lugar donde estamos. Y luego usaremos la siguiente API para representar una imagen rectangular que contiene una sección del mapa usando un nivel de zoom que oscila entre 0 y 20.

GET https://atlas.microsoft.com/map/static/png?api-version=2022-08-01

En el siguiente ejemplo, enviamos los siguientes parámetros adicionales al API:

  • Layer: El valor Basic, devuelve una imagen que contiene todas las características del mapa, incluidos polígonos, bordes, carreteras y etiquetas.
  • Zoom: Nivel de zoom deseado del mapa. El valor de zoom debe estar en el rango: 0-20.
  • Style: Estilo principal de Azure Maps
  • View: Permite mostrar los mapas correctos para un determinado país/región para regiones geopolíticamente disputadas. El valor «Auto» devolverá los datos del mapa en función de la dirección IP de la solicitud.
  • Height y Width: Altura y Anchura de la imagen resultante en píxeles.

Desde Business Central, tendríamos la siguiente página con la imagen del mapa.

¿Hay puntos de interés, cerca de mí?

Primero usaremos la funcionalidad de geolocalización de Business Central para obtener la longitud y latitud de lugar donde estamos. Y luego usaremos la siguiente API para buscar puntos de interés por nombre cerca de mí, el punto de interés lo configuramos en la página de configuración.

GET https://atlas.microsoft.com/search/poi/{format}?api-version=1.0&query={query}

En el siguiente ejemplo, enviamos los siguientes parámetros adicionales al API:

  • Limit: Número máximo de respuestas que se devolverán. En el ejemplo, 5.
  • Radious: El radio en metros para que los resultados se limiten al área definida. En el ejemplo 8 kilómetros.

Desde Business Central, tendríamos la siguiente página con los campos principales del API y el resultado de los 5 bancos que ha encontrado cerca.

¿Cómo está el clima donde me encuentro?

Primero usaremos la funcionalidad de geolocalización de Business Central para obtener la longitud y latitud de lugar donde estamos. Y luego usaremos la siguiente API para obtener las condiciones meteorológicas detalladas, como precipitación, temperatura y viento para la ubicación de coordenadas enviada.

GET https://atlas.microsoft.com/weather/currentConditions/json?api-version=1.1&query={query}

Desde Business Central, tendríamos la siguiente página con los datos principales del API.

El detalle de las APIs disponibles lo encontramos aquí:

Otros servicios similares

Adicionalmente, al servicio de Azure Maps mencionado, tenemos otras opciones de servicios de geolocalización como lo son Bing Maps y Google Maps.

Espero que esta información te ayude.


Let’s identify geolocation as the ability to obtain the real geographical location of an object, such as a radar, a mobile phone or a computer connected to the Internet, it can refer to the query of the location, or for the actual query of the location. It is commonly used to provide location metadata, objects, and georeferencing data quickly and accurately.

Among some of the advantages of its use, we have an optimization in the display of search results for location-based services. We can filter ads or messages that the user, based on their current location, does not need. Improving communication.

Improves and refines logistics and security operations by locating and tracking vehicles, people and goods in real time, in addition to optimizing route management.

Functionality in Business Central

The following objects belong to the module.

The «Geolocation» codeunit contains the main functions for use:

  • SetHighAccuracy: Sets whether device geolocation data should have the highest level of accuracy.
  • RequestGeolocation: Request a geolocation from the client device and return if the request was successful.
  • GetGeolocation: Gets a geographic location of the client device and returns it in longitude and latitude parameters.

When we use this feature for the first time, we are asked for permission for Business Central to work with our location.

The «RequestGeolocation» function of codeunit 7569 «Geolocation» shows us the next page 7568 «Geolocation»

    procedure RequestGeolocation(GeolocationImpl: Codeunit "Geolocation Impl."): Boolean
    begin
        Clear(GeolocationPage);
        GeolocationPage.SetGeolocationImpl(GeolocationImpl);
        GeolocationPage.RunModal();
        if HasGeolocation() then
            exit(true);

        exit(false);
    end;

The «GetGeolocation» function of codeunit 7569 «Geolocation» allows us to obtain latitude and longitude information.

    procedure GetGeolocation(var Latitude: Decimal; var Longitude: Decimal)
    begin
        if (not HasGeolocation()) then
            Error(LocationNotRetrievedErrorMsg);

        Latitude := CachedLocation.Coordinate.Latitude;
        Longitude := CachedLocation.Coordinate.Longitude;
    end;

Azure Maps

Therefore, I will proceed to create an Azure Maps account, and I will work in this case, as an example, with «Shared Key Authentication».

Example in Business Central

In «Tell Me» feature we will find two pages, one for setup and another where the example options are found:

  • Setup: The Api Key that we will use to connect to Azure Maps is registered and also a point of interest that we want to find close to where we are, we will see it in action later.
  • Example options: Obtain the address information where we are, the image of the map of the place where we are, what places of interest (for example, schools or banks) are close to where we are and finally obtain the current weather of the place where we are.

Where I am?

First we will use Business Central’s geolocation functionality to obtain the longitude and latitude of where we are. And then we will use the following API to get a street address and location information from latitude and longitude coordinates.

GET https://atlas.microsoft.com/search/address/reverse/{format}?api-version=1.0&query={query}

From Business Central, we would have the following page with the main data of the API.

Where I am? (Map image)

First we will use Business Central’s geolocation functionality to obtain the longitude and latitude of where we are. And then we will use the following API to render a rectangular image containing a section of the map using a zoom level ranging from 0 to 20.

GET https://atlas.microsoft.com/map/static/png?api-version=2022-08-01

In the following example, we send the following additional parameters to the API:

  • Layer: The Basic value returns an image that contains all the map features, including polygons, edges, roads, and labels.
  • Zoom: Desired zoom level of the map. The zoom value must be in the range: 0-20.
  • Style: Azure Maps main style
  • View: Allows you to display the correct maps for a given country/region for geopolitically disputed regions. The «Auto» value will return map data based on the IP address of the request.
  • Height and Width: Height and Width of the resulting image in pixels.

From Business Central, we would have the following page with the map image.

Are there points of interest near me?

First we will use Business Central’s geolocation functionality to obtain the longitude and latitude of where we are. And then we will use the following API to search points of interest by name near me, we set the point of interest in the setup page.

GET https://atlas.microsoft.com/search/poi/{format}?api-version=1.0&query={query}

In the following example, we send the following additional parameters to the API:

  • Limit: Maximum number of responses to be returned. In the example, 5.
  • Radius: The radius in meters so that the results are limited to the defined area. In the example 8 kilometers.

From Business Central, we would have the following page with the main fields of the API and the result of the 5 banks that it has found nearby.

What is the weather where I am?

First we will use Business Central’s geolocation functionality to obtain the longitude and latitude of where we are. And then we will use the following API to get the detailed weather conditions such as precipitation, temperature and wind for the submitted coordinate location.

GET https://atlas.microsoft.com/weather/currentConditions/json?api-version=1.1&query={query}

From Business Central, we would have the following page with the main data of the API.

The details of the available APIs can be found here:

Other similar services

Additionally, to the Azure Maps service mentioned, we have other options for geolocation services such as Bing Maps and Google Maps.

I hope this information helps you.


Más información / More information:

Deja un comentario