/
tiles.py
205 lines (171 loc) · 8.94 KB
/
tiles.py
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
194
195
196
197
198
199
200
201
202
203
204
205
from __future__ import absolute_import, division, unicode_literals
from types import FunctionType
import param
import numpy as np
from ..core import util
from ..core.dimension import Dimension
from ..core.element import Element2D
class Tiles(Element2D):
"""
The Tiles element represents tile sources, specified as URL
containing different template variables. These variables
correspond to three different formats for specifying the spatial
location and zoom level of the requested tiles:
* Web mapping tiles sources containing {x}, {y}, and {z} variables
* Bounding box tile sources containing {XMIN}, {XMAX}, {YMIN}, {YMAX} variables
* Quadkey tile sources containin a {Q} variable
Tiles are defined in a pseudo-Mercator projection (EPSG:3857)
defined as eastings and northings. Any data overlaid on a tile
source therefore has to be defined in those coordinates or be
projected (e.g. using GeoViews).
"""
kdims = param.List(default=[Dimension('x'), Dimension('y')],
bounds=(2, 2), constant=True, doc="""
The key dimensions of a geometry represent the x- and y-
coordinates in a 2D space.""")
group = param.String(default='Tiles', constant=True)
def __init__(self, data, kdims=None, vdims=None, **params):
try:
from bokeh.models import MercatorTileSource
except:
MercatorTileSource = None
if MercatorTileSource and isinstance(data, MercatorTileSource):
data = data.url
elif not isinstance(data, util.basestring):
raise TypeError('%s data should be a tile service URL not a %s type.'
% (type(self).__name__, type(data).__name__) )
super(Tiles, self).__init__(data, kdims=kdims, vdims=vdims, **params)
def range(self, dim, data_range=True, dimension_range=True):
return np.nan, np.nan
def dimension_values(self, dimension, expanded=True, flat=True):
return np.array([])
@staticmethod
def lon_lat_to_easting_northing(longitude, latitude):
"""
Projects the given longitude, latitude values into Web Mercator
(aka Pseudo-Mercator or EPSG:3857) coordinates.
Longitude and latitude can be provided as scalars, Pandas columns,
or Numpy arrays, and will be returned in the same form. Lists
or tuples will be converted to Numpy arrays.
Args:
longitude
latitude
Returns:
(easting, northing)
Examples:
easting, northing = lon_lat_to_easting_northing(-74,40.71)
easting, northing = lon_lat_to_easting_northing(
np.array([-74]),np.array([40.71])
)
df=pandas.DataFrame(dict(longitude=np.array([-74]),latitude=np.array([40.71])))
df.loc[:, 'longitude'], df.loc[:, 'latitude'] = lon_lat_to_easting_northing(
df.longitude,df.latitude
)
"""
if isinstance(longitude, (list, tuple)):
longitude = np.array(longitude)
if isinstance(latitude, (list, tuple)):
latitude = np.array(latitude)
origin_shift = np.pi * 6378137
easting = longitude * origin_shift / 180.0
with np.errstate(divide='ignore', invalid='ignore'):
northing = np.log(
np.tan((90 + latitude) * np.pi / 360.0)
) * origin_shift / np.pi
return easting, northing
@staticmethod
def easting_northing_to_lon_lat(easting, northing):
"""
Projects the given easting, northing values into
longitude, latitude coordinates.
easting and northing values are assumed to be in Web Mercator
(aka Pseudo-Mercator or EPSG:3857) coordinates.
Args:
easting
northing
Returns:
(longitude, latitude)
"""
if isinstance(easting, (list, tuple)):
easting = np.array(easting)
if isinstance(northing, (list, tuple)):
northing = np.array(northing)
origin_shift = np.pi * 6378137
longitude = easting * 180.0 / origin_shift
with np.errstate(divide='ignore'):
latitude = np.arctan(
np.exp(northing * np.pi / origin_shift)
) * 360.0 / np.pi - 90
return longitude, latitude
# Mapping between patterns to match specified as tuples and tuples containing attributions
_ATTRIBUTIONS = {
('openstreetmap',) : (
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
),
('cartodb',) : (
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, '
'© <a href="https://cartodb.com/attributions">CartoDB</a>'
),
('cartocdn',) : (
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, '
'© <a href="https://cartodb.com/attributions">CartoDB</a>'
),
('stamen', 'com/t') : ( # to match both 'toner' and 'terrain'
'Map tiles by <a href="https://stamen.com">Stamen Design</a>, '
'under <a href="https://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. '
'Data by <a href="https://openstreetmap.org">OpenStreetMap</a>, '
'under <a href="https://www.openstreetmap.org/copyright">ODbL</a>.'
),
('stamen', 'watercolor') : (
'Map tiles by <a href="https://stamen.com">Stamen Design</a>, '
'under <a href="https://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. '
'Data by <a href="https://openstreetmap.org">OpenStreetMap</a>, '
'under <a href="https://creativecommons.org/licenses/by-sa/3.0">CC BY SA</a>.'
),
('wikimedia',) : (
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
),
('arcgis','Terrain') : (
'© <a href="http://downloads.esri.com/ArcGISOnline/docs/tou_summary.pdf">Esri</a>, '
'USGS, NOAA'
),
('arcgis','Reference') : (
'© <a href="http://downloads.esri.com/ArcGISOnline/docs/tou_summary.pdf">Esri</a>, '
'Garmin, USGS, NPS'
),
('arcgis','Imagery') : (
'© <a href="http://downloads.esri.com/ArcGISOnline/docs/tou_summary.pdf">Esri</a>, '
'Earthstar Geographics'
),
('arcgis','NatGeo') : (
'© <a href="http://downloads.esri.com/ArcGISOnline/docs/tou_summary.pdf">Esri</a>, '
'NatGeo, Garmin, HERE, UNEP-WCMC, USGS, NASA, ESA, METI, NRCAN, GEBCO, NOAA, Increment P'
),
('arcgis','USA_Topo') : (
'© <a href="http://downloads.esri.com/ArcGISOnline/docs/tou_summary.pdf">Esri</a>, '
'NatGeo, i-cubed'
)
}
# CartoDB basemaps
CartoDark = lambda: Tiles('https://cartodb-basemaps-4.global.ssl.fastly.net/dark_all/{Z}/{X}/{Y}.png', name="CartoDark")
CartoEco = lambda: Tiles('http://3.api.cartocdn.com/base-eco/{Z}/{X}/{Y}.png', name="CartoEco")
CartoLight = lambda: Tiles('https://cartodb-basemaps-4.global.ssl.fastly.net/light_all/{Z}/{X}/{Y}.png', name="CartoLight")
CartoMidnight = lambda: Tiles('http://3.api.cartocdn.com/base-midnight/{Z}/{X}/{Y}.png', name="CartoMidnight")
# Stamen basemaps
StamenTerrain = lambda: Tiles('http://tile.stamen.com/terrain/{Z}/{X}/{Y}.png', name="StamenTerrain")
StamenTerrainRetina = lambda: Tiles('http://tile.stamen.com/terrain/{Z}/{X}/{Y}@2x.png', name="StamenTerrainRetina")
StamenWatercolor = lambda: Tiles('http://tile.stamen.com/watercolor/{Z}/{X}/{Y}.jpg', name="StamenWatercolor")
StamenToner = lambda: Tiles('http://tile.stamen.com/toner/{Z}/{X}/{Y}.png', name="StamenToner")
StamenTonerBackground = lambda: Tiles('http://tile.stamen.com/toner-background/{Z}/{X}/{Y}.png', name="StamenTonerBackground")
StamenLabels = lambda: Tiles('http://tile.stamen.com/toner-labels/{Z}/{X}/{Y}.png', name="StamenLabels")
# Esri maps (see https://server.arcgisonline.com/arcgis/rest/services for the full list)
EsriImagery = lambda: Tiles('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.jpg', name="EsriImagery")
EsriNatGeo = lambda: Tiles('https://server.arcgisonline.com/ArcGIS/rest/services/NatGeo_World_Map/MapServer/tile/{Z}/{Y}/{X}', name="EsriNatGeo")
EsriUSATopo = lambda: Tiles('https://server.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer/tile/{Z}/{Y}/{X}', name="EsriUSATopo")
EsriTerrain = lambda: Tiles('https://server.arcgisonline.com/ArcGIS/rest/services/World_Terrain_Base/MapServer/tile/{Z}/{Y}/{X}', name="EsriTerrain")
EsriReference = lambda: Tiles('http://server.arcgisonline.com/ArcGIS/rest/services/Reference/World_Reference_Overlay/MapServer/tile/{Z}/{Y}/{X}', name="EsriReference")
ESRI = EsriImagery # For backwards compatibility with gv 1.5
# Miscellaneous
OSM = lambda: Tiles('http://c.tile.openstreetmap.org/{Z}/{X}/{Y}.png', name="OSM")
Wikipedia = lambda: Tiles('https://maps.wikimedia.org/osm-intl/{Z}/{X}/{Y}@2x.png', name="Wikipedia")
tile_sources = {k: v for k, v in locals().items() if isinstance(v, FunctionType) and k != 'ESRI'}