Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Función get_map #34

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,16 @@ Prints:
Gire a la izquierda por CALLE RIOS ROSAS
Objetivo logrado


Get static map image
~~~~~~~~~~~~~~~~~~~~

This function gets a static map centered on an address,
as a png image.

Please note this function is quite heavy on the server side, it should be used only for single uses. For an extensive use, please consider cached map tiles extraction
(for an example on this use, please check the ``example_get_map`` in the notebooks directory.

Running the tests
-----------------

Expand Down
296 changes: 296 additions & 0 deletions notebooks/example_get_map.ipynb

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions pycartociudad/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@
from .reverse_geocode import reverse_geocode
from .get_location_info import get_location_info
from .route_between_two_points import route_between_two_points
from .get_map import get_map
176 changes: 176 additions & 0 deletions pycartociudad/get_map.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
"""
Obtain static image map of an address
using cartociudad API
"""

import requests
import urllib
from PIL import Image
from math import radians, cos, sin, asin, sqrt
#import shutil

import geocode

def haversine(lon1: float, lat1: float, lon2: float, lat2: float) -> float:
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])

# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
return c * r

def get_bounding_box(lat: float, lon: float, radiusKm: float, aspectRatio: float) -> list:
"""
Creates the bbox centered on a point with coords (lat,lon)

Parameters
----------
lat: float
central point latitude

lon: float
central point longitude

radiusKm: float
area covered by the map (from center to the sides)

aspectRatio: float
height/width of the map

Returns
-------
bbox: list of float
list of coordinates in EPSG 4326 representation:
[bottom lat, left long, upper lat, right long]

"""

assert radiusKm > 0

delta = 0.5 # This is sort of a magic number ?
deltaLon = radiusKm * delta * haversine(lon, lat, lon+delta, lat) / 2000
deltaLat = radiusKm * delta * haversine(lon, lat, lon, lat+delta) / 2000
deltaLat = deltaLat * aspectRatio

bbox = [lat - deltaLat, # bottom lat
lon - deltaLon, # left lon
lat + deltaLat, # upper lat
lon + deltaLon] # right lon

bbox = ['{:.12f}'.format(x) for x in bbox]

return bbox

def get_layer_img(url: str, searchContent: str) -> Image.Image:
qParams = urllib.parse.urlencode(searchContent)
"""Helper function to download the layer image
"""
# perform request
r = requests.get(url=url, params=qParams, stream=True)

# Get image from the API response
if r.status_code == 200:
r.raw.decode_content = True
layerImg = Image.open(r.raw)
r.close()

return layerImg


def get_map(center: tuple, radius: float,
height: float = 600, width: float = 800,
censalLayer: bool = False,
postLayer: bool = False,
cadastralLayer: bool = False) -> Image.Image:
"""This function downloads a map from CartoCiudad API centered on
a geographical point and returns it as a PIL image.

Parameters
----------
center : tuple of str
(latitude, longitude) coordinates to center the map

radius: float
Map coverage in kilometers

height: int
Returned map height in pixels (default 600)

width: int
Returned map width in pixels (default 800)

censalLayer: bool
Option to add the limit of censal sections and districts to the
base map; note that this layer may not be available at low zoom
levels

postLayer: bool
Option to add the limit of zip code areas to the base map; note
that this layer may not be available at low zoom levels

cadastralLayer: bool
Option to add cadastral information

Returns
-------
image : PIL image of height x width pixels
"""

# build query content
bbox = get_bounding_box(float(center[0]),
float(center[1]),
float(radius),
float(height)/width)

url = 'http://www.ign.es/wms-inspire/ign-base'
searchContent = {'service': 'WMS',
'version': '1.3.0',
'request': 'GetMap',
'format': 'image/png',
'transparent': 'true',
'layers': 'IGNBaseTodo',
'styles': 'default',
'exceptions': 'xml',
'srs': 'EPSG:4326',
'width': str(width),
'height': str(height),
'bbox': ','.join(bbox)
}
bgLayerImg = get_layer_img(url, searchContent)

if postLayer:
url = 'http://www.ign.es/wms-inspire/ign-base'
searchContent = {'service': 'WMS',
'version': '1.3.0',
'request': 'GetMap',
'format': 'image/png',
'transparent': 'true',
'layers': 'codigo-postal',
'styles': 'codigopostal',
'exceptions': 'xml',
'srs': 'EPSG:4326',
'width': str(width),
'height': str(height),
'bbox': ','.join(bbox)
}
fgLayerImg = get_layer_img(url, searchContent)
bgLayerImg.paste(fgLayerImg, (0,0), fgLayerImg.convert('RGBA'))


## Code to download image locally
#r.raw.decode_content = True

#with open('image_name.png', 'wb') as handler:
# shutil.copyfileobj(r.raw, handler)
#del r

return bgLayerImg