1

I wrote a function that gets an input containing the name of a city/village. Now it seems that the Google API directions matrix does not recognize one of the values given. Does anyone know how to get results anyway? If I type in the village name (Erp, in the Netherlands) in Google Maps, it finds it without struggle.

The code of the function:

def calc_dist(dest):
    jsonReq = json.load(uReq(jsonURL + source + "&destinations=" + dest + 
    "&key=" + googleAPI))
    distance = jsonReq['rows'][0]['elements'][0]['distance']['value']
    return distance

The error is:

Traceback (most recent call last):
File "webscraper_tester.py", line 88, in <module>
distance = str(calc_dist(destination))
File "webscraper_tester.py", line 25, in calc_dist
distance = jsonReq['rows'][0]['elements'][0]['distance']['value']
KeyError: 'distance'

The generated URL is as follows:

https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=Nijmegen,GE&destinations=Erp,NB&key="API-KEY"
Thomson
  • 37
  • 9

1 Answers1

1

Google Maps uses ISO 3166-1 country codes in its various APIs and when looking up a locality, it is good to include the country code.

The country code for Netherlands is NL. If I rewrite your request, removing what looks to be the region code you included and adding the country code, like this:

https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=Nijmegen,NL&destinations=Erp,NL&key=YOUR_KEY

It then returns:

{
  "destination_addresses": [
    "5469 Erp, Netherlands"
  ],
  "origin_addresses": [
    "Nijmegen, Netherlands"
  ],
  "rows": [{
    "elements": [{
      "distance": {
        "text": "45.7 km",
        "value": 45652
      },
      "duration": {
        "text": "35 mins",
        "value": 2113
      },
      "status": "OK"
    }]
  }],
  "status": "OK"
}
MrUpsidown
  • 21,592
  • 15
  • 77
  • 131