alexreisner / geocoder

Complete Ruby geocoding solution.
http://www.rubygeocoder.com
MIT License
6.35k stars 1.19k forks source link

Fix nil values in mapbox result #1655

Closed tmh-dev closed 5 months ago

tmh-dev commented 5 months ago

Summary

Fixes nil return in the following Geocoder::Result::Mapbox methods: city, state, state_code, postal_code, country, country_code, and neighborhood.

Explanation

Given the following example of a "region" type response, the Geocoder::Result::Mapbox class will not return a value for the state or state_code methods despite the necessary data existing in the payload:

  {
    "id": "region.107756",
    "type": "Feature",
    "place_type": [
      "region"
    ],
    "relevance": 1,
    "properties": {
      "mapbox_id": "dXJuOm1ieHBsYzpBYVRz",
      "wikidata": "Q1384",
      "short_code": "US-NY"
    },
    "text": "New York",
    "place_name": "New York, United States",
    "bbox": [
      -79.8046875,
      40.4771401,
      -71.763627,
      45.0239467
    ],
    "center": [
      -75.4652471468304,
      42.751210955038
    ],
    "geometry": {
      "type": "Point",
      "coordinates": [
        -75.4652471468304,
        42.751210955038
      ]
    },
    "context": [
      {
        "id": "country.8940",
        "mapbox_id": "dXJuOm1ieHBsYzpJdXc",
        "wikidata": "Q30",
        "short_code": "us",
        "text": "United States"
      }
    ]
}

The incumbent logic assumes that there is an array item in context that will have an id containing the "region" string. Since there isn't one, nil is returned from the state and state_code methods. However, the id in the top-level of the object does contain the "region" string because it is a region type response. This means that the top-level text property is the value that should be returned in the state method, and the top-level properties.short_code should be returned as state_code.

This same pattern holds true for the other types of responses. The base payload "type" (id) determines whether or not values for certain methods should be pulled from a context list item or from the base text/properties.

alexreisner commented 5 months ago

Thanks for this!