Namespaces

Variants
Actions

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

Archived:PyS60 YahooMaps API

From Wiki
Jump to: navigation, search

Archived.pngArchived: This article is archived because it is not considered relevant for third-party developers creating commercial solutions today. If you think this article is still relevant, let us know by adding the template {{ReviewForRemovalFromArchive|user=~~~~|write your reason here}}.

Article Metadata
Code ExampleTested with
Devices(s): E63
Compatibility
Platform(s): S60 3rd Edition
S60 3rd Edition (initial release)
Article
Keywords: YahooMaps,API, REST, GeoLocation
Created: marcelcaraciolo (February, 27, 2010)
Last edited: hamishwillee (01 Jul 2012)

Contents

Introduction=

This article will present a simple Yahoo Maps API Wrapper library for Python for Symbian applications. The main goal is give another option for integrating maps into your Symbian applications in few, easy steps. The next section will present a suitable Python module for accessing the Yahoo Maps services. The module is on his first release so some bugs can be found. Please use the comments tab to describe problems.

Warning.pngWarning: Before using the Yahoo MAPS API, please take a look at the Yahoo Maps Terms Of Use. Check if all restrictions are in accordance to your application. It's important!

How to use it?

PyYahooMaps is designed to be simple. You only have to do is to create a map and display it on in your application.

== Creating a simple map ==

To get a map handler, you have to perform two steps:

First, instantiate a new PyYahooMaps object. Notice there are two parameters, first it's your APP_ID. You have to get one. For that, take a look at the Yahoo Maps Developer's Portal and sign up to get your Yahoo application ID. The second one is the path of where the temporary map image will be stored. The default value is the folder Python placed on the Memory Card. You can change it to where your application files are placed at your phone.

from PyYahooMaps import *
mapHandler = PyYahooMaps(APP_ID,PATH)

Now, you have to define a location for the map. You have two methods for this task. One if you want to define the location by the latitude and longitude values "getMapByCoordinates". The other one is if you want to define it by the address of the location "getMapByAddress". There are some optional parameters that you can change. Take a look at the doc of the methods and more information at the Yahoo Maps RESTP API. Both methods will return the map image url. If something goes wrong, it will be raised an exception with the error message.

#By Address
mp = mapHandler.getMapByAddress('Rua Galante Recife')
 
#By Lat, Long.
mp = mapHandler.getMapByCoordinates(-8.3445,-30.34445)

Once you have defined the location of your map, it is necessary to define the image Handler "imgHandler". The image handler has an important role, it will be the place where you will paint the map. You can pass as argument an appuifw.Canvas or a graphics.Image object. Once you've created the handler, you have to pass it to the PyYahooMaps instance with the showMap() method. Don't forget to pass also the map image url fetched from the last step. The mapX_inc and mapY_inc are optional parameters, in case if you like to display other regions of the map. By default the map will be centered at the location defined by you.

...
imgHandler = appuifw.Canvas(redraw_callback=handle_redraw)
mapHandler.showMap(imgHandler,mp)
 
handle_redraw(None)

After you've called showmap, the map image will be loaded. If the map is correctly loaded, you can actually draw it by using its blit method. And force the painting by calling the redraw_callback defined by you.

The Module

Below you can see the full module of PyYahooMaps

s60yahoomaps.py

__all__ = [ "PyYahooMaps" ]
__author__ = 'caraciol@gmail.com'
__version__ = '0.1'
 
import urllib, e32, graphics, os, os.path
 
 
class PyYahooMaps(object):
'''Simple class for fetching maps from Yahoo Maps webService'''
MMDEFDIR = u''
MAP_FILE = u''
MAP_URL = "http://local.yahooapis.com/MapsService/V1/mapImage?"
 
def __init__(self,api_key,path=u'e:\\python'):
''' Set the PATH for the temp map img file and the Yahoo Application ID '''
PyYahooMaps.MMDEFDIR = path
PyYahooMaps.MAP_FILE = os.path.join(path,u'yahoomap.png')
self.api_key = api_key
 
def naive_xml_parser(self,key, xml):
''' Simple XML parser '''
key = key.lower()
for tag in xml.split("<"):
tokens = tag.split()
if tokens and tokens[0].lower().startswith(key):
return tag.split(">")[1].strip()
return None
 
 
def getMapByAddress(self,address,image_type='png',imageSize=(600,600), zoom=6):
''' Get the map by address (text) and return the url of the map image.
Params:
address: The address of the desired location
image_type: The image format for the map. (The default is png).
imageSize: A tuple with the (height,width) of the requested map
zoom: The zoom level for the map. 1 (street level) to 12 (country level)
'''

params = {'location': address,
'image_type': image_type,
'appid' : self.api_key,
'image_height': str(imageSize[0]),
'image_width': str(imageSize[1]),
'zoom': str(zoom)}
 
try:
url = PyYahooMaps.MAP_URL + urllib.urlencode(params)
res = urllib.urlopen(url).read()
except:
raise Exception('Network Error')
 
img_url = self.naive_xml_parser('result',res)
 
if not img_url:
msg = self.naive_xml_parser('message',res)
raise Exception(msg)
 
return img_url
 
def getMapByCoordinates(self,lat,longT,image_type='png',imageSize=(600,600), zoom=6):
''' Get the map by coordinates (lat,long) and return the url of the map image.
Params:
lat: The latitude of the starting location.
long: The longitude of the starting location.
image_type: The image format for the map. (The default is png).
imageSize: A tuple with the (height,width) of the requested map
zoom: The zoom level for the map. 1 (street level) to 12 (country level)
 
PS:If only one of latitude or longitude is specified, both will be ignored.
'''

params = {'latitude': str(lat),
'longitude': str(longT),
'appid' : self.api_key,
'image_height': str(imageSize[0]),
'image_width': str(imageSize[1]),
'zoom': str(zoom)}
 
try:
url = PyYahooMaps.MAP_URL + urllib.urlencode(params)
res = urllib.urlopen(url).read()
except:
raise Exception('Network Error')
 
img_url = self.naive_xml_parser('result',res)
 
if not img_url:
msg = self.naive_xml_parser('message',res)
raise Exception(msg)
 
return img_url
 
def showMap(self,imgHandler,img_url,mapX_inc=0,mapY_inc=0):
''' Show the map in the screen
Params:
imgHandler: A graphics.Image handler or a Canvas handler where the map will be painted.
img_url: The image url
mapX_inc, mapY_inc : The increment for displaying other parts of the map.
'''

urllib.urlretrieve(img_url,PyYahooMaps.MAP_FILE)
mapimg = graphics.Image.open(PyYahooMaps.MAP_FILE)
map_x = mapimg.size[0] / 2 - imgHandler.size[0] /2
map_y = mapimg.size[1] /2 - imgHandler.size[1] /2
 
if mapimg:
imgHandler.blit(mapimg,target=(0,0),
source=(map_x + mapX_inc,map_y + mapY_inc))
else:
imgHandler.clear((255,255,255))


Application Example

A small application that uses the PyYahooMaps module is below. Copy the files to memory card or memory (depending on your PySymbian version). Don't forget to put the library API in a folder called lib inside of the python folder. If it's not created, create one yourself. Just run it and select which method do you prefer to define the location of your map. After passing the parameters, the map will be displayed on a Canvas.


PyYahooMaps.py

# -*- coding: utf-8 -*-
""""
=======================
PyYahooMaps
=======================
(c) 2010 Marcel Caraciolo
e-mail: caraciol@gmail.com
Released under the GNU General Public License
"""

 
import urllib, e32, graphics, appuifw, key_codes, os, os.path
from s60yahoomaps import *
 
 
def quit():
app_lock.signal()
 
def show_text(txt):
global imgH
imgH.clear((255,255,255))
imgH.text((10, 50), txt,
fill=(0, 0, 255), font="title")
 
def handle_redraw(rect):
global imgH
if imgH:
canvas.blit(imgH)
else:
canvas.clear((255,255,255))
 
def new_mapByGeo():
df = unicode(os.path.join(['c:','Data','python']))
mapHandler = PyYahooMaps(APP_ID,df)
addr = appuifw.multi_query(u"Latitude:", u"Longitude:")
if addr:
try:
lat,log = addr
show_text(u'Loading Map...')
handle_redraw(canvas.size)
mp = mapHandler.getMapByCoordinates(lat,log)
mapHandler.showMap(imgH,mp)
except Exception,err:
show_text(unicode(str(err)))
handle_redraw(None)
 
def new_mapByAddress():
#df = unicode(os.path.join(['c:','Data','python']))
mapHandler = PyYahooMaps(APP_ID)
addr = appuifw.query(u"Address:", "text")
if addr:
try:
show_text(u'Loading Map...')
handle_redraw(canvas.size)
mp = mapHandler.getMapByAddress(addr)
mapHandler.showMap(imgH,mp)
except Exception,err:
show_text(unicode(str(err)))
handle_redraw(None)
 
APP_ID = "YOUR YAHOO APPLICATION ID"
 
 
appuifw.app.exit_key_handler = quit
appuifw.app.title = u'PyYahooMaps!'
appuifw.app.menu = [(u'New location', new_mapByAddress),
(u'New location by Lat/Long', new_mapByGeo),
(u'Quit',quit)]
 
canvas = appuifw.Canvas(redraw_callback=handle_redraw)
imgH = graphics.Image.new(canvas.size)
appuifw.app.body = canvas
show_text(u'Welcome to PyYahooMaps!')
handle_redraw(canvas.size)
app_lock = e32.Ao_lock()
app_lock.wait()

Conclusion

A lot of improvements can be made at this library as also advanced support for another features. Take a look at the Yahoo Maps RESTP API to see more about the REST API. Inspire yourself! This is a simple example of how showing your location. It can be used with location based applications or even on Twitter, since now it has support for geo-tagged tweets!

ScreenShots

Some screen-shots of the demo.

YahooMaps01.jpg        YahooMaps02.jpg        YahooMaps03.jpg        YahooMaps04.jpg        YahooMaps05.jpg       YahooMaps06.jpg

Source Code

Download source code of all examples in this article: File:PyYahooMaps.zip

This page was last modified on 1 July 2012, at 22:51.
62 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×