-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmap_util.py
More file actions
194 lines (164 loc) · 6.67 KB
/
map_util.py
File metadata and controls
194 lines (164 loc) · 6.67 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File : map_util.py
# Author : Yan <yanwong@126.com>
# Date : 01.03.2024
# Last Modified Date: 16.03.2024
# Last Modified By : Yan <yanwong@126.com>
import os
import json
import logging
import re
import requests
import plotly.graph_objects as go
logger = logging.getLogger(__name__)
def locations_center(locations):
lon_lat = [loc.split(',') for loc in locations]
center_lon = sum([float(ll[0]) for ll in lon_lat]) / len(lon_lat)
center_lat = sum([float(ll[1]) for ll in lon_lat]) / len(lon_lat)
return center_lon, center_lat
def same_province(code1, code2):
return int(code1) // 1000 == int(code2) // 1000
def same_city(code1, code2):
return int(code1) // 100 == int(code2) // 100
def plot_markers_map(location_traces, marker_size=10):
fig = go.Figure()
locations = []
for tr in location_traces:
locations.extend(tr['locations'])
lon_lat = [loc.split(',') for loc in tr['locations']]
fig.add_trace(go.Scattermapbox(
name=tr['trace'],
customdata=tr['addresses'],
lat=[ll[1] for ll in lon_lat],
lon=[ll[0] for ll in lon_lat],
mode='markers',
marker=go.scattermapbox.Marker(
size=marker_size
),
hoverinfo='text',
hovertemplate='<b>%{customdata}</b>'
))
if not locations:
logger.warning('No marker locations provided, can not plot.')
return fig
center_lon, center_lat = locations_center(locations)
fig.update_layout(
mapbox_style="open-street-map",
hovermode='closest',
mapbox=dict(
bearing=0,
center=go.layout.mapbox.Center(
lat=center_lat,
lon=center_lon
),
pitch=0,
zoom=9
)
)
return fig
class GaodeGeo(object):
def __init__(self, geocode_url, poi_url, staticmap_url,
staticmap_scale='2', staticmap_size='400*400'):
self.api_key = os.environ['GAODE_API_KEY']
self.geocode_url = geocode_url
self.poi_url = poi_url
self.staticmap_url = staticmap_url
self.staticmap_scale = staticmap_scale # 1: general 2: hd
self.staticmap_size = staticmap_size # largest: 1024*1024
def get_geocode(self, address, city=None):
payload = {'address': address, 'key': self.api_key}
if city:
payload['city'] = city
geocode = []
try:
res = requests.get(self.geocode_url, params=payload)
res_content = json.loads(res.text)
if res_content['status'] == 0:
logger.error('Gaode geocode api error: {}'.format(res_content['info']))
return geocode
geocode = [{
'adcode': g['adcode'],
'citycode': g.get('citycode'),
'city': g.get('city'),
'province': g['province'],
'formatted_address': g['formatted_address']}
for g in res_content['geocodes']]
except Exception as e:
logger.error('Get geocode failed: {}'.format(e))
return geocode
def get_location(self, address, city=None):
payload = {'address': address, 'key': self.api_key}
if city:
payload['city'] = city
location = []
try:
res = requests.get(self.geocode_url, params=payload)
res_content = json.loads(res.text)
if res_content['status'] == 0:
logger.error('Gaode geocode api error: {}'.format(res_content['info']))
return location
geocodes = res_content.get('geocodes')
if geocodes:
if not city:
location = [g['location'] for g in res_content['geocodes']]
else:
for g in geocodes:
lon_lat = g['location']
if re.match(r'(110|120|310|500)\d{3}', city) and \
same_province(city, g['adcode']):
location.append(lon_lat)
elif re.match(r'\d{6}', city) and same_city(city, g['adcode']):
location.append(lon_lat)
elif re.match(r'\d{3,4}', city) and city == g['citycode']:
location.append(lon_lat)
elif city in g['formatted_address']:
location.append(lon_lat)
else:
logger.warning(
f'Gaode does not provide geocodes of {address}:{city}'
)
if not location:
logger.warning(f'Searching POI of {address}:{city}')
payload.update({'keywords': address, 'citylimit': True})
res = requests.get(self.poi_url, params=payload)
res_content = json.loads(res.text)
if res_content['status'] == 0:
logger.error('Gaode poi api error: {}'.format(res_content['info']))
return location
pois = res_content.get('pois')
if pois:
location = [p['location'] for p in pois]
else:
logger.warning(
f'Gaode does not provide poi of {address}:{city}'
)
except Exception as e:
logger.error('Get location failed: {}'.format(e))
return location
def get_staticmap(self, addresses, city, locations=None, marker=False, label=True):
if not locations:
locations = []
for addr in addresses:
coords = self.get_location(addr, city)
locations.append(coords[0])
payload = {'size': self.staticmap_size, 'scale': self.staticmap_scale,
'key': self.api_key}
if marker:
markers = []
for addr, loc in zip(addresses, locations):
marker_style = ','.join(['mid', '0xFF0000', addr[0]])
markers.append(marker_style + ':' + loc)
payload['markers'] = '|'.join(markers)
if label:
labels = []
for addr, loc in zip(addresses, locations):
label_style = ','.join([addr, '0', '1', '20', '0x000000', '0xFF0000'])
labels.append(label_style + ':' + loc)
payload['labels'] = '|'.join(labels)
try:
res = requests.get(self.staticmap_url, params=payload)
except Exception as e:
logger.error('Get staticmap failed: {}'.format(e))
return ''
return res.content