Validating Overture Maps Address Data Using a QGIS Processing Model

Address data quality, we all know that it´s an irresistable topic. I often see a lot of errors when dealing with address data, such as:

  • The street name is spelled incorrectly or missing completely
  • The address number is missing
  • The address number is incorrect, such as Main Street 5D, when only 5A-5C is available
  • Wrong or missing postal code
  • Wrong or incorrectly spelled postal area

Still, I hadn´t tested address data from Overture Maps Foundation. This had to change.

The city of Gothenburg, Sweden, has a lot of open data published and in this case, the address data set will be used to test the Overture Maps Foundation addresses. It doesn’t include postal code or postal area, but it will have to do for this test.

Overture features in Gothenburg.

The approach is to download the two data sets and use a QGIS processing model to validate address data from the Overture Maps Foundation. The plugin GeoParquet Downloader for QGIS is very useful for fetching the data, in this case the the table overture_places. Each address from the data sets will be concatenated into a string and the Overture addresses will be tested against the official data set.

The Processing model in QGIS 3.44.2.

Some of the attributes in the Overture addresses contain JSON data and QGIS doesn´t shine when it comes to dealing with this data type in Processing models. In order to solve this, Gemini and I wrote a Python script that extracted the relevant parts of this attribute. Python scripts can be included in a model, adding a lot of room for data wrangling.

The result shows that there are 19 037 features (restaurants, pubs, hotels etc) with address data in this region. 3097 of these did not match the official address data set exactly, so there is work to be done here. I would expect a lot of additional errors to be detected if the test had included postal code and postal area data as well. It would also be interesting to run this model with nationwide data sets. The model is published on GitHub. Feel free to download it and run it with your own data.

In case you need the Python part as well:

import json
from qgis.core import QgsProcessing
from qgis.core import QgsProcessingParameterVectorLayer, QgsProcessingParameterFeatureSink, QgsProcessingAlgorithm, QgsFields, QgsField, QgsWkbTypes, QgsFeature, QgsFeatureSink, QgsApplication
from PyQt5.QtCore import QCoreApplication

class CleanAddressAttribute(QgsProcessingAlgorithm):
    
    INPUT_LAYER = 'INPUT_LAYER'
    OUTPUT_LAYER = 'OUTPUT_LAYER'

    def tr(self, message):
        """Get the translation for a string using the translator for this class."""
        return QCoreApplication.translate('CleanAddressAttribute', message)

    def initAlgorithm(self, config=None):
        self.addParameter(
            QgsProcessingParameterVectorLayer(
                self.INPUT_LAYER,
                self.tr('Input Layer'),
                [QgsProcessing.TypeVector]
            )
        )
        self.addParameter(
            QgsProcessingParameterFeatureSink(
                self.OUTPUT_LAYER,
                self.tr('Output Layer')
            )
        )

    def processAlgorithm(self, parameters, context, feedback):
        source_layer = self.parameterAsVectorLayer(parameters, self.INPUT_LAYER, context)
        
        input_fields = source_layer.fields()
        
        # Skapa de nya fälten, exklusive "sources" och "addresses"
        output_fields = QgsFields()
        for field in input_fields:
            if field.name().lower() not in ['sources', 'addresses']:
                output_fields.append(QgsField(field))
        
        output_fields.append(QgsField('clean_address', 10, len=200))
        
        sink, dest_id = self.parameterAsSink(
            parameters,
            self.OUTPUT_LAYER,
            context,
            output_fields,
            source_layer.wkbType(),
            source_layer.crs()
        )

        total = source_layer.featureCount()
        if total == 0:
            return {self.OUTPUT_LAYER: dest_id}

        for current, feature in enumerate(source_layer.getFeatures()):
            if feedback.isCanceled():
                break

            cleaned_address = None

            try:
                json_data = feature['addresses']
                
                if isinstance(json_data, list) and len(json_data) > 0:
                    address_entry = json_data[0]
                    if isinstance(address_entry, dict) and 'freeform' in address_entry:
                        freeform_value = address_entry['freeform']
                        
                        if freeform_value is not None and str(freeform_value).lower() != 'null':
                            cleaned_address = str(freeform_value)
            
            except (KeyError, IndexError, TypeError) as e:
                feedback.pushInfo(f"Skipping feature due to JSON parsing error or unexpected format: {e}. Original value: {feature.attribute('addresses')}")
            
            new_feature = QgsFeature()
            new_feature.setGeometry(feature.geometry())
            new_feature.setFields(output_fields)

            source_attributes = feature.attributes()
            new_attributes = [None] * len(output_fields)
            
            # Copy old attributes
            for i in range(len(input_fields)):
                field_name = input_fields[i].name()
                if field_name.lower() not in ['sources', 'addresses']:
                    new_index = output_fields.indexOf(field_name)
                    if new_index != -1:
                        new_attributes[new_index] = source_attributes[i]

            new_feature.setAttributes(new_attributes)

            new_feature['clean_address'] = cleaned_address
            
            sink.addFeature(new_feature, QgsFeatureSink.FastInsert)
            
            feedback.setProgress((current / total) * 100)

        return {self.OUTPUT_LAYER: dest_id}

    def name(self):
        return 'clean_address_attribute'

    def displayName(self):
        return self.tr('Clean Address Attribute')

    def group(self):
        return self.tr('Custom Scripts')

    def createInstance(self):
        return CleanAddressAttribute()

Leave a Reply

Your email address will not be published. Required fields are marked *

Please reload

Please Wait