Search code examples
javascriptvue.jsopenlayers

How can I get the variable to be set to show something outside the method?


Good day my friends.

I got a variable set in the data of vue:

var comp=
{
    data()
    {
        return{
            polygonString:""
        }
    }
}

Now when I want to set the 'polygonString' inside the method of 'modifyend' it stays blank when doing a console.log() outside the method:

methods:{
     addCoordinate(){
         modify.on('modifyend', function (evt) {

            var flat_coords;
            var modified_coords = [];

            evt.features.forEach(function (feature) {
            flat_coords = feature.getGeometry().getCoordinates();

            for (var i in flat_coords) 
            {
                var flat_coord = flat_coords[i];
                for(var coord_array in flat_coord)
                {
                    var lat_lng = flat_coord[coord_array];
                    var transformed_coords = ol.proj.transform(lat_lng,'EPSG:3857','EPSG:4326');
                                
                    modified_coords.push(transformed_coords.toString().replace(",", " "));
                            }
                        }
                    });
                    this.polygonString = modified_coords.toString().replaceAll(",", ", ");
        });
        console.log("POLYGON STRING", this.polygonString);
     }
}

Solution

  • Registering the modifyend event listener inside a method seems like it will be problematic. You should probably move the registration logic to one of the lifecycle hooks, mounted or created.

    Try making the following changes:

    mounted() {
      modify.on('modifyend', this.addCoordinate);
    },
    methods: {
      addCoordinate(evt) {
        var flat_coords;
        var modified_coords = [];
    
        evt.features.forEach(function(feature) {
          flat_coords = feature.getGeometry().getCoordinates();
    
          for (var i in flat_coords) {
            var flat_coord = flat_coords[i];
            for (var coord_array in flat_coord) {
              var lat_lng = flat_coord[coord_array];
              var transformed_coords = ol.proj.transform(lat_lng, 'EPSG:3857', 'EPSG:4326');
              modified_coords.push(transformed_coords.toString().replace(",", " "));
            }
          }
        });
          
        this.polygonString = modified_coords.toString().replaceAll(",", ", ");
    
        console.log("POLYGON STRING", this.polygonString);
      }
    }