Search code examples
mongodbdatasourcegeojsongeocodingreverse-geocoding

How to get a country region code for a given address


I let users to fill out a form where they state their city of residence. To simplify the process I use Mapbox geocoding API: user starts filling the name of his city and the API suggests results.

User form

User selects a result and I store in my DB the data in following format:

{
  "city": "Paris",
  "region": "TX, //Texas
  "country": "US"
}

I have country svg maps divided by regions.

<svg>
  <g>
    <path id="US-AK" title="Alaska" d="..." />
    <path id="US-TX" title="Texas" d="..." />
    ...
  </g>
</svg>

Now I'm able to select from the DB all users living in Texas and to show the information (number of users living in the region) on the svg map.

The problem is that the API does not always give me a region information in the response. For example for Paris, France

I've tested 6 different API but the data they give me about regions is not consistent. Sometimes APIs don't contain any information about region. Sometimes the information is wrong.

I see only one solution: to store all data about regions (codes and names in different languages) and to let users select their country region by themselves. But maybe you see another, simpler solution ?


Solution

  • We found a different solution. We store shapes of regions in geoJSON format in MongoDB. For each address returned by the API we have GPS coordinates. So we can always find a code of region.

    // Insert regions to DB
    
    db.getCollection('region').insert({
        "code": "FR-IDF",
        "polygons": {
            "type":"MultiPolygon",
            "coordinates": <multi polygon shape>
        }
    });
    
    // Find regions by gps coordinates
    
    db.getCollection('region').find({
        "polygons": {
            $geoIntersects: {
                $geometry:{
                    "type":"Point",
                    "coordinates" : [ 7.0174, 43.5528 ]
                }
            }
        }
    });
    

    I get regions details from here : https://gadm.org/download_country_v3.html → format KMZ (level1). We can simplify regions paths with QGIS (Menu: Vector → Geometry Tools → Simplify…). Then export them to geoJSON file.