Search code examples
widgetopenstreetmapthingsboard

Adding Polygon data to an OSM map on ThingsBoard


I'm trying to integrate Polygons data into an OpenStreetMap on a ThingsBoard map widget. I have the data saves as a GeoJSON file and I also converted it to a list of polygons (another list) made of [LAT, long] values. Not sure how to add the file into the map and there isn't a choice to use my own OpenStreetMap map/link.

I tried inserting the following lines into the "onInit" function of the widget but can't make it load successfully. Here is the code I added to the 'controllerScript' attribute on the widget's JSON.

self.onInit = function() {
\n\tself.ctx.map = new TbMapWidgetV2('openstreet-map', false, self.ctx);
\n\tself.ctx.map.location.polygon = self.ctx.map.createPolygon(
ListOfLatLnGPolygons, self.ctx.map.location.settings, self.ctx.map.location, 
function (event) 
\n{
\n\tself.ctx.map.callbacks.onLocationClick(self.ctx.map.location);
\n\tself.ctx.map.locationPolygonClick(event, self.ctx.map.location);
\n}, self.ctx.map.location.dsIndex);
\n\tself.ctx.map.polygons.push(self.ctx.map.location.polygon);
\n}
\nself.onDataUpdated = function() {
\n\tself.ctx.map.update();
\n}
\n
\nself.onResize = function() {
\n\tself.ctx.map.resize();
\n}
\n
\nself.getSettingsSchema = function() {
\n\treturn TbMapWidgetV2.settingsSchema('openstreet-map');
\n}
\n
\nself.getDataKeySettingsSchema = function() {
\n\treturn TbMapWidgetV2.dataKeySettingsSchema('openstreet-map');
\n}
\n
\nself.actionSources = function() {
\n\treturn TbMapWidgetV2.actionSources();
\n}
\n
\nself.onDestroy = function() {
\n}
\n

Solution

  • Edited the code and made it work as follows on the onInit() function.

    self.onInit = function() {
    self.ctx.map = new TbMapWidgetV2('openstreet-map',
            false, self.ctx);
        var tbMap = self.ctx.map;
        var coordinates = [[lat1,long1],[lat2,long2],[lat2,long3]]; 
        // I manually entered the coordinates
        var latLangs = [];
    
        self.ctx.map.configureLocationsSettings();
        self.ctx.settings.showPolygon = true;
        self.ctx.settings.polygonColor = "#FE7569";
        self.ctx.settings.polygonStrokeColor = "#000000";
        coordinates.forEach(function(coord) {
            latLangs.push(tbMap.map.createLatLng(
                coord[1], coord[0]));
        })
        tbMap.map.createPolygon(latLangs, self.ctx.settings,
            location, true, null);
    
        tbMap.update();
    }
    

    I still don't know why, but this answer only shows the polygon on the map, but it is not clickable in order to use it with a "on polygon click" action.