日期:2014-05-16 浏览次数:20420 次
1 :在views.py中
//阿里云地图之地址转地理坐标
http://ditu.aliyun.com/jsdoc/geocode_api.html 里面有返回的数据格式。
//参考geopy
import traceback import xml.dom.minidom from urllib2 import urlopen from sys import version_info from apps.address.models import City from apps.org.models import Vresource from django.utils.encoding import smart_str from xml.parsers.expat import ExpatError ################################Quick Search########################################### def search(request): qs = Vresource.objects.all() q = request.GET.get('q', '') result = util.ali_getlocation(q) result = simplejson.loads(result) distance = request.GET.get('distance', '1') if q != '': myfilter = Q() q = q.split(" ") for i in q: myfilter = myfilter|Q(name__icontains=i)|Q(address__icontains=i)|Q(traffic_info__icontains=i) if result['level'] != -1: geom = fromstr("POINT(%s %s)" % (result['lon'],result['lat'])) distance_from_point = {'km':distance} qs = qs.filter(geometry__distance_lte=(geom, D(**distance_from_point))) myfilter = myfilter|Q(geometry__distance_lte=(geom, D(**distance_from_point))) qs = qs.filter(myfilter) return render_to_response('org/search.html', {'results':qs}, context_instance=RequestContext(request)) ###############################ali_getlocation########################################## def ali_getlocation(address, city_id=1): try: city = City.objects.get(id=city_id) address = smart_str(city.name + address) page = urlopen('http://gc.ditu.aliyun.com/geocoding?a=%s' %address) page = decode_page(page) return page except: print "Unexpected error:" tb = traceback.format_exc() print tb def get_encoding(page, contents=None): # TODO: clean up Py3k support if version_info < (3, 0): charset = page.headers.getparam("charset") or None else: charset = page.headers.get_param("charset") or None if charset: return charset if contents: try: return xml.dom.minidom.parseString(contents).encoding except ExpatError: pass def decode_page(page): contents = page.read() &