In [1]:
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt  
import matplotlib.cbook as cbook
import numpy as np
import os
import sys
import requests
import json
import datawash

In [28]:
AKEY = 'Pt15VZ8Msk0fjKO4SXLUD58CiwbOOZ0P'
def get_coord(address):
    """从百度地图API获取地址对应的坐标。
    """
    response = requests.get('http://api.map.baidu.com/geocoder/v2/?address=' + address 
                            + '&ak=' + AKEY + '&output=json')
    address_dict = json.loads(response.text)
    return address_dict

def get_map():
    """从百度地图API获取地图并存储
    """
    width = '1024'
    height = '768'
    centerlng = 105.0
    centerlat = 37.0
    response = requests.get('http://api.map.baidu.com/staticimage/v2?ak=' + AKEY
                            + '&width='+ width + '&height='+ height
                            + '&zoom=5&center=' + str(centerlng)+','+str(centerlat))
    with open(os.path.join('image','map.png'),'wb') as img:
        img.write(response.content)
    edge = {'left':67.177, 'right':142.606,'top':56.269,'bottom':11.467}
    return os.path.abspath(os.path.join('image','map.png')),edge

In [29]:
# 遍历所有用户,读取需要的信息
locationslist = list()

jsons = datawash.datajsons()
for user in jsons:
    try:
        locationslist.append(user['locations'][0]['name'])
    except:
        pass

In [34]:
# 批量获取坐标
coord_dict = dict()
templist = list(set(locationslist))
for loc in templist:
    coord_dict[loc] = get_coord(loc)


---------------------------------------------------------------------------
TimeoutError                              Traceback (most recent call last)
c:\users\张成悟\appdata\local\programs\python\python36\lib\site-packages\urllib3\connection.py in _new_conn(self)
    140             conn = connection.create_connection(
--> 141                 (self.host, self.port), self.timeout, **extra_kw)
    142 

c:\users\张成悟\appdata\local\programs\python\python36\lib\site-packages\urllib3\util\connection.py in create_connection(address, timeout, source_address, socket_options)
     82     if err is not None:
---> 83         raise err
     84 

c:\users\张成悟\appdata\local\programs\python\python36\lib\site-packages\urllib3\util\connection.py in create_connection(address, timeout, source_address, socket_options)
     72                 sock.bind(source_address)
---> 73             sock.connect(sa)
     74             return sock

TimeoutError: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。

During handling of the above exception, another exception occurred:

NewConnectionError                        Traceback (most recent call last)
c:\users\张成悟\appdata\local\programs\python\python36\lib\site-packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    599                                                   body=body, headers=headers,
--> 600                                                   chunked=chunked)
    601 

c:\users\张成悟\appdata\local\programs\python\python36\lib\site-packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
    355         else:
--> 356             conn.request(method, url, **httplib_request_kw)
    357 

c:\users\张成悟\appdata\local\programs\python\python36\lib\http\client.py in request(self, method, url, body, headers, encode_chunked)
   1238         """Send a complete request to the server."""
-> 1239         self._send_request(method, url, body, headers, encode_chunked)
   1240 

c:\users\张成悟\appdata\local\programs\python\python36\lib\http\client.py in _send_request(self, method, url, body, headers, encode_chunked)
   1284             body = _encode(body, 'body')
-> 1285         self.endheaders(body, encode_chunked=encode_chunked)
   1286 

c:\users\张成悟\appdata\local\programs\python\python36\lib\http\client.py in endheaders(self, message_body, encode_chunked)
   1233             raise CannotSendHeader()
-> 1234         self._send_output(message_body, encode_chunked=encode_chunked)
   1235 

c:\users\张成悟\appdata\local\programs\python\python36\lib\http\client.py in _send_output(self, message_body, encode_chunked)
   1025         del self._buffer[:]
-> 1026         self.send(msg)
   1027 

c:\users\张成悟\appdata\local\programs\python\python36\lib\http\client.py in send(self, data)
    963             if self.auto_open:
--> 964                 self.connect()
    965             else:

c:\users\张成悟\appdata\local\programs\python\python36\lib\site-packages\urllib3\connection.py in connect(self)
    165     def connect(self):
--> 166         conn = self._new_conn()
    167         self._prepare_conn(conn)

c:\users\张成悟\appdata\local\programs\python\python36\lib\site-packages\urllib3\connection.py in _new_conn(self)
    149             raise NewConnectionError(
--> 150                 self, "Failed to establish a new connection: %s" % e)
    151 

NewConnectionError: <urllib3.connection.HTTPConnection object at 0x000001F77A058358>: Failed to establish a new connection: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。

During handling of the above exception, another exception occurred:

MaxRetryError                             Traceback (most recent call last)
c:\users\张成悟\appdata\local\programs\python\python36\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    439                     retries=self.max_retries,
--> 440                     timeout=timeout
    441                 )

c:\users\张成悟\appdata\local\programs\python\python36\lib\site-packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    648             retries = retries.increment(method, url, error=e, _pool=self,
--> 649                                         _stacktrace=sys.exc_info()[2])
    650             retries.sleep()

c:\users\张成悟\appdata\local\programs\python\python36\lib\site-packages\urllib3\util\retry.py in increment(self, method, url, response, error, _pool, _stacktrace)
    387         if new_retry.is_exhausted():
--> 388             raise MaxRetryError(_pool, url, error or ResponseError(cause))
    389 

MaxRetryError: HTTPConnectionPool(host='api.map.baidu.com', port=80): Max retries exceeded with url: /geocoder/v2/?address=%E6%B0%AA%E6%98%9F%E7%90%83&ak=Pt15VZ8Msk0fjKO4SXLUD58CiwbOOZ0P&output=json (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001F77A058358>: Failed to establish a new connection: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。',))

During handling of the above exception, another exception occurred:

ConnectionError                           Traceback (most recent call last)
<ipython-input-34-6177ddffa865> in <module>()
      3 templist = list(set(locationslist))
      4 for loc in templist:
----> 5     coord_dict[loc] = get_coord(loc)

<ipython-input-28-1697b5a66be6> in get_coord(address)
      4     """
      5     response = requests.get('http://api.map.baidu.com/geocoder/v2/?address=' + address 
----> 6                             + '&ak=' + AKEY + '&output=json')
      7     address_dict = json.loads(response.text)
      8     return address_dict

c:\users\张成悟\appdata\local\programs\python\python36\lib\site-packages\requests\api.py in get(url, params, **kwargs)
     70 
     71     kwargs.setdefault('allow_redirects', True)
---> 72     return request('get', url, params=params, **kwargs)
     73 
     74 

c:\users\张成悟\appdata\local\programs\python\python36\lib\site-packages\requests\api.py in request(method, url, **kwargs)
     56     # cases, and look like a memory leak in others.
     57     with sessions.Session() as session:
---> 58         return session.request(method=method, url=url, **kwargs)
     59 
     60 

c:\users\张成悟\appdata\local\programs\python\python36\lib\site-packages\requests\sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
    511         }
    512         send_kwargs.update(settings)
--> 513         resp = self.send(prep, **send_kwargs)
    514 
    515         return resp

c:\users\张成悟\appdata\local\programs\python\python36\lib\site-packages\requests\sessions.py in send(self, request, **kwargs)
    621 
    622         # Send the request
--> 623         r = adapter.send(request, **kwargs)
    624 
    625         # Total elapsed time of the request (approximately)

c:\users\张成悟\appdata\local\programs\python\python36\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    502                 raise ProxyError(e, request=request)
    503 
--> 504             raise ConnectionError(e, request=request)
    505 
    506         except ClosedPoolError as e:

ConnectionError: HTTPConnectionPool(host='api.map.baidu.com', port=80): Max retries exceeded with url: /geocoder/v2/?address=%E6%B0%AA%E6%98%9F%E7%90%83&ak=Pt15VZ8Msk0fjKO4SXLUD58CiwbOOZ0P&output=json (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001F77A058358>: Failed to establish a new connection: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。',))

In [ ]:


In [36]:
# 获取地图
img = get_map()
imgfile = img[0]
imgedge = img[1]
# 绘制地图
image_file = cbook.get_sample_data(imgfile)  
image = plt.imread(image_file)
fig, ax= plt.subplots(1,1)
ax.imshow(image)
# 绘制用户分布
# 'lng':data['result']['location']['lng']
# 'lat':data['result']['location']['lat']
x = list()
y = list()

d = [11.467, 22.195, 32.429, 41.558, 49.36, 56.269]
for loc in locationslist:
    try:
        if coord_dict[loc]['status'] == 0:
            lng = coord_dict[loc]['result']['location']['lng']+np.random.rand(1)[0]*2-1
            lat = coord_dict[loc]['result']['location']['lat']+np.random.rand(1)[0]*2-1
            tempx =((lng-imgedge['left'])/(imgedge['right']-imgedge['left'])) * 1024
            for i in range(len(d)-1):
                if lat > d[i] and lat <= d[i+1]:
                    tempy = (((d[i+1]-lat)/(d[i+1]-d[i]))/5.0+(1-(i+1)/5.0))*768
            x.append(tempx)
            y.append(tempy)
    except:
        pass

x = np.array(x)
y = np.array(y)
ax.scatter(x, y, color='#FF8C00',alpha=0.1, edgecolors='none')
ax.axis('off')
fig.show()