Search code examples
phpgoogle-mapsgoogle-geocoder

Restrict Google Geocoding to only true country results


At the moment, I can send shsihsigsuygdjhgadjhg through my Google Geocode API, and it returns an APPROXIMATE location type - even though I have just made it up!

I have restricted the request to just GB (United Kingdom), as per the documentation, but how can I restrict it to only return a true place?

Parameters:

$param = ['address' => 'shsihsigsuygdjhgadjhg','components' => 'country:GB'];

Response:

$response = \Geocoder::geocode('json', $param);
            $decoded_response = json_decode($response);

The response is:

+"results": array:1 [▼
    0 => {#314 ▼
      +"address_components": array:1 [▼
        0 => {#313 ▼
          +"long_name": "United Kingdom"
          +"short_name": "GB"
          +"types": array:2 [▼
            0 => "country"
            1 => "political"
          ]
        }
      ]
      +"formatted_address": "United Kingdom"
      +"geometry": {#320 ▼
        +"bounds": {#131 ▶}
        +"location": {#321 ▶}
        +"location_type": "APPROXIMATE"
        +"viewport": {#323 ▶}
      }
      +"partial_match": true
      +"place_id": "ChIJqZHHQhE7WgIReiWIMkOg-MQ"
      +"types": array:2 [▼
        0 => "country"
        1 => "political"
      ]
    }
  ]
  +"status": "OK"
}

How can I ensure it returns ZERO_RESULTS for approximate locations?


Solution

  • Instead of adding the components field add the country value to the address field itself. The component field tries to get the component within the values you specified. It couldn't identify the address you are passing in but it recognizes the country and hence you are getting the partial match for it.

    Instead of

    $param = ['address' => 'shsihsigsuygdjhgadjhg','components' => 'country:GB'];
    

    Try,

    $param = ['address' => 'shsihsigsuygdjhgadjhg, GB'];
    

    I am getting Zero results for the second implementation.