def new(request): context = {'YAHOO_MAPS_API_KEY': lazy_key()} if request.method == 'POST': location_form = LocationForm(request.POST) if location_form.is_valid(): y = geocoders.Yahoo(lazy_key()) p = location_form.cleaned_data['place'] try: (place, (lat, lng)) = list(y.geocode(p, exactly_one=False))[0] # Actually returns more than one result but I am taking only the # first result except HTTPError: request.user.message_set.create( message=_('Location not found, Try something else.')) context['location_form'] = location_form return render_to_response("locations/new.html", context, context_instance=RequestContext(request) ) context.update({ 'location': {'place': place, 'latitude': lat, 'longitude': lng}, 'checkin_form': CheckinForm(), }) return render_to_response("locations/checkin.html", context, context_instance=RequestContext(request) ) else: return HttpResponseRedirect(reverse('locations.views.your_locations')) else: return HttpResponseRedirect(reverse('locations.views.your_locations'))
def getYahooResults(place_name): g = geocoders.Yahoo(settings.YAHOO_API_KEY) try: results = g.geocode(place_name, False) formatted_results = [] for result in results: formatted_results.append(formatExternalGeocode('Yahoo', result)) return formatted_results except: return []
def handle(self, *args, **options): """Run geocode.""" appid = getattr(settings, "YAHOO_APP_ID", None) if not "google" in options["geocoder"] and appid is not None: self.geocoder = geocoders.Yahoo(appid) sys.stderr.write("Geocoding with Yahoo world...\n") else: self.geocoder = geocoders.Google() sys.stderr.write("Geocoding with Google maps...\n") for repo in models.Repository.objects.all(): self.geocode_contact(repo)
def prepare_sel(self, assistant, page): address = self.vals["_address"].get_text() if not address: return try: g = geocoders.Yahoo(YID) places = g.geocode(address, exactly_one=False) self.set_page_complete(page, True) except Exception, e: print "Did not find `%s': %s" % (address, e) places = [] lat = lon = 0 self.set_page_complete(page, False)
def setGeoCoders(gCoderStrings, configFilePtr): gCoders = {} config = ConfigParser.RawConfigParser() config.readfp(configFilePtr) for gCoderKey in gCoderStrings: if gCoderKey == "google": gCoders[gCoderKey] = geocoders.GoogleV3() elif gCoderKey == "geocoder.us": gCoders[gCoderKey] = geocoders.GeocoderDotUS() elif gCoderKey == "GeoNames": gCoders[gCoderKey] = geocoders.GeoNames() elif gCoderKey == "MediaWiki": gCoders[gCoderKey] = geocoders.MediaWiki() elif gCoderKey == "yahoo": gCoders[gCoderKey] = geocoders.Yahoo(config.get('API KEYS', gCoderKey)) elif gCoderKey == 'bing': gCoders[gCoderKey] = geocoders.Bing(config.get('API KEYS', gCoderKey)) return gCoders
def addrgeocoder(qdata): q = '* FROM "geotable"' gdata = scraperwiki.sqlite.select(q) gcompanies=[] for gd in gdata: gcompanies.append(c['ocid']) print qdata for c in qdata: if c['ocid'] not in gcompanies: #g = geocoders.Google() time.sleep(2.0) g=geocoders.Yahoo(ykey) place, (lat, lng) = g.geocode(c['address']) c['place']=place c['lat']=lat c['lng']=lng c['latlng']=','.join([str(lat),str(lng)]) scraperwiki.sqlite.save(unique_keys=['ocid'], table_name='geotable', data=c)
def GeocodeCaller(callindex): if "GoogleV3" in callindex: coder = 'geo = geocoders.GoogleV3()' CallID = 0 return coder, CallID elif "Yahoo" in callindex: coder = geocoders.Yahoo( 'gnlL.tLV34HMbeXJAadqK9PFHeedqomQKyWQbC3tRQrZwwvJkVshznyn7LNH.KVp7OE5' ) CallID = 1 return coder, CallID elif "Geocoder.us" in callindex: coder = 'geo = geocoders.GeocoderDotUS()' CallID = 2 return coder, CallID elif "GeoNames" in callindex: coder = 'geo = geocoders.MediaWiki("http://wiki.case.edu/%s")' CallID = 3 return coder, CallID elif "MediaWiki" in callindex and not "Semantic" in callindex: coder = "geo = geocoders.SemanticMediaWiki('http://wiki.case.edu/%s', attributes=['Coordinates'], relations=['Located in'])" CallID = 4 return coder, CallID
def save(self, *args, **kwargs): if self.primary == True: da = DeliveryAddress.objects.filter(user__id=self.user_id).filter( primary=True) if da.count() > 0: da.update(primary=False) if (self.perform_geolocation): y = geocoders.Yahoo( 'dj0yJmk9RUttbDF4S3BmbFo3JmQ9WVdrOVJXSjRaVkpPTm1VbWNHbzlNVEl5TWpJMU9EZzJNZy0tJnM9Y29uc3VtZXJzZWNyZXQmeD1hZA--' ) nb = re.findall(r'(\d+)', self.number) if len(nb) > 0: nb = nb[0] else: nb = self.number try: self.geolocated_address, (self.latitude, self.longitude) = y.geocode( "%s %s, %s, Romania" % (nb, self.street, self.city)) self.geolocation_error = False except: self.geolocation_error = True self.perform_geolocation = True super(DeliveryAddress, self).save(*args, **kwargs) # Call the "real" save() method.
description = row[5] except: parse_errors += 1 continue try: shape = row[3] except: shape = '' try: duration = row[4] except: duration = '' # Geocoders y = geocoders.Yahoo(YAHOO_API_KEY) g = geocoders.Google(GOOGLE_API_KEY) us = geocoders.GeocoderDotUS() # Free, but didn't seem to work well when I tried it # Geocode locations try: # Try Google first place, (latitude, longitude) = list(g.geocode(location, exactly_one=False))[0] except: try: # Then Yahoo place, (latitude, longitude) = list(y.geocode(location, exactly_one=False))[0] except: # Can't find it latitude = '' longitude = ''
def geosearch(request): """ Returns geocoded results in MERCATOR projection First tries coordinates, then a series of geocoding engines """ from geopy import distance if request.method != 'GET': return HttpResponse('Invalid http method; use GET', status=405) try: txt = unicode(request.GET['search']) except: return HttpResponseBadRequest() searchtype = lat = lon = None place = txt try: p = Point(txt) lat, lon, altitude = p searchtype = 'coordinates' except: pass # not a point centerloc = Point("45.54 N 120.64 W") max_dist = 315 # should be everything in WA and Oregon searches = [ geocoders.GeoNames(), geocoders.OpenMapQuest(), geocoders.Yahoo(app_id=settings.APP_NAME), geocoders.Bing(api_key=settings.BING_API_KEY), # these are tried in reverse order, fastest first # TODO thread them and try them as they come in. ] while not (searchtype and lat and lon): # try a geocoder try: g = searches.pop() except IndexError: break # no more search engines left to try try: for p, loc in g.geocode(txt, exactly_one=False): d = distance.distance(loc, centerloc).miles if d < max_dist: # TODO maybe compile these and return the closest to map center? # print g, p, loc place = p lat = loc[0] lon = loc[1] max_dist = d else: pass searchtype = g.__class__.__name__ except: pass if searchtype and lat and lon: # we have a winner cntr = GEOSGeometry('SRID=4326;POINT(%f %f)' % (lon, lat)) cntr.transform(settings.GEOMETRY_DB_SRID) cntrbuf = cntr.buffer(settings.POINT_BUFFER) extent = cntrbuf.extent loc = { 'status': 'ok', 'search': txt, 'place': place, 'type': searchtype, 'extent': extent, 'latlon': [lat, lon], 'center': (cntr[0], cntr[1]), } json_loc = json.dumps(loc) return HttpResponse(json_loc, mimetype='application/json', status=200) else: loc = { 'status': 'failed', 'search': txt, 'type': None, 'extent': None, 'center': None, } json_loc = json.dumps(loc) return HttpResponse(json_loc, mimetype='application/json', status=404)
# Use your own API key here if you use a geocoding service # such as Google or Yahoo! GEOCODING_API_KEY = sys.argv[1] CONNECTIONS_PICKLE = sys.argv[2] # An HTML page that we'll inject Protovis consumable data into HTML_TEMPLATE = '../web_code/protovis/dorling_cartogram/dorling_cartogram.html' OUT = os.path.basename(HTML_TEMPLATE) # Open up your saved connections with extended profile information extended_connections = cPickle.load(open(CONNECTIONS_PICKLE)) locations = [ec.location for ec in extended_connections] g = geocoders.Yahoo(GEOCODING_API_KEY) # Some basic transforms may be necessary for geocoding services to function properly transforms = [('Greater ', ''), (' Area', ''), ('San Francisco Bay', 'San Francisco')] # Tally the frequency of each location freqs = {} for location in locations: # Avoid unnecessary I/O if freqs.has_key(location): freqs[location][1] += 1
print('FAILED TO WRITE', r) subprocess.call("ssconvert ./source/report.xls ./source/report.csv", shell=True) deathtoll = [] with open('./source/report.csv') as f: vals = csv.DictReader(f) for i in vals: deathtoll.append(i) for d in deathtoll: d['Country'] = d["City"].rstrip(",.").split(",")[-1].strip() gmap = geocoders.GoogleV3() ymap = geocoders.Yahoo(YAHOOID) def city2country(x): try: gres = gmap.geocode(x) except: gres = '' if gres: try: place = gres[0].split(",")[-1] except: place = '' else: try: yres = ymap.geocode(x)
def geocode(self, addressText): # Create a progress indicator prog = QProgressDialog("Geocoder", "Cancel", 0, 100, self.iface.getMainWindow()) prog.setMinimumDuration(0) prog.setValue(0) prog.setWindowTitle('Geocoder') prog.setLabelText('Geocoding addresses...') prog.setModal(True) prog.forceShow() # Create a geocoder gc = geocoders.Yahoo(self.key) self.errors = False # # Alternative geocoding engines are possible but I've found # it very difficult to get them to work reliably # # gc = geocoders.Google('API_KEY') # gc = geocoders.VirtualEarth() # gc = geocoders.GeocoderDotUS() # gc = geocoders.GeoNames() # gc = geocoders.MediaWiki("http://wiki.case.edu/%s") # gc = geocoders.SemanticMediaWiki("http://wiki.case.edu/%s", # attributes=['Coordinates'], # relations=['Located in']) # get list of addresses addresses = str(addressText).strip().split('\n') # set progress bar range prog.setRange(0, len(addresses)) # strip out whitespace addresses = [address.strip() for address in addresses] # open files for output and error logging self.fh = open(self.outfile, 'w') self.fh.write('place|lon|lat\n') self.fh.flush() self.fhe = open( os.path.join(tempfile.gettempdir(), "geocode_errors.txt"), 'w') # Loop through and geocode counter = 0 for a in addresses: prog.setValue(counter) if prog.wasCanceled(): self.fh.close() self.fhe.close() print "######## geocoding canceled" break if a != "": try: place, (lat, lon) = gc.geocode(a) outline = '|'.join([place, str(lon), str(lat)]) print outline self.fh.write(outline + "\n") self.fh.flush except Exception, e: self.fhe.write(a + "," + str(e) + "\n") self.fhe.flush() self.errors = True print "Geocode error with", a counter = counter + 1
#!/usr/bin/env python from geopy import geocoders from urllib2 import urlopen import simplejson as json addresses = ["309 Northeast 45th Street, Seattle, WA", "1928 North 45th Street, Seattle, WA", "1635 East Olive Way, Seattle, WA", "1001 East Pike Street, Seattle, WA", "1600 Melrose Avenue, Seattle, WA", "332 15th Avenue East, Seattle, WA"] locations = [] google = geocoders.Google('ABQIAAAAQGbzqUyUyFqkuiq-bCdE0xS4Is1OHekFoVwasBc-LoBG9zsjaBRfMrSYNWNPFnfGOUgXZUAcFXEGrw') yahoo = geocoders.Yahoo('9E7nLOPV34HwxYM0gRxwbasTCb2juFN1IZJh7N8Zz0xJ.RtlGkdwrD.hJ9li.0vjiGGwR234KA--') for address in addresses: try: place, (lat, lng) = google.geocode(address) locations.append((lat, lng)) print str.format("Place: {0}, lat: {1} long: {2}", place, lat, lng) except: print "ERROR" url_builder = 'https://api.foursquare.com/v2/venues/search?ll={0},{1}&query=bar&client_id=MNSGUJNRDL2NU01ELWC4QFE5HOQSC3AI2UMV1PHDL1F2SLOM&client_secret=5AMGF43FMANQSEWQJ124XXWZOXY2RPFGF5BGWJ0F5I2G0PIT' locationdict = {} for location in locations: url = str.format(url_builder, location[0], location[1]) data = urlopen(url).read() jsond = json.loads(data) interesting = jsond['response']['groups'] for group in interesting: for item in group['items']: locationdict[item['id']] = unicode.format(u'{0} {1} {2} {3}', item['id'], item['name'], item['location']['lat'], item['location']['lng']) print len(locationdict)
import csv from geopy import geocoders import time from sys import exit import sys ajdy = 0 f = open("ssRejstrikCoded_opravy2.csv", 'w') with open("ssRejstrik_opravy2.csv", "rb") as csvfile: celler = csv.reader(csvfile, delimiter=";", quotechar='"') for line in celler: ajdy = ajdy + 1 g = geocoders.GoogleV3() y = geocoders.Yahoo('JRzWhaPV34H4SIgp_XjoYtfMlbB9tdZ4AQ_UU3OZ.Iy2WFw0ABQJLYuPVppIolfQ') try: lat = g.geocode(line[1], exactly_one=False)[0][1][0] lng = g.geocode(line[1], exactly_one=False)[0][1][1] except: try: time.sleep(1) lat = g.geocode(line[1], exactly_one=False)[0][1][0] lng = g.geocode(line[1], exactly_one=False)[0][1][1] except: try: time.sleep(3) lat = g.geocode(line[1], exactly_one=False)[0][1][0] lng = g.geocode(line[1], exactly_one=False)[0][1][1] except: try: