Next Spaceship

Driving into future…

Python Script for Getting a Random Address With Google Map API

| Comments

With Google Map API, you can do a lot of thing. Here I will use it to turn latitude and longitude into human-readable addresses.

This script has 2 parts. The first part generate a random location, ie latitude and longitude, with the Gaussion distribution which is a method in random package. Then it turns a coordinate into an address with The Google Geocoding API.

Note that use of the Google Geocoding API is subject to a query limit of 2,500 geolocation requests per day. Read more restrictions about Google Map API here:http://code.google.com/apis/maps/terms.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#encoding:utf-8
#Created by Leon <i@leons.im> in 2012

import urllib2
import re, json, time,hashlib, random
import MultipartPostHandler
from gevent import pool
from gevent import monkey
from urllib2 import URLError, HTTPError

monkey.patch_all()

def get_address():
    u = 100000.0
    v = 1000000.0

    longitude = int(random.gauss(116467615, u))
    latitude = int(random.gauss(39923488, u))
    print "longitude=%d,latitude=%d" % (longitude, latitude)

    url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false&language=zh-CN' % (latitude / v, longitude / v)
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(), urllib2.HTTPRedirectHandler())

    try:
        str_content = opener.open(url).read()
    except HTTPError, e:
        print 'Error code: ', e.code
        time.sleep(36)
        return get_address()
    except URLError, e:
        print e.reason
        time.sleep(36)
        return get_address()

    if str_content:
        content = json.loads(str_content)
        if content['status'] == 'OK':
            address = content['results'][0]['formatted_address']
            if address.find(' ') > 0:
                address = address[:address.find(' ')]

            address = address.encode('utf-8')
            return (longitude, latitude, address)
        else:
            print content['status'].encode('utf-8') + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
            time.sleep(36) # This is due to the 2500/24h limit.
            return get_address()

Comments